Upload folder using huggingface_hub (part 3)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- benchmarks/skillbench-venus-e/tasks/005f203871f784b90af3d608/skill/scripts/sdk-fallback.go +234 -0
- benchmarks/skillbench-venus-e/tasks/005f203871f784b90af3d608/skill/scripts/skillopt-lib.sh +371 -0
- benchmarks/skillbench-venus-e/tasks/005f203871f784b90af3d608/skill/test-skillopt-backward-compatibility.sh +14 -0
- benchmarks/skillbench-venus-e/tasks/005f203871f784b90af3d608/skill/test-wrapper-self-call.sh +36 -0
- benchmarks/skillbench-venus-e/tasks/005f203871f784b90af3d608/task.json +100 -0
- benchmarks/skillbench-venus-e/tasks/0140580c4200357f5c54f0fa/evaluator/auto_contract.json +22 -0
- benchmarks/skillbench-venus-e/tasks/0140580c4200357f5c54f0fa/evaluator/auto_entry.py +38 -0
- benchmarks/skillbench-venus-e/tasks/0140580c4200357f5c54f0fa/evaluator/auto_policy.py +133 -0
- benchmarks/skillbench-venus-e/tasks/0140580c4200357f5c54f0fa/evaluator/auto_policy_guard.py +86 -0
- benchmarks/skillbench-venus-e/tasks/0140580c4200357f5c54f0fa/evaluator/autograde_task_check.py +44 -0
- benchmarks/skillbench-venus-e/tasks/0140580c4200357f5c54f0fa/evaluator/check.py +2 -0
- benchmarks/skillbench-venus-e/tasks/0140580c4200357f5c54f0fa/grading/verified_config.json +106 -0
- benchmarks/skillbench-venus-e/tasks/0140580c4200357f5c54f0fa/inputs/requests.txt +6 -0
- benchmarks/skillbench-venus-e/tasks/0140580c4200357f5c54f0fa/instruction.md +1 -0
- benchmarks/skillbench-venus-e/tasks/0140580c4200357f5c54f0fa/skill/SKILL.md +112 -0
- benchmarks/skillbench-venus-e/tasks/0140580c4200357f5c54f0fa/task.json +48 -0
- benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_q1/evaluator/auto_contract.json +8 -0
- benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_q1/evaluator/auto_entry.py +38 -0
- benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_q1/evaluator/auto_policy.py +133 -0
- benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_q1/evaluator/auto_policy_guard.py +86 -0
- benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_q1/evaluator/autograde_task_check.py +12 -0
- benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_q1/evaluator/check.py +2 -0
- benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_q1/evaluator/legacy-task.json +106 -0
- benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_q1/evaluator/legacy_tests/evaluate.py +159 -0
- benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_q1/evaluator/legacy_tests/objective_evaluators.py +1329 -0
- benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_q1/evaluator/legacy_tests/shell_invocations.py +265 -0
- benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_q1/evaluator/legacy_tests/test.sh +8 -0
- benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_q1/evaluator/legacy_tests/verifiers.py +544 -0
- benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_q1/grading/verified_config.json +99 -0
- benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_q1/instruction.md +1 -0
- benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_q1/skill/SKILL.md +31 -0
- benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_q1/task.json +46 -0
- benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/evaluator/auto_contract.json +20 -0
- benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/evaluator/auto_entry.py +38 -0
- benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/evaluator/auto_policy.json +16 -0
- benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/evaluator/auto_policy.py +133 -0
- benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/evaluator/auto_policy_guard.py +86 -0
- benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/evaluator/autograde_task_check.py +3 -0
- benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/evaluator/check.py +2 -0
- benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/evaluator/dependency_scan.py +14 -0
- benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/evaluator/old_check.py +122 -0
- benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/evaluator/r9_contract.py +723 -0
- benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/evaluator/repair_manifest.json +55 -0
- benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/grading/verified_config.json +129 -0
- benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/inputs/orchestrator-state.yaml +16 -0
- benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/instruction.md +12 -0
- benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/skill/SKILL.md +205 -0
- benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/skill/_export_skill_meta.json +20 -0
- benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/skill/references/bmad-commands.md +65 -0
- benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/skill/references/tmux-setup.md +71 -0
benchmarks/skillbench-venus-e/tasks/005f203871f784b90af3d608/skill/scripts/sdk-fallback.go
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
"flag"
|
| 6 |
+
"fmt"
|
| 7 |
+
"os"
|
| 8 |
+
"text/tabwriter"
|
| 9 |
+
|
| 10 |
+
openapi "github.com/alibabacloud-go/darabonba-openapi/client"
|
| 11 |
+
"github.com/alibabacloud-go/tea/tea"
|
| 12 |
+
rkvstore "github.com/alibabacloud-go/r-kvstore-20150101/v2/client"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
type InstanceInfo struct {
|
| 16 |
+
InstanceId string `json:"InstanceId"`
|
| 17 |
+
InstanceName string `json:"InstanceName"`
|
| 18 |
+
InstanceStatus string `json:"InstanceStatus"`
|
| 19 |
+
InstanceClass string `json:"InstanceClass"`
|
| 20 |
+
EngineVersion string `json:"EngineVersion"`
|
| 21 |
+
Capacity int64 `json:"Capacity"`
|
| 22 |
+
Bandwidth int64 `json:"Bandwidth"`
|
| 23 |
+
Connections int64 `json:"Connections"`
|
| 24 |
+
QPS int64 `json:"QPS"`
|
| 25 |
+
NetworkType string `json:"NetworkType"`
|
| 26 |
+
ChargeType string `json:"ChargeType"`
|
| 27 |
+
ConnectionDomain string `json:"ConnectionDomain"`
|
| 28 |
+
Port int64 `json:"Port"`
|
| 29 |
+
PrivateIp string `json:"PrivateIp"`
|
| 30 |
+
ZoneId string `json:"ZoneId"`
|
| 31 |
+
CreateTime string `json:"CreateTime"`
|
| 32 |
+
EndTime string `json:"EndTime"`
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
type InstanceListResult struct {
|
| 36 |
+
Success bool `json:"success"`
|
| 37 |
+
Region string `json:"region"`
|
| 38 |
+
Total int `json:"total"`
|
| 39 |
+
Instances []InstanceInfo `json:"instances"`
|
| 40 |
+
Error string `json:"error,omitempty"`
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
type DescribeInstancesResponse struct {
|
| 44 |
+
Instances struct {
|
| 45 |
+
KVStoreInstance []InstanceInfo `json:"KVStoreInstance"`
|
| 46 |
+
} `json:"Instances"`
|
| 47 |
+
TotalCount int `json:"TotalCount"`
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
func main() {
|
| 51 |
+
jsonOutput := flag.Bool("json", false, "Output in JSON format (machine-readable)")
|
| 52 |
+
flag.Parse()
|
| 53 |
+
|
| 54 |
+
if !*jsonOutput {
|
| 55 |
+
fmt.Println("=== SDK Fallback Path for Redis/Tair Operations ===")
|
| 56 |
+
fmt.Println()
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
credentials := loadCredentials()
|
| 60 |
+
if credentials == nil {
|
| 61 |
+
if *jsonOutput {
|
| 62 |
+
printJSONError("credentials missing", "Create .env file or set ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, ALIBABA_CLOUD_REGION_ID")
|
| 63 |
+
} else {
|
| 64 |
+
fmt.Fprintf(os.Stderr, "ERROR: Failed to load credentials\n")
|
| 65 |
+
fmt.Fprintf(os.Stderr, "Suggestion: Create .env file or set environment variables\n")
|
| 66 |
+
}
|
| 67 |
+
os.Exit(1)
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
config := &openapi.Config{
|
| 71 |
+
AccessKeyId: tea.String(credentials.AccessKeyId),
|
| 72 |
+
AccessKeySecret: tea.String(credentials.AccessKeySecret),
|
| 73 |
+
RegionId: tea.String(credentials.RegionId),
|
| 74 |
+
Endpoint: tea.String("r-kvstore.aliyuncs.com"),
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
c, err := rkvstore.NewClient(config)
|
| 78 |
+
if err != nil {
|
| 79 |
+
if *jsonOutput {
|
| 80 |
+
printJSONError("client creation failed", "Check credentials and network connectivity")
|
| 81 |
+
} else {
|
| 82 |
+
handleError("Client creation failed", err, "Check credentials and network connectivity")
|
| 83 |
+
}
|
| 84 |
+
os.Exit(1)
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
req := &rkvstore.DescribeInstancesRequest{
|
| 88 |
+
RegionId: tea.String(credentials.RegionId),
|
| 89 |
+
PageSize: tea.Int32(100),
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
resp, err := c.DescribeInstances(req)
|
| 93 |
+
if err != nil {
|
| 94 |
+
if *jsonOutput {
|
| 95 |
+
printJSONError("describe instances failed",
|
| 96 |
+
fmt.Sprintf("Region=%s, check region validity and RAM permissions", credentials.RegionId))
|
| 97 |
+
} else {
|
| 98 |
+
handleError("DescribeInstances failed", err,
|
| 99 |
+
fmt.Sprintf("Region=%s, check region validity and RAM permissions", credentials.RegionId))
|
| 100 |
+
}
|
| 101 |
+
os.Exit(1)
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
data, err := json.Marshal(resp.Body)
|
| 105 |
+
if err != nil {
|
| 106 |
+
if *jsonOutput {
|
| 107 |
+
printJSONError("JSON marshal failed", "Internal error")
|
| 108 |
+
} else {
|
| 109 |
+
handleError("JSON marshaling failed", err, "Internal error")
|
| 110 |
+
}
|
| 111 |
+
os.Exit(1)
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
var result DescribeInstancesResponse
|
| 115 |
+
if err := json.Unmarshal(data, &result); err != nil {
|
| 116 |
+
if *jsonOutput {
|
| 117 |
+
printJSONError("JSON unmarshal failed", "Internal error")
|
| 118 |
+
} else {
|
| 119 |
+
handleError("JSON unmarshaling failed", err, "Internal error")
|
| 120 |
+
}
|
| 121 |
+
os.Exit(1)
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
if *jsonOutput {
|
| 125 |
+
displayJSONResult(credentials.RegionId, result)
|
| 126 |
+
} else {
|
| 127 |
+
displayResults(credentials.RegionId, result)
|
| 128 |
+
}
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
type Credentials struct {
|
| 132 |
+
AccessKeyId string
|
| 133 |
+
AccessKeySecret string
|
| 134 |
+
RegionId string
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
func loadCredentials() *Credentials {
|
| 138 |
+
cred := &Credentials{}
|
| 139 |
+
|
| 140 |
+
cred.AccessKeyId = os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
|
| 141 |
+
cred.AccessKeySecret = os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
|
| 142 |
+
cred.RegionId = os.Getenv("ALIBABA_CLOUD_REGION_ID")
|
| 143 |
+
|
| 144 |
+
if cred.AccessKeyId == "" || cred.AccessKeySecret == "" || cred.RegionId == "" {
|
| 145 |
+
return nil
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
return cred
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
func printJSONError(context, suggestion string) {
|
| 152 |
+
result := InstanceListResult{
|
| 153 |
+
Success: false,
|
| 154 |
+
Region: os.Getenv("ALIBABA_CLOUD_REGION_ID"),
|
| 155 |
+
Error: fmt.Sprintf("%s: %s", context, suggestion),
|
| 156 |
+
}
|
| 157 |
+
out, _ := json.MarshalIndent(result, "", " ")
|
| 158 |
+
fmt.Println(string(out))
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
func handleError(context string, err error, suggestion string) {
|
| 162 |
+
fmt.Fprintf(os.Stderr, "\nERROR: %s\n", context)
|
| 163 |
+
fmt.Fprintf(os.Stderr, "Details: %v\n", err)
|
| 164 |
+
fmt.Fprintf(os.Stderr, "Suggestion: %s\n", suggestion)
|
| 165 |
+
fmt.Fprintf(os.Stderr, "\nTroubleshooting Steps:\n")
|
| 166 |
+
fmt.Fprintf(os.Stderr, "1. Run pre-flight check: bash scripts/preflight-check.sh\n")
|
| 167 |
+
fmt.Fprintf(os.Stderr, "2. Check .env file exists and contains valid credentials\n")
|
| 168 |
+
fmt.Fprintf(os.Stderr, "3. Verify network connectivity to r-kvstore.aliyuncs.com\n")
|
| 169 |
+
fmt.Fprintf(os.Stderr, "4. Check RAM permissions for r-kvstore:* actions\n")
|
| 170 |
+
fmt.Fprintf(os.Stderr, "5. Source preflight env: source scripts/preflight-env.sh\n")
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
func displayJSONResult(region string, result DescribeInstancesResponse) {
|
| 174 |
+
instances := result.Instances.KVStoreInstance
|
| 175 |
+
if instances == nil {
|
| 176 |
+
instances = []InstanceInfo{}
|
| 177 |
+
}
|
| 178 |
+
output := InstanceListResult{
|
| 179 |
+
Success: true,
|
| 180 |
+
Region: region,
|
| 181 |
+
Total: len(instances),
|
| 182 |
+
Instances: instances,
|
| 183 |
+
}
|
| 184 |
+
out, _ := json.MarshalIndent(output, "", " ")
|
| 185 |
+
fmt.Println(string(out))
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
func displayResults(region string, result DescribeInstancesResponse) {
|
| 189 |
+
fmt.Printf("\n=== Redis/Tair 实例列表 (区域: %s) ===\n", region)
|
| 190 |
+
fmt.Printf("总计: %d 个实例\n\n", result.TotalCount)
|
| 191 |
+
|
| 192 |
+
w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0)
|
| 193 |
+
fmt.Fprintln(w, "序号\t实例ID\t实例名称\t状态\t规格\t版本\t容量(MB)\t网络类型\t付费类型")
|
| 194 |
+
fmt.Fprintln(w, "----\t--------\t----------\t----\t----\t----\t---------\t----------\t--------")
|
| 195 |
+
|
| 196 |
+
for i, instance := range result.Instances.KVStoreInstance {
|
| 197 |
+
fmt.Fprintf(w, "%d\t%s\t%s\t%s\t%s\t%s\t%d\t%s\t%s\n",
|
| 198 |
+
i+1,
|
| 199 |
+
instance.InstanceId,
|
| 200 |
+
instance.InstanceName,
|
| 201 |
+
instance.InstanceStatus,
|
| 202 |
+
instance.InstanceClass,
|
| 203 |
+
instance.EngineVersion,
|
| 204 |
+
instance.Capacity,
|
| 205 |
+
instance.NetworkType,
|
| 206 |
+
instance.ChargeType,
|
| 207 |
+
)
|
| 208 |
+
}
|
| 209 |
+
w.Flush()
|
| 210 |
+
|
| 211 |
+
fmt.Println("\n详细信息:")
|
| 212 |
+
fmt.Println("=====================================")
|
| 213 |
+
for i, instance := range result.Instances.KVStoreInstance {
|
| 214 |
+
fmt.Printf("\n[%d] %s (%s)\n", i+1, instance.InstanceName, instance.InstanceId)
|
| 215 |
+
fmt.Printf(" 状态: %s\n", instance.InstanceStatus)
|
| 216 |
+
fmt.Printf(" 规格: %s\n", instance.InstanceClass)
|
| 217 |
+
fmt.Printf(" 版本: Redis %s\n", instance.EngineVersion)
|
| 218 |
+
fmt.Printf(" 容量: %d MB\n", instance.Capacity)
|
| 219 |
+
fmt.Printf(" 带宽: %d MB/s\n", instance.Bandwidth)
|
| 220 |
+
fmt.Printf(" 最大连接数: %d\n", instance.Connections)
|
| 221 |
+
fmt.Printf(" QPS: %d\n", instance.QPS)
|
| 222 |
+
fmt.Printf(" 网络类型: %s\n", instance.NetworkType)
|
| 223 |
+
fmt.Printf(" 付费类型: %s\n", instance.ChargeType)
|
| 224 |
+
fmt.Printf(" 连接地址: %s:%d\n", instance.ConnectionDomain, instance.Port)
|
| 225 |
+
fmt.Printf(" 私网IP: %s\n", instance.PrivateIp)
|
| 226 |
+
fmt.Printf(" 可用区: %s\n", instance.ZoneId)
|
| 227 |
+
fmt.Printf(" 创建时间: %s\n", instance.CreateTime)
|
| 228 |
+
if instance.ChargeType == "PrePaid" {
|
| 229 |
+
fmt.Printf(" 到期时间: %s\n", instance.EndTime)
|
| 230 |
+
}
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
fmt.Println("\n=== SDK Fallback Execution Successful ===")
|
| 234 |
+
}
|
benchmarks/skillbench-venus-e/tasks/005f203871f784b90af3d608/skill/scripts/skillopt-lib.sh
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# SkillOpt Core Library for alicloud-redis-ops
|
| 3 |
+
# Self-repair and dynamic optimization for Redis CLI commands.
|
| 4 |
+
# Compatible with macOS (BSD grep/sed) and Linux.
|
| 5 |
+
|
| 6 |
+
_SKILLOPT_LIB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 7 |
+
_SKILLOPT_SKILL_ROOT="$(dirname "$_SKILLOPT_LIB_DIR")"
|
| 8 |
+
|
| 9 |
+
# SKILLOPT_ENABLED resolved in skillopt_init (env / .env / flags)
|
| 10 |
+
SKILLOPT_REPORT=false
|
| 11 |
+
SKILLOPT_RETRIES=3
|
| 12 |
+
SKILLOPT_BACKOFF=(1 2 4)
|
| 13 |
+
SKILLOPT_LAST_OUTPUT=""
|
| 14 |
+
SKILLOPT_PARAMS=()
|
| 15 |
+
|
| 16 |
+
# 熔断器配置
|
| 17 |
+
SKILLOPT_CB_ENABLED=false
|
| 18 |
+
SKILLOPT_CB_THRESHOLD=5
|
| 19 |
+
SKILLOPT_CB_COOLDOWN=60
|
| 20 |
+
|
| 21 |
+
# Observability configuration
|
| 22 |
+
SKILLOPT_LOG_FORMAT="${SKILLOPT_LOG_FORMAT:-text}" # text | json
|
| 23 |
+
SKILLOPT_METRICS_DIR="${SKILLOPT_METRICS_DIR:-}" # empty = no export
|
| 24 |
+
SKILLOPT_LOG_LABEL="Redis-SkillOpt"
|
| 25 |
+
SKILLOPT_SKILL_TAG="alicloud-redis-ops"
|
| 26 |
+
|
| 27 |
+
# Langfuse tracing configuration
|
| 28 |
+
SKILLOPT_LANGFUSE_ENABLED="${SKILLOPT_LANGFUSE_ENABLED:-false}"
|
| 29 |
+
LANGFUSE_HOST="${LANGFUSE_HOST:-}"
|
| 30 |
+
LANGFUSE_PUBLIC_KEY="${LANGFUSE_PUBLIC_KEY:-}"
|
| 31 |
+
LANGFUSE_SECRET_KEY="${LANGFUSE_SECRET_KEY:-}"
|
| 32 |
+
|
| 33 |
+
# Session & Trace state
|
| 34 |
+
SKILLOPT_SESSION_ID="${SKILLOPT_SESSION_ID:-}"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# --- Shared SkillOpt core (alicloud-skillopt-ops) ---
|
| 38 |
+
if [[ -z "${_SKILLOPT_SKILLS_ROOT:-}" ]]; then
|
| 39 |
+
_SKILLOPT_SKILLS_ROOT="${ALIYUN_SKILLS_ROOT:-$(git -C "$_SKILLOPT_SKILL_ROOT" rev-parse --show-toplevel 2>/dev/null || dirname "$_SKILLOPT_SKILL_ROOT")}"
|
| 40 |
+
fi
|
| 41 |
+
_SKILLOPT_SHARED_ROOT="${SKILLOPT_SHARED_ROOT:-${_SKILLOPT_SKILLS_ROOT}/alicloud-skillopt-ops}"
|
| 42 |
+
# shellcheck source=/dev/null
|
| 43 |
+
source "${_SKILLOPT_SHARED_ROOT}/scripts/skillopt-paths.sh"
|
| 44 |
+
# shellcheck source=/dev/null
|
| 45 |
+
source "${_SKILLOPT_SHARED_ROOT}/scripts/skillopt-core-lib.sh"
|
| 46 |
+
SKILLOPT_LOG_FILE="${ALIBABA_CLOUD_LOG_DIR:-${_SKILLOPT_LOGS_DIR:-$_SKILLOPT_RUNTIME_ROOT}}/redis-skillopt-$(date +%Y%m%d).log"
|
| 47 |
+
SKILLOPT_RUNTIME_DATA="${_SKILLOPT_METRICS_DATA_DIR:-$_SKILLOPT_RUNTIME_ROOT}/redis-skillopt-runtime.json"
|
| 48 |
+
# --- End shared core ---
|
| 49 |
+
|
| 50 |
+
skillopt_repair_error() {
|
| 51 |
+
local error_code="$1"; shift
|
| 52 |
+
local product="$1"; shift
|
| 53 |
+
local action="$1"; shift
|
| 54 |
+
local params=("$@")
|
| 55 |
+
|
| 56 |
+
if [[ "$SKILLOPT_ENABLED" != "true" ]]; then
|
| 57 |
+
skillopt_log "repair skipped (disabled): $error_code"
|
| 58 |
+
return 1
|
| 59 |
+
fi
|
| 60 |
+
|
| 61 |
+
if ! skillopt_is_readonly_action "$action"; then
|
| 62 |
+
skillopt_log "repair skipped (mutating action): $product $action"
|
| 63 |
+
return 1
|
| 64 |
+
fi
|
| 65 |
+
|
| 66 |
+
skillopt_log "repair start: error=$error_code cmd=$product $action"
|
| 67 |
+
local repair_failed=1
|
| 68 |
+
|
| 69 |
+
case "$error_code" in
|
| 70 |
+
Throttling.User|Throttling)
|
| 71 |
+
skillopt_log "repair[Throttling]: exponential backoff + raise Period"
|
| 72 |
+
local attempt=0
|
| 73 |
+
local new_params=("${params[@]}")
|
| 74 |
+
|
| 75 |
+
local has_period=false
|
| 76 |
+
for p in "${new_params[@]}"; do
|
| 77 |
+
[[ "$p" == "--Period" ]] && has_period=true
|
| 78 |
+
done
|
| 79 |
+
$has_period || new_params+=("--Period" "300")
|
| 80 |
+
|
| 81 |
+
for sleep_s in "${SKILLOPT_BACKOFF[@]}"; do
|
| 82 |
+
skillopt_log "repair[Throttling]: wait ${sleep_s}s (attempt $((attempt+1)))"
|
| 83 |
+
sleep "$sleep_s"
|
| 84 |
+
if skillopt_run_aliyun "$product" "$action" "${new_params[@]}"; then
|
| 85 |
+
skillopt_log "repair[Throttling]: succeeded after ${sleep_s}s"
|
| 86 |
+
repair_failed=0
|
| 87 |
+
break
|
| 88 |
+
fi
|
| 89 |
+
attempt=$((attempt + 1))
|
| 90 |
+
done
|
| 91 |
+
;;
|
| 92 |
+
|
| 93 |
+
InvalidParameter|InvalidJSON|MissingParameter|MissingParameter.RegionId|InvalidParameter.RegionId|MissingRegionId|DataRetentionExceeded|InvalidTimeRange|TimeRangeExceeded|InvalidParameter.StartTime|InvalidParameter.TimeRange)
|
| 94 |
+
skillopt_log "repair[InvalidParam]: check RegionId, TimeRange, or JSON params"
|
| 95 |
+
local new_params=()
|
| 96 |
+
local skip_next=false
|
| 97 |
+
local modified=false
|
| 98 |
+
|
| 99 |
+
# 1. RegionId missing check
|
| 100 |
+
local has_region=false
|
| 101 |
+
for p in "${params[@]}"; do
|
| 102 |
+
[[ "$p" == "--RegionId" ]] && has_region=true
|
| 103 |
+
done
|
| 104 |
+
|
| 105 |
+
# 2. TimeRange/DataRetention check
|
| 106 |
+
local is_retention_error=false
|
| 107 |
+
if [[ "$error_code" == "DataRetentionExceeded" || "$error_code" == "InvalidTimeRange" || "$error_code" == "TimeRangeExceeded" || "$error_code" == "InvalidParameter.StartTime" || "$error_code" == "InvalidParameter.TimeRange" ]]; then
|
| 108 |
+
is_retention_error=true
|
| 109 |
+
elif [[ "$SKILLOPT_LAST_OUTPUT" == *"retention"* || "$SKILLOPT_LAST_OUTPUT" == *"31 days"* || "$SKILLOPT_LAST_OUTPUT" == *"30 days"* || "$SKILLOPT_LAST_OUTPUT" == *"exceed"* ]]; then
|
| 110 |
+
for p in "${params[@]}"; do
|
| 111 |
+
[[ "$p" == "--StartTime" ]] && is_retention_error=true
|
| 112 |
+
done
|
| 113 |
+
fi
|
| 114 |
+
|
| 115 |
+
local is_region_error=false
|
| 116 |
+
if [[ "$error_code" == "MissingParameter.RegionId" || "$error_code" == "InvalidParameter.RegionId" || "$error_code" == "MissingRegionId" ]]; then
|
| 117 |
+
is_region_error=true
|
| 118 |
+
elif [[ "$error_code" == "MissingParameter" ]] && ! $has_region; then
|
| 119 |
+
is_region_error=true
|
| 120 |
+
fi
|
| 121 |
+
|
| 122 |
+
if $is_region_error; then
|
| 123 |
+
skillopt_log "repair[RegionId]: RegionId is missing, attempting auto-completion"
|
| 124 |
+
local region="${ALIBABA_CLOUD_REGION_ID:-}"
|
| 125 |
+
if [[ -z "$region" ]]; then
|
| 126 |
+
if _SKILLOPT_INTERNAL_REPAIR=1 skillopt_run_aliyun ecs DescribeRegions --output cols=RegionId rows=Regions.Region 2>/dev/null; then
|
| 127 |
+
region="$(printf '%s' "$SKILLOPT_LAST_OUTPUT" | head -n 1 | tr -d ' \r\n')"
|
| 128 |
+
else
|
| 129 |
+
region=""
|
| 130 |
+
fi
|
| 131 |
+
fi
|
| 132 |
+
if [[ -z "$region" ]]; then
|
| 133 |
+
region="cn-hangzhou"
|
| 134 |
+
fi
|
| 135 |
+
skillopt_log "repair[RegionId]: using region $region"
|
| 136 |
+
new_params=("${params[@]}" "--RegionId" "$region")
|
| 137 |
+
modified=true
|
| 138 |
+
elif $is_retention_error; then
|
| 139 |
+
skillopt_log "repair[TimeRange]: Data retention exceeded, shrinking StartTime to 14 days ago"
|
| 140 |
+
skillopt_get_14_days_ago() {
|
| 141 |
+
local format_type="$1"
|
| 142 |
+
local now_s
|
| 143 |
+
now_s="$(date +%s)"
|
| 144 |
+
local fourteen_days_ago_s=$((now_s - 14 * 86400))
|
| 145 |
+
if [[ "$format_type" == "ms" ]]; then
|
| 146 |
+
echo "$((fourteen_days_ago_s * 1000))"
|
| 147 |
+
elif [[ "$format_type" == "s" ]]; then
|
| 148 |
+
echo "$fourteen_days_ago_s"
|
| 149 |
+
else
|
| 150 |
+
if command -v python3 &>/dev/null; then
|
| 151 |
+
python3 -c "import datetime; print((datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=14)).strftime('%Y-%m-%dT%H:%M:%SZ'))"
|
| 152 |
+
else
|
| 153 |
+
date -u -d '14 days ago' +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u -v-14d +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || echo "2026-06-02T00:00:00Z"
|
| 154 |
+
fi
|
| 155 |
+
fi
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
for ((i=0; i<${#params[@]}; i++)); do
|
| 159 |
+
local arg="${params[$i]}"
|
| 160 |
+
if $skip_next; then
|
| 161 |
+
skip_next=false
|
| 162 |
+
continue
|
| 163 |
+
fi
|
| 164 |
+
if [[ "$arg" == "--StartTime" && $((i+1)) -lt ${#params[@]} ]]; then
|
| 165 |
+
local val="${params[$((i+1))]}"
|
| 166 |
+
local new_val=""
|
| 167 |
+
if [[ "$val" =~ ^[0-9]+$ ]]; then
|
| 168 |
+
if [[ ${#val} -ge 12 ]]; then
|
| 169 |
+
new_val="$(skillopt_get_14_days_ago "ms")"
|
| 170 |
+
else
|
| 171 |
+
new_val="$(skillopt_get_14_days_ago "s")"
|
| 172 |
+
fi
|
| 173 |
+
else
|
| 174 |
+
new_val="$(skillopt_get_14_days_ago "string")"
|
| 175 |
+
fi
|
| 176 |
+
new_params+=("--StartTime" "$new_val")
|
| 177 |
+
skip_next=true
|
| 178 |
+
modified=true
|
| 179 |
+
skillopt_log "repair[TimeRange]: adjusted StartTime from $val to $new_val"
|
| 180 |
+
else
|
| 181 |
+
new_params+=("$arg")
|
| 182 |
+
fi
|
| 183 |
+
done
|
| 184 |
+
else
|
| 185 |
+
# Fallback to JSON parameter validation
|
| 186 |
+
local jp=()
|
| 187 |
+
for ((i=0; i<${#params[@]}; i++)); do
|
| 188 |
+
local arg="${params[$i]}"
|
| 189 |
+
if $skip_next; then
|
| 190 |
+
skip_next=false
|
| 191 |
+
continue
|
| 192 |
+
fi
|
| 193 |
+
|
| 194 |
+
local is_json_param=false
|
| 195 |
+
for p in "${jp[@]}"; do
|
| 196 |
+
if [[ "$arg" == "--$p" ]]; then
|
| 197 |
+
is_json_param=true
|
| 198 |
+
break
|
| 199 |
+
fi
|
| 200 |
+
done
|
| 201 |
+
|
| 202 |
+
if $is_json_param && [[ $((i+1)) -lt ${#params[@]} ]]; then
|
| 203 |
+
local raw_val="${params[$((i+1))]}"
|
| 204 |
+
local fixed_val
|
| 205 |
+
fixed_val="$(printf '%s' "$raw_val" | jq -c '.' 2>/dev/null || echo "$raw_val")"
|
| 206 |
+
if [[ "$raw_val" != "$fixed_val" ]]; then
|
| 207 |
+
new_params+=("$arg" "$fixed_val")
|
| 208 |
+
modified=true
|
| 209 |
+
else
|
| 210 |
+
new_params+=("$arg" "$raw_val")
|
| 211 |
+
fi
|
| 212 |
+
skip_next=true
|
| 213 |
+
else
|
| 214 |
+
new_params+=("$arg")
|
| 215 |
+
fi
|
| 216 |
+
done
|
| 217 |
+
fi
|
| 218 |
+
|
| 219 |
+
if $modified; then
|
| 220 |
+
skillopt_log "repair[InvalidParam]: retrying with modified params"
|
| 221 |
+
if skillopt_run_aliyun "$product" "$action" "${new_params[@]}"; then
|
| 222 |
+
skillopt_log "repair[InvalidParam]: succeeded"
|
| 223 |
+
repair_failed=0
|
| 224 |
+
fi
|
| 225 |
+
else
|
| 226 |
+
skillopt_log "repair[InvalidParam]: no modifications applied"
|
| 227 |
+
fi
|
| 228 |
+
;;
|
| 229 |
+
|
| 230 |
+
ResourceNotFound)
|
| 231 |
+
skillopt_log "repair[ResourceNotFound]: verify resource existence"
|
| 232 |
+
local instance_id=""
|
| 233 |
+
for ((i=0; i<${#params[@]}; i++)); do
|
| 234 |
+
if [[ "${params[$i]}" == "--Dimensions" && $((i+1)) -lt ${#params[@]} ]]; then
|
| 235 |
+
instance_id="$(printf '%s' "${params[$((i+1))]}" | jq -r '.[0].instanceId // empty' 2>/dev/null)"
|
| 236 |
+
break
|
| 237 |
+
fi
|
| 238 |
+
done
|
| 239 |
+
local region="${ALIBABA_CLOUD_REGION_ID:-}"
|
| 240 |
+
for ((i=0; i<${#params[@]}; i++)); do
|
| 241 |
+
[[ "${params[$i]}" == "--RegionId" ]] && region="${params[$((i+1))]}" && break
|
| 242 |
+
done
|
| 243 |
+
|
| 244 |
+
if [[ -n "$instance_id" && -n "$region" ]]; then
|
| 245 |
+
skillopt_log "repair[ResourceNotFound]: checking $instance_id in $region"
|
| 246 |
+
local check_cmd=""
|
| 247 |
+
if [[ "$instance_id" =~ ^i- ]]; then
|
| 248 |
+
check_cmd="aliyun ecs DescribeInstances --RegionId $region --InstanceIds [\"$instance_id\"]"
|
| 249 |
+
elif [[ "$instance_id" =~ ^rm- ]]; then
|
| 250 |
+
check_cmd="aliyun rds DescribeDBInstances --RegionId $region --DBInstanceId $instance_id"
|
| 251 |
+
elif [[ "$instance_id" =~ ^r- ]]; then
|
| 252 |
+
check_cmd="aliyun r-kvstore DescribeInstances --RegionId $region --InstanceIds $instance_id"
|
| 253 |
+
elif [[ "$instance_id" =~ ^lb- ]]; then
|
| 254 |
+
check_cmd="aliyun slb DescribeLoadBalancers --RegionId $region --LoadBalancerId $instance_id"
|
| 255 |
+
elif [[ "$instance_id" =~ ^dds- ]]; then
|
| 256 |
+
check_cmd="aliyun dds DescribeDBInstances --RegionId $region --DBInstanceId $instance_id"
|
| 257 |
+
elif [[ "$instance_id" =~ ^pc- ]]; then
|
| 258 |
+
check_cmd="aliyun polardb DescribeDBClusters --RegionId $region --DBClusterId $instance_id"
|
| 259 |
+
elif [[ "$instance_id" =~ ^eip- ]]; then
|
| 260 |
+
check_cmd="aliyun vpc DescribeEipAddresses --RegionId $region --AllocationId $instance_id"
|
| 261 |
+
elif [[ "$instance_id" =~ ^vpc- ]]; then
|
| 262 |
+
check_cmd="aliyun vpc DescribeVpcs --RegionId $region --VpcId $instance_id"
|
| 263 |
+
fi
|
| 264 |
+
|
| 265 |
+
local exists=false
|
| 266 |
+
if [[ -n "$check_cmd" ]]; then
|
| 267 |
+
skillopt_log "repair[ResourceNotFound]: executing probe: $check_cmd"
|
| 268 |
+
if eval "$check_cmd" >/dev/null 2>&1; then
|
| 269 |
+
exists=true
|
| 270 |
+
fi
|
| 271 |
+
else
|
| 272 |
+
# Fallback for generic/unrecognized instance prefixes: assume true and retry
|
| 273 |
+
exists=true
|
| 274 |
+
fi
|
| 275 |
+
|
| 276 |
+
if $exists; then
|
| 277 |
+
skillopt_log "repair[ResourceNotFound]: resource exists, retrying"
|
| 278 |
+
if skillopt_run_aliyun "$product" "$action" "${params[@]}"; then
|
| 279 |
+
repair_failed=0
|
| 280 |
+
fi
|
| 281 |
+
else
|
| 282 |
+
skillopt_log "repair[ResourceNotFound]: resource $instance_id not found in $region"
|
| 283 |
+
fi
|
| 284 |
+
else
|
| 285 |
+
skillopt_log "repair[ResourceNotFound]: cannot extract instanceId/region, skipping"
|
| 286 |
+
fi
|
| 287 |
+
;;
|
| 288 |
+
|
| 289 |
+
Forbidden|NoPermission)
|
| 290 |
+
skillopt_log "repair[Forbidden]: RAM policy suggestion"
|
| 291 |
+
skillopt_log "HINT: Ensure AK has policy: {\"Action\":[\"redis:*\"],\"Effect\":\"Allow\",\"Resource\":\"*\"}"
|
| 292 |
+
;;
|
| 293 |
+
|
| 294 |
+
ConnectionTimeout|ConnectTimeout)
|
| 295 |
+
skillopt_log "repair[Timeout]: retrying with increased timeout"
|
| 296 |
+
local new_params=("${params[@]}")
|
| 297 |
+
local has_timeout=false
|
| 298 |
+
for p in "${new_params[@]}"; do
|
| 299 |
+
[[ "$p" == "--Timeout" ]] && has_timeout=true
|
| 300 |
+
done
|
| 301 |
+
$has_timeout || new_params+=("--Timeout" "30")
|
| 302 |
+
if skillopt_run_aliyun "$product" "$action" "${new_params[@]}"; then
|
| 303 |
+
repair_failed=0
|
| 304 |
+
fi
|
| 305 |
+
;;
|
| 306 |
+
|
| 307 |
+
QuotaExceeded)
|
| 308 |
+
skillopt_log "Quota exceeded for Redis"
|
| 309 |
+
;;
|
| 310 |
+
|
| 311 |
+
*)
|
| 312 |
+
skillopt_log "repair: no handler for $error_code"
|
| 313 |
+
;;
|
| 314 |
+
esac
|
| 315 |
+
|
| 316 |
+
skillopt_update_runtime "$error_code" "$repair_failed"
|
| 317 |
+
|
| 318 |
+
if [[ $repair_failed -eq 0 ]]; then
|
| 319 |
+
printf '%s\n' "$SKILLOPT_LAST_OUTPUT"
|
| 320 |
+
fi
|
| 321 |
+
|
| 322 |
+
return $repair_failed
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
skillopt_optimize_params() {
|
| 326 |
+
local product="$1"
|
| 327 |
+
local action="$2"
|
| 328 |
+
|
| 329 |
+
if [[ "$SKILLOPT_ENABLED" != "true" ]]; then
|
| 330 |
+
return 0
|
| 331 |
+
fi
|
| 332 |
+
|
| 333 |
+
skillopt_log "optimize: $product $action (${#SKILLOPT_PARAMS[@]} params)"
|
| 334 |
+
|
| 335 |
+
local runtime_data='{}'
|
| 336 |
+
[[ -f "$SKILLOPT_RUNTIME_DATA" ]] && \
|
| 337 |
+
runtime_data="$(jq '.' "$SKILLOPT_RUNTIME_DATA" 2>/dev/null || echo '{}')"
|
| 338 |
+
|
| 339 |
+
local error_rate query_count
|
| 340 |
+
error_rate="$(printf '%s' "$runtime_data" | jq -r '.error_rate // 0')"
|
| 341 |
+
query_count="$(printf '%s' "$runtime_data" | jq -r '.query_count // 0')"
|
| 342 |
+
|
| 343 |
+
if awk "BEGIN { exit !($error_rate > 5) }" 2>/dev/null; then
|
| 344 |
+
if [[ $SKILLOPT_RETRIES -lt 6 ]]; then
|
| 345 |
+
SKILLOPT_RETRIES=$((SKILLOPT_RETRIES + 1))
|
| 346 |
+
skillopt_log "optimize: error_rate=${error_rate}% → retries=$SKILLOPT_RETRIES"
|
| 347 |
+
else
|
| 348 |
+
skillopt_log "optimize: error_rate=${error_rate}% (retries capped at $SKILLOPT_RETRIES)"
|
| 349 |
+
fi
|
| 350 |
+
fi
|
| 351 |
+
|
| 352 |
+
if awk "BEGIN { exit !($query_count > 1000) }" 2>/dev/null; then
|
| 353 |
+
local has_period=false
|
| 354 |
+
for p in "${SKILLOPT_PARAMS[@]+"${SKILLOPT_PARAMS[@]}"}"; do
|
| 355 |
+
[[ "$p" == "--Period" ]] && has_period=true
|
| 356 |
+
done
|
| 357 |
+
if ! $has_period; then
|
| 358 |
+
SKILLOPT_PARAMS+=("--Period" "300")
|
| 359 |
+
skillopt_log "optimize: high query_count=${query_count} → added --Period 300"
|
| 360 |
+
fi
|
| 361 |
+
fi
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
if [ -n "$BASH_VERSION" ]; then
|
| 366 |
+
export -f skillopt_init skillopt_log skillopt_is_readonly_action \
|
| 367 |
+
skillopt_extract_error_code skillopt_run_aliyun skillopt_repair_error \
|
| 368 |
+
skillopt_update_runtime skillopt_optimize_params \
|
| 369 |
+
skillopt_session_init skillopt_trace_start skillopt_trace_span \
|
| 370 |
+
skillopt_trace_span_io skillopt_trace_end
|
| 371 |
+
fi
|
benchmarks/skillbench-venus-e/tasks/005f203871f784b90af3d608/skill/test-skillopt-backward-compatibility.sh
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
SDIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 4 |
+
echo "Testing alicloud-redis-ops SkillOpt backward compatibility"
|
| 5 |
+
echo "=============================================="
|
| 6 |
+
echo -n "Test 1: Native command... "
|
| 7 |
+
aliyun redis DescribeInstances --RegionId cn-hangzhou &>/dev/null && echo "✓" || echo "✓ (format valid)"
|
| 8 |
+
echo -n "Test 2: SKILLOPT_ENABLED env + wrapper... "
|
| 9 |
+
SKILLOPT_ENABLED=true "$SDIR/scripts/redis-skillopt-wrapper.sh" DescribeInstances --RegionId cn-hangzhou --PageSize 1 &>/dev/null && echo "✓" || echo "✗"
|
| 10 |
+
echo -n "Test 3: Wrapper exists... "
|
| 11 |
+
[ -f "$SDIR/scripts/redis-skillopt-wrapper.sh" ] && echo "✓" || echo "✗"
|
| 12 |
+
echo -n "Test 4: Library exists... "
|
| 13 |
+
[ -f "$SDIR/scripts/skillopt-lib.sh" ] && echo "✓" || echo "✗"
|
| 14 |
+
echo "=============================================="
|
benchmarks/skillbench-venus-e/tasks/005f203871f784b90af3d608/skill/test-wrapper-self-call.sh
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Regression test: alicloud-redis-ops wrapper does not self-block.
|
| 3 |
+
set -euo pipefail
|
| 4 |
+
|
| 5 |
+
SDIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 6 |
+
WRAPPER="$SDIR/scripts/redis-skillopt-wrapper.sh"
|
| 7 |
+
|
| 8 |
+
PASS=0; FAIL=0
|
| 9 |
+
ok() { echo " [PASS] $1"; PASS=$((PASS + 1)); }
|
| 10 |
+
bad() { echo " [FAIL] $1"; FAIL=$((FAIL + 1)); }
|
| 11 |
+
|
| 12 |
+
echo "=== alicloud-redis-ops wrapper self-call regression ==="
|
| 13 |
+
|
| 14 |
+
STUB_DIR="$(mktemp -d)"
|
| 15 |
+
trap "rm -rf $STUB_DIR" EXIT
|
| 16 |
+
cat >"$STUB_DIR/aliyun" <<'EOF'
|
| 17 |
+
#!/bin/bash
|
| 18 |
+
echo '{"Instances":{"KVStoreInstance":[{"InstanceId":"r-stub"}]}}'
|
| 19 |
+
exit 0
|
| 20 |
+
EOF
|
| 21 |
+
chmod +x "$STUB_DIR/aliyun"
|
| 22 |
+
|
| 23 |
+
if PATH="$STUB_DIR:$PATH" bash "$WRAPPER" DescribeInstances --RegionId cn-hangzhou >/tmp/wrap.out 2>&1; then
|
| 24 |
+
if grep -q 'WRAPPER REQUIRED' /tmp/wrap.out; then
|
| 25 |
+
bad "wrapper hit P0 self-block"
|
| 26 |
+
elif grep -q 'r-stub' /tmp/wrap.out; then
|
| 27 |
+
ok "wrapper reached aliyun stub (r-stub)"
|
| 28 |
+
else
|
| 29 |
+
bad "wrapper produced unexpected output: $(cat /tmp/wrap.out | head -3)"
|
| 30 |
+
fi
|
| 31 |
+
else
|
| 32 |
+
bad "wrapper failed (rc=$?)"
|
| 33 |
+
fi
|
| 34 |
+
|
| 35 |
+
echo "=== Results: $PASS passed, $FAIL failed ==="
|
| 36 |
+
[[ $FAIL -eq 0 ]]
|
benchmarks/skillbench-venus-e/tasks/005f203871f784b90af3d608/task.json
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": "skill-search-synthesis-v1",
|
| 3 |
+
"task_id": "005f203871f784b90af3d608",
|
| 4 |
+
"environment": {
|
| 5 |
+
"image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
|
| 6 |
+
"network": "none"
|
| 7 |
+
},
|
| 8 |
+
"query_id": "005f203871f784b90af3d608",
|
| 9 |
+
"outputs": [
|
| 10 |
+
"inspection.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": "815466fb96caf480f7504d688057a4c6198c5ba85946c226b055f240de84ef4d",
|
| 23 |
+
"files": {
|
| 24 |
+
"SKILL.md": "df0c664b17b90bbb4dbba1b1276dfaaae72e324b47913826d6a6c98f20dff536",
|
| 25 |
+
"TODO.md": "98862c8d80ce80c462b5ded758eb327fde2573c2940d63dcac98c3cd425e5a8d",
|
| 26 |
+
"assets/eval_queries.json": "98020e65ca65e35124c95a15f4e90c58b76be3094c61372f92cc58ee5b86e92d",
|
| 27 |
+
"references/api-sdk-usage.md": "1fb13cc79ab736cfe01dcb687c4e1512abd21f4721209dd9e853ad6271530135",
|
| 28 |
+
"references/ci-compatibility.md": "4fa78238e1a3a05a9389fad12579d5ff0acbb04eb7c9c40076cbe5e50d34dc84",
|
| 29 |
+
"references/cli-usage.md": "b5c443fc9dc97358abe91e9aa802fa44e241f87e1ad0483c1a318e5c1b66eb84",
|
| 30 |
+
"references/core-concepts.md": "95ad71233c29af2904d0357da05ac08d1f9e93099c38fadc36b2fcce619362ea",
|
| 31 |
+
"references/integration.md": "d2bdb5a518d44ec6728b5a12975d6093c1c01ee1dcd6921470ad6b9938a62d56",
|
| 32 |
+
"references/intelligent-inspection.md": "60383a6500876e1bc302b499aa3045b5c4b578827238dc1d161d981ddb837f89",
|
| 33 |
+
"references/knowledge-base.md": "81ee82795ce9b7215cc93e63acfde418352a39a0ade062658b352a856e5d97a2",
|
| 34 |
+
"references/monitoring.md": "26465ea4edb66028c3cbe3f0a84c0d2a4239284fc8b5c6693019974c9eaddfa6",
|
| 35 |
+
"references/observability.md": "1857b819541965b747c262207939c8370e2cecc0eb662b9da02d13443ebc989a",
|
| 36 |
+
"references/polling-patterns.md": "623aaaf7ec7271ab42b74acf692c0752a42d8866c05403d5cffa03ecb13b8705",
|
| 37 |
+
"references/prompt-examples.md": "6674b77b3024716f3e44c26548de69e28a3cb278d0083a96a91f27c3f788b6bd",
|
| 38 |
+
"references/prompt-templates.md": "2f78c1390c7012376632beade5cf01ac116b9e96d9ebd0a679d43cebdd2b3971",
|
| 39 |
+
"references/redis-cli-execution.md": "0e8fe461521a99fe37902fe9619ac2e53ac5768da4af3befc6120caf4954954a",
|
| 40 |
+
"references/redis-cli-install.md": "17920cc30ee452f9832d601d787bf3ff220305d43ff9ce19bea6fc29384a60a4",
|
| 41 |
+
"references/rubric.md": "123a62010c115d2118c481cb4c66035daa4b96f1ac5c56e84371afa29b44f5b0",
|
| 42 |
+
"references/skillopt-integration.md": "03413cfa42489e5296c4f58ea3cd37edb13d73c600cf39f265fcbe1c80924f96",
|
| 43 |
+
"references/troubleshooting.md": "0a9ec4059ce8ec95159d8cb1922170a8afeb1788e1f15afa45b174d161717d64",
|
| 44 |
+
"references/well-architected-assessment.md": "d5c33e732e6eb656c18cc029027aaedd5217dee1659f87f17d598e5958496a20",
|
| 45 |
+
"scripts/go.mod": "a3368537256c6de15ae91f9836cb839d5d9986d18cfca2d8c189605886bd4813",
|
| 46 |
+
"scripts/harness-lib.sh": "cbaf7f9c7427a0700be1dc85d15afe7ae36afa3a7fae55454cd606d959734d0c",
|
| 47 |
+
"scripts/preflight-check.sh": "d248e65e6c27835d3543f6fb420c4980187d2ecad0d8ba37f624614d00a8e931",
|
| 48 |
+
"scripts/preflight-env.sh": "57fb069cb6a50a0480e8dd0d40a0be6c91053ee59c95edcce0b7ffd1fc5999c7",
|
| 49 |
+
"scripts/preflight-result.json": "51832deb8af80b84ab5a1a0295513b5e714ce89ef81e45ef9a853538eaa7d5df",
|
| 50 |
+
"scripts/redis-cli-install.sh": "8d1c2622cd7394c09574bde914f26118730e4f58bf12ce924c13e7c63c8f88e6",
|
| 51 |
+
"scripts/redis-harness-wrapper.sh": "8645efbee60251ef4f0f0abc926c4946134f290e2de8011eb08f0336cb02ed31",
|
| 52 |
+
"scripts/redis-skillopt-wrapper.sh": "a7336cad91d7906f96b99f1c398959e2c80c5d29cee5a8101fdf62ac28842a6e",
|
| 53 |
+
"scripts/sdk-fallback.go": "08baa0de05362a0b0d92505018b6b7c8f089e33a58fb074f62467d2d722318ad",
|
| 54 |
+
"scripts/skillopt-lib.sh": "cbaf7f9c7427a0700be1dc85d15afe7ae36afa3a7fae55454cd606d959734d0c",
|
| 55 |
+
"test-skillopt-backward-compatibility.sh": "142960f76f797114a9b5cb94d612cca5237d80ce714ad05e242dcb0693fca86b",
|
| 56 |
+
"test-wrapper-self-call.sh": "43e4468f2a55de42b38a5b8ee9cc77171527344f8e7394a6b19942a4fe163aa4"
|
| 57 |
+
}
|
| 58 |
+
},
|
| 59 |
+
"workspace": {
|
| 60 |
+
"candidate_mode": "workspace",
|
| 61 |
+
"input_mappings": [
|
| 62 |
+
{
|
| 63 |
+
"source": "inputs/instance.",
|
| 64 |
+
"workspace_target": "instance.",
|
| 65 |
+
"sha256": "f80280e5aaf7974646ec4bf606828702adc98d41d522d19c74ae0a2519d5d858"
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"source": "inputs/monitor.",
|
| 69 |
+
"workspace_target": "monitor.",
|
| 70 |
+
"sha256": "02bb4ce780306dd8839b8d70c75715cea5b261fc0b41d5c37d002654146e6d68"
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"source": "inputs/backups.",
|
| 74 |
+
"workspace_target": "backups.",
|
| 75 |
+
"sha256": "7e306704f33742dbfa130502b9e8c3cbea690b1faf969550ed70ae8b4e999064"
|
| 76 |
+
}
|
| 77 |
+
],
|
| 78 |
+
"skill_packages": [
|
| 79 |
+
{
|
| 80 |
+
"package_path": "skill",
|
| 81 |
+
"content_hash": "815466fb96caf480f7504d688057a4c6198c5ba85946c226b055f240de84ef4d"
|
| 82 |
+
}
|
| 83 |
+
]
|
| 84 |
+
},
|
| 85 |
+
"automatic_evaluation_runtime": {
|
| 86 |
+
"stdlib_only": true,
|
| 87 |
+
"forbid_network": true,
|
| 88 |
+
"forbid_subprocess": false,
|
| 89 |
+
"forbid_native": true,
|
| 90 |
+
"owner_ids": [
|
| 91 |
+
"0"
|
| 92 |
+
],
|
| 93 |
+
"runtime_owner_ids": [
|
| 94 |
+
"0"
|
| 95 |
+
],
|
| 96 |
+
"execution_budget_seconds": 60,
|
| 97 |
+
"total_evaluation_budget_seconds": 420,
|
| 98 |
+
"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."
|
| 99 |
+
}
|
| 100 |
+
}
|
benchmarks/skillbench-venus-e/tasks/0140580c4200357f5c54f0fa/evaluator/auto_contract.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"expected_check_ids": [
|
| 3 |
+
"0",
|
| 4 |
+
"1",
|
| 5 |
+
"2",
|
| 6 |
+
"3",
|
| 7 |
+
"4",
|
| 8 |
+
"5",
|
| 9 |
+
"6",
|
| 10 |
+
"7"
|
| 11 |
+
],
|
| 12 |
+
"criterion_weights": {
|
| 13 |
+
"0": 1,
|
| 14 |
+
"1": 1,
|
| 15 |
+
"2": 1,
|
| 16 |
+
"3": 1,
|
| 17 |
+
"4": 1,
|
| 18 |
+
"5": 1,
|
| 19 |
+
"6": 1,
|
| 20 |
+
"7": 1
|
| 21 |
+
}
|
| 22 |
+
}
|
benchmarks/skillbench-venus-e/tasks/0140580c4200357f5c54f0fa/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/0140580c4200357f5c54f0fa/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/0140580c4200357f5c54f0fa/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/0140580c4200357f5c54f0fa/evaluator/autograde_task_check.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 2 |
+
import json, os
|
| 3 |
+
|
| 4 |
+
def run():
|
| 5 |
+
checks = []
|
| 6 |
+
expected = [
|
| 7 |
+
("grids+foundation", ".la-grid--3-1"),
|
| 8 |
+
("grids+foundation", ".la-cardrow + .la-card"),
|
| 9 |
+
("kpi", ".la-dashboard + data-span"),
|
| 10 |
+
("chrome", ".la-header.--glass"),
|
| 11 |
+
("print-hero", "@page + .la-cover + .la-break-* + .no-print"),
|
| 12 |
+
("print-hero", ".la-device (set --dev-*)"),
|
| 13 |
+
]
|
| 14 |
+
data = None
|
| 15 |
+
try:
|
| 16 |
+
with open("/candidate/routing.json") as f:
|
| 17 |
+
data = json.load(f)
|
| 18 |
+
except Exception as e:
|
| 19 |
+
data = None
|
| 20 |
+
err = str(e)
|
| 21 |
+
if not isinstance(data, list):
|
| 22 |
+
checks.append({"id":"0","passed":False,"reason":"routing.json missing or does not parse as a JSON array"})
|
| 23 |
+
# pad remaining checks as failed
|
| 24 |
+
for i in range(1, 8):
|
| 25 |
+
checks.append({"id":str(i),"passed":False,"reason":"routing.json missing or invalid"})
|
| 26 |
+
print(json.dumps({"checks":checks}))
|
| 27 |
+
return
|
| 28 |
+
checks.append({"id":"0","passed":len(data)==6,"reason":f"array length {len(data)}, expected 6"})
|
| 29 |
+
keys_ok = isinstance(data, list) and all(isinstance(o,dict) and set(o.keys())=={"id","sibling","scaffold"} for o in data)
|
| 30 |
+
checks.append({"id":"1","passed":keys_ok,"reason":"each object must have exactly keys id, sibling, scaffold"})
|
| 31 |
+
for i,(sib,scaf) in enumerate(expected):
|
| 32 |
+
idx = i+2
|
| 33 |
+
if i >= len(data) or not isinstance(data[i], dict):
|
| 34 |
+
checks.append({"id":str(idx),"passed":False,"reason":"missing object"})
|
| 35 |
+
continue
|
| 36 |
+
o = data[i]
|
| 37 |
+
sib_ok = str(o.get("sibling","")).strip().lower() == sib
|
| 38 |
+
scaf_ok = str(o.get("scaffold","")).strip() == scaf
|
| 39 |
+
ok = type(o.get("id")) is int and o["id"] == i+1 and sib_ok and scaf_ok
|
| 40 |
+
reason = "correct" if ok else f"expected sibling={sib}, scaffold={scaf}; got sibling={o.get('sibling')!r}, scaffold={o.get('scaffold')!r}"
|
| 41 |
+
checks.append({"id":str(idx),"passed":ok,"reason":reason})
|
| 42 |
+
print(json.dumps({"checks":checks}))
|
| 43 |
+
|
| 44 |
+
run()
|
benchmarks/skillbench-venus-e/tasks/0140580c4200357f5c54f0fa/evaluator/check.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from auto_entry import main
|
| 2 |
+
raise SystemExit(main())
|
benchmarks/skillbench-venus-e/tasks/0140580c4200357f5c54f0fa/grading/verified_config.json
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema": "audited-verified-grader-v1",
|
| 3 |
+
"query_id": "0140580c4200357f5c54f0fa",
|
| 4 |
+
"selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
|
| 5 |
+
"grader_file_sha256": {
|
| 6 |
+
"auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa",
|
| 7 |
+
"check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
|
| 8 |
+
"auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0",
|
| 9 |
+
"autograde_task_check.py": "3691f3406c7145d90d7cb3d15f83c4fda0dbb0784cb3dce7347e2ab4c4a03793",
|
| 10 |
+
"auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932",
|
| 11 |
+
"auto_contract.json": "1973ab59d6c798839dc76976e2cf6ec72facd1f60b833ebabefed0e297a7ccd7"
|
| 12 |
+
},
|
| 13 |
+
"runtime_requirements": {
|
| 14 |
+
"candidate_mode": "workspace",
|
| 15 |
+
"candidate_snapshot_copy_to_ephemeral_app": true,
|
| 16 |
+
"container_private_entry": "/grader/check.py",
|
| 17 |
+
"environment": {
|
| 18 |
+
"CANDIDATE_DIR": "/candidate",
|
| 19 |
+
"CANDIDATE_ROOT": "/candidate",
|
| 20 |
+
"MYBENCH_ANSWER": "/answer.txt",
|
| 21 |
+
"MYBENCH_ANSWER_FILE": "/answer.txt",
|
| 22 |
+
"MYBENCH_CANDIDATE": "/candidate",
|
| 23 |
+
"MYBENCH_EPHEMERAL_APP": "1",
|
| 24 |
+
"MYBENCH_EPHEMERAL_WORKSPACE": "1",
|
| 25 |
+
"MYBENCH_RUN_METADATA": "/run_metadata.json",
|
| 26 |
+
"MYBENCH_SOURCE_TASK": "/source",
|
| 27 |
+
"SOURCE_TASK_DIR": "/source"
|
| 28 |
+
},
|
| 29 |
+
"expected_check_ids": [
|
| 30 |
+
"0",
|
| 31 |
+
"1",
|
| 32 |
+
"2",
|
| 33 |
+
"3",
|
| 34 |
+
"4",
|
| 35 |
+
"5",
|
| 36 |
+
"6",
|
| 37 |
+
"7"
|
| 38 |
+
],
|
| 39 |
+
"external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer",
|
| 40 |
+
"external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored",
|
| 41 |
+
"image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
|
| 42 |
+
"image_included": false,
|
| 43 |
+
"legacy_adapter": false,
|
| 44 |
+
"mounts_readonly": [
|
| 45 |
+
"/candidate",
|
| 46 |
+
"/source",
|
| 47 |
+
"/grader",
|
| 48 |
+
"/answer.txt"
|
| 49 |
+
],
|
| 50 |
+
"network": "none",
|
| 51 |
+
"original_declared_resources": {
|
| 52 |
+
"agent": {
|
| 53 |
+
"cpu_memory_basis": "source_runtime_container_limits",
|
| 54 |
+
"cpus": 2,
|
| 55 |
+
"disk_mib": 10240,
|
| 56 |
+
"memory_mib": 4096,
|
| 57 |
+
"timeout_disk_basis": "advisory_not_measured_or_enforced",
|
| 58 |
+
"timeout_sec": 1200
|
| 59 |
+
},
|
| 60 |
+
"oracle": {
|
| 61 |
+
"basis": "advisory_reference_copy",
|
| 62 |
+
"timeout_sec": 120
|
| 63 |
+
},
|
| 64 |
+
"source_agent": {
|
| 65 |
+
"command_timeout_sec": 60,
|
| 66 |
+
"max_steps": 16
|
| 67 |
+
},
|
| 68 |
+
"verifier": {
|
| 69 |
+
"basis": "original_python_evaluator_enforced_limits",
|
| 70 |
+
"cpus": 1,
|
| 71 |
+
"memory_mib": 1024,
|
| 72 |
+
"pids": 64,
|
| 73 |
+
"timeout_sec": 60,
|
| 74 |
+
"tmpfs_mib": 128
|
| 75 |
+
}
|
| 76 |
+
},
|
| 77 |
+
"private_entry": "evaluator/check.py",
|
| 78 |
+
"private_tree_environment_tokens": [],
|
| 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 |
+
"1": 1,
|
| 95 |
+
"2": 1,
|
| 96 |
+
"3": 1,
|
| 97 |
+
"4": 1,
|
| 98 |
+
"5": 1,
|
| 99 |
+
"6": 1,
|
| 100 |
+
"7": 1
|
| 101 |
+
},
|
| 102 |
+
"grader_timeout_seconds": 600,
|
| 103 |
+
"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."
|
| 104 |
+
},
|
| 105 |
+
"engine": "portable_verified_v1"
|
| 106 |
+
}
|
benchmarks/skillbench-venus-e/tasks/0140580c4200357f5c54f0fa/inputs/requests.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
1. A content page with a left sidebar and a 3-1 grid
|
| 2 |
+
2. A row of equal cards aligned via subgrid
|
| 3 |
+
3. A metrics dashboard with 12-col placement
|
| 4 |
+
4. A sticky glass page header
|
| 5 |
+
5. A printable A4 invoice with token tints preserved
|
| 6 |
+
6. A device screenshot frame
|
benchmarks/skillbench-venus-e/tasks/0140580c4200357f5c54f0fa/instruction.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
You are acting as a layout routing assistant. Using the routing matrix below, classify each of the following 6 user requests into the correct sibling and scaffold class. For each request, output a JSON object with keys "id", "sibling", and "scaffold". Requests: (1) "A content page with a left sidebar and a 3-1 grid" (2) "A row of equal cards aligned via subgrid" (3) "A metrics dashboard with 12-col placement" (4) "A sticky glass page header" (5) "A printable A4 invoice with token tints preserved" (6) "A device screenshot frame". Write the result to routing.json as a JSON array of these 6 objects, in order.
|
benchmarks/skillbench-venus-e/tasks/0140580c4200357f5c54f0fa/skill/SKILL.md
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: amvcp-layout
|
| 3 |
+
description: "Router skill for layouts — layout surface split into 5 focused siblings (grids+foundation, shells, kpi, chrome, print-hero). Use when the user wants ANY layout task (grid, sidebar, dashboard, KPI, TOC, sticky header, print, hero, device mockup) to route to the right sibling. Trigger with 'layout', 'grid', 'sidebar', 'dashboard', 'TOC', 'print', 'A4', 'sticky header', 'glassmorphism', 'hero', 'device mockup', 'KPI', 'IDE shell'."
|
| 4 |
+
license: MIT
|
| 5 |
+
compatibility: "Browser (no build step). amvcp-layout.css + amvcp-layout.js + amvcp-runtime.js + amvcp-designmd.js colocated with the HTML."
|
| 6 |
+
metadata:
|
| 7 |
+
author: Emasoft
|
| 8 |
+
---
|
| 9 |
+
|
| 10 |
+
# Layout (Router)
|
| 11 |
+
|
| 12 |
+
> **Parent umbrella:** [`skills/amvcp-visual-communication/SKILL.md`](../amvcp-visual-communication/SKILL.md) — load the umbrella first to route between the 13 visual categories.
|
| 13 |
+
|
| 14 |
+
## Overview
|
| 15 |
+
|
| 16 |
+
This is the **router** for the layout surface. The layout catalogue was split into 5 focused siblings so each sibling's embedded TOC fits naturally and progressive discovery works without per-link contortion. The router emits no markup itself — pick the right sibling per the table below.
|
| 17 |
+
|
| 18 |
+
## Prerequisites
|
| 19 |
+
|
| 20 |
+
- `scripts/amvcp-layout.css` linked (every sibling's presets ship here).
|
| 21 |
+
- `scripts/amvcp-layout.js` loaded for chrome (sticky header IO sentinel, scroll-spy TOC) and for shells (collapse toggle). Pure-CSS siblings (grids foundation, kpi, print-hero) don't need it.
|
| 22 |
+
- The DESIGN.md engine (`scripts/amvcp-designmd.js`) wired — every `--vc-*` token comes from here.
|
| 23 |
+
- `scripts/amvcp-runtime.js` for selection + the no-nested-scrollbars backstop.
|
| 24 |
+
- Python 3.12+ for `scripts/amvcp-select.py`.
|
| 25 |
+
|
| 26 |
+
## Instructions
|
| 27 |
+
|
| 28 |
+
1. Match the user's request to a row in the routing matrix below.
|
| 29 |
+
2. Load the matched sibling SKILL.md (often one row covers it; combine when needed).
|
| 30 |
+
3. Follow the sibling's Instructions; come back to this router only to route a second concern.
|
| 31 |
+
|
| 32 |
+
## Routing matrix
|
| 33 |
+
|
| 34 |
+
| Request shape | Sibling | Scaffold class |
|
| 35 |
+
|---|---|---|
|
| 36 |
+
| spatial tokens / `--la-*` aliases / named gaps / reading measure | [grids+foundation](../amvcp-layout-grids/SKILL.md) | `var(--vc-space-N)` / `var(--la-*)` / `ch` |
|
| 37 |
+
| content + sidebar (2-1 or 3-1) | [grids+foundation](../amvcp-layout-grids/SKILL.md) | `.la-grid--2-1` / `.la-grid--3-1` |
|
| 38 |
+
| row of equal cards aligned via subgrid | [grids+foundation](../amvcp-layout-grids/SKILL.md) | `.la-cardrow` + `.la-card` |
|
| 39 |
+
| gallery / tile grid (auto-fill) | [grids+foundation](../amvcp-layout-grids/SKILL.md) | custom `auto-fill` grid |
|
| 40 |
+
| long article / report body | [grids+foundation](../amvcp-layout-grids/SKILL.md) | `.la-article` + `.la-article__wide` / `__bleed` |
|
| 41 |
+
| mobile collapse breakpoint | [grids+foundation](../amvcp-layout-grids/SKILL.md) | `@media (max-width: 768px)` |
|
| 42 |
+
| RTL-correct layout | [grids+foundation](../amvcp-layout-grids/SKILL.md) | `dir="rtl"` on root |
|
| 43 |
+
| no-nested-scrollbars rule | [grids+foundation](../amvcp-layout-grids/SKILL.md) | `overflow: visible` / `clip` |
|
| 44 |
+
| selection-atoms contract | [grids+foundation](../amvcp-layout-grids/SKILL.md) | `markLayoutAtoms()` |
|
| 45 |
+
| IDE / 3-panel tool UI + collapsible sidebar | [shells](../amvcp-layout-shells/SKILL.md) | `.la-ide` + `[data-la-toggle]` |
|
| 46 |
+
| at-a-glance KPI / metric strip | [kpi](../amvcp-layout-kpi/SKILL.md) | `.la-kpi-row` |
|
| 47 |
+
| metrics dashboard (12-col placement) | [kpi](../amvcp-layout-kpi/SKILL.md) | `.la-dashboard` + `data-span` |
|
| 48 |
+
| persistent page header (opaque) | [chrome](../amvcp-layout-chrome/SKILL.md) | `.la-header` |
|
| 49 |
+
| persistent page header (glass) | [chrome](../amvcp-layout-chrome/SKILL.md) | `.la-header.--glass` |
|
| 50 |
+
| sticky controls bar above a section | [chrome](../amvcp-layout-chrome/SKILL.md) | custom sticky toolbar |
|
| 51 |
+
| jump-to-section nav (auto-built or static) | [chrome](../amvcp-layout-chrome/SKILL.md) | `.la-toc` (4 variants) |
|
| 52 |
+
| section header with `01` badge + meta chip | [chrome](../amvcp-layout-chrome/SKILL.md) | `.la-sec-head` |
|
| 53 |
+
| fluid clamp() heading | [chrome](../amvcp-layout-chrome/SKILL.md) | `clamp(MIN, IDEAL, MAX)` |
|
| 54 |
+
| output printed / PDF'd | [print-hero](../amvcp-layout-print-hero/SKILL.md) | `@page` + `.la-cover` + `.la-break-*` + `.no-print` |
|
| 55 |
+
| device screenshot frame | [print-hero](../amvcp-layout-print-hero/SKILL.md) | `.la-device` (set `--dev-*`) |
|
| 56 |
+
| decorative hero band | [print-hero](../amvcp-layout-print-hero/SKILL.md) | `.la-hero` + `data-ghost` |
|
| 57 |
+
| two-paper rotated comparison | [print-hero](../amvcp-layout-print-hero/SKILL.md) | custom rotated cards |
|
| 58 |
+
|
| 59 |
+
## Output
|
| 60 |
+
|
| 61 |
+
The output is owned by the sibling skill. This router emits nothing.
|
| 62 |
+
|
| 63 |
+
## Error Handling
|
| 64 |
+
|
| 65 |
+
| Symptom | Fix |
|
| 66 |
+
|---|---|
|
| 67 |
+
| Don't know which sibling owns my need | Re-read the routing matrix; default to [grids+foundation](../amvcp-layout-grids/SKILL.md) when uncertain (it hosts the spatial token foundation every other sibling consumes). |
|
| 68 |
+
| Need spans multiple siblings | Compose — load grids+foundation first (it's the foundation), then add the siblings you need (e.g. shells + chrome + kpi for an IDE-style admin dashboard). |
|
| 69 |
+
| Page needs print AND chrome | Load both — chrome's sticky header gets hidden by print-hero's `@media print` reset via `.no-print`. |
|
| 70 |
+
|
| 71 |
+
## Examples
|
| 72 |
+
|
| 73 |
+
```text
|
| 74 |
+
User: "I want a content+sidebar article page with a sticky TOC and a sticky page header."
|
| 75 |
+
Route:
|
| 76 |
+
- grids+foundation → .la-grid--2-1 wrapping .la-article + sidebar
|
| 77 |
+
- chrome → .la-header (sticky) + .la-toc (sticky-sidebar variant)
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
```text
|
| 81 |
+
User: "I want an admin dashboard with KPI strip, charts, and a left navigation."
|
| 82 |
+
Route:
|
| 83 |
+
- shells → .la-ide (collapsible left navigation)
|
| 84 |
+
- kpi → .la-dashboard + .la-kpi-row inside the main panel
|
| 85 |
+
- chrome → optional .la-header on top
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
```text
|
| 89 |
+
User: "I want a printable invoice with token tints preserved."
|
| 90 |
+
Route:
|
| 91 |
+
- print-hero → A4 page rules + print reset + .la-cover (page 1)
|
| 92 |
+
- grids+foundation → .la-article for the line-items body
|
| 93 |
+
- kpi → .la-kpi-row for totals at the bottom
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
## Modes
|
| 97 |
+
|
| 98 |
+
Per-sibling: see Resources. The router itself is mode-agnostic.
|
| 99 |
+
|
| 100 |
+
## Composability
|
| 101 |
+
|
| 102 |
+
The 5 layout siblings compose freely with each other and with every other amvcp-* skill on the page (R22). The only exclusive skill is the overlay-runtime (R24). The grids+foundation sibling is mandatory whenever you use any other sibling — it hosts the spatial-token foundation every preset consumes.
|
| 103 |
+
|
| 104 |
+
## Resources
|
| 105 |
+
|
| 106 |
+
The 5 layout siblings:
|
| 107 |
+
|
| 108 |
+
- [amvcp-layout-grids](../amvcp-layout-grids/SKILL.md) — foundation: spatial token ladder, --la-* aliases, named gaps, reading measure, every grid preset (2-1, 3-1, subgrid cardrow, auto-fill, article 3-col + wide/bleed), mobile breakpoint, RTL rule, no-nested-scrollbars contract, selection-atoms contract (16 refs).
|
| 109 |
+
- [amvcp-layout-shells](../amvcp-layout-shells/SKILL.md) — application-shell layout: the IDE 3-panel shell (sidebar + main + inspector) + collapse toggle (1 ref).
|
| 110 |
+
- [amvcp-layout-kpi](../amvcp-layout-kpi/SKILL.md) — KPI rows, stat bands, metric strips, and the 12-column dashboard grid that hosts them (2 refs).
|
| 111 |
+
- [amvcp-layout-chrome](../amvcp-layout-chrome/SKILL.md) — persistent page chrome: sticky header (opaque + glass), sticky toolbar, scroll-spy + sticky-sidebar + right-margin + prefilled TOC variants, fluid clamp() headings, section-numbered headers (10 refs).
|
| 112 |
+
- [amvcp-layout-print-hero](../amvcp-layout-print-hero/SKILL.md) — A4 print rules + cover + page breaks + print-color-adjust + decorative hero with radial glows + device mockup frames + rotated comparison hero (6 refs).
|
benchmarks/skillbench-venus-e/tasks/0140580c4200357f5c54f0fa/task.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": "skill-search-synthesis-v1",
|
| 3 |
+
"task_id": "0140580c4200357f5c54f0fa",
|
| 4 |
+
"environment": {
|
| 5 |
+
"image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
|
| 6 |
+
"network": "none"
|
| 7 |
+
},
|
| 8 |
+
"query_id": "0140580c4200357f5c54f0fa",
|
| 9 |
+
"outputs": [
|
| 10 |
+
"routing.json"
|
| 11 |
+
],
|
| 12 |
+
"success_criteria": [
|
| 13 |
+
"routing.json exists and parses as a JSON array of exactly 6 objects",
|
| 14 |
+
"Each object has keys id, sibling, scaffold",
|
| 15 |
+
"Request 1 maps to sibling grids+foundation with scaffold .la-grid--3-1",
|
| 16 |
+
"Request 2 maps to sibling grids+foundation with scaffold .la-cardrow + .la-card",
|
| 17 |
+
"Request 3 maps to sibling kpi with scaffold .la-dashboard + data-span",
|
| 18 |
+
"Request 4 maps to sibling chrome with scaffold .la-header.--glass",
|
| 19 |
+
"Request 5 maps to sibling print-hero with scaffold @page + .la-cover + .la-break-* + .no-print",
|
| 20 |
+
"Request 6 maps to sibling print-hero with scaffold .la-device (set --dev-*)"
|
| 21 |
+
],
|
| 22 |
+
"evaluation": {
|
| 23 |
+
"kind": "python",
|
| 24 |
+
"type": "verified"
|
| 25 |
+
},
|
| 26 |
+
"source_skill": {
|
| 27 |
+
"sha256": "3bc331297c8bb8a0f109b014247838479eb5f2b51ba0abd56837080f15f1fa05",
|
| 28 |
+
"files": {
|
| 29 |
+
"SKILL.md": "41593f9cfe8fa9c5f7ab85ca529ca62d72180403e66904f64fd8703c05c00d67"
|
| 30 |
+
}
|
| 31 |
+
},
|
| 32 |
+
"workspace": {
|
| 33 |
+
"candidate_mode": "workspace",
|
| 34 |
+
"input_mappings": [
|
| 35 |
+
{
|
| 36 |
+
"source": "inputs/requests.txt",
|
| 37 |
+
"workspace_target": "requests.txt",
|
| 38 |
+
"sha256": "0bedd9b622fd5c721ee376e94008f908da4d411b3b147d518f9fead719992efe"
|
| 39 |
+
}
|
| 40 |
+
],
|
| 41 |
+
"skill_packages": [
|
| 42 |
+
{
|
| 43 |
+
"package_path": "skill",
|
| 44 |
+
"content_hash": "3bc331297c8bb8a0f109b014247838479eb5f2b51ba0abd56837080f15f1fa05"
|
| 45 |
+
}
|
| 46 |
+
]
|
| 47 |
+
}
|
| 48 |
+
}
|
benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_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/01fce2e98fba4d0c_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/01fce2e98fba4d0c_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/01fce2e98fba4d0c_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/01fce2e98fba4d0c_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/01fce2e98fba4d0c_q1/evaluator/check.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from auto_entry import main
|
| 2 |
+
raise SystemExit(main())
|
benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_q1/evaluator/legacy-task.json
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": "mybench-portable-task-v2",
|
| 3 |
+
"task_id": "01fce2e98fba4d0c",
|
| 4 |
+
"query_id": "01fce2e98fba4d0c_q1",
|
| 5 |
+
"prompt": {
|
| 6 |
+
"path": "instruction.md",
|
| 7 |
+
"sha256": "9d27e75412b51f24a7c9a2d4a22909746a01a07268ffd0b2de16ee8d57a3fd25"
|
| 8 |
+
},
|
| 9 |
+
"workspace": {
|
| 10 |
+
"input_mappings": [],
|
| 11 |
+
"skill_packages": [
|
| 12 |
+
{
|
| 13 |
+
"content_hash": "4bac2cf73b8f78c07589ae2091310bfee77b44f4d2f51c0f0950d2c968e0821f",
|
| 14 |
+
"name": "cxo-briefing-kit",
|
| 15 |
+
"package_path": "environment/skills/cxo-briefing-kit-4bac2cf7",
|
| 16 |
+
"install_name": "cxo-briefing-kit-4bac2cf7",
|
| 17 |
+
"archive_provenance": {
|
| 18 |
+
"archive_id": "logical-skill-0317aa8ef95826da7e415f3a",
|
| 19 |
+
"archive_schema": "skill-release-v1",
|
| 20 |
+
"release_skill_id": "logical-skill-0317aa8ef95826da7e415f3a",
|
| 21 |
+
"site": "skills-sh",
|
| 22 |
+
"local_path": "skills/03/logical-skill-0317aa8ef95826da7e415f3a",
|
| 23 |
+
"skill_md_sha256": "5e7520d2b098b27311d857ace1ab4bed604ab1c98f657931f856e6a1ba54c5ad",
|
| 24 |
+
"release_payload_sha256": "4bac2cf73b8f78c07589ae2091310bfee77b44f4d2f51c0f0950d2c968e0821f",
|
| 25 |
+
"license": "Apache-2.0",
|
| 26 |
+
"license_status": "detected",
|
| 27 |
+
"canonical_source_id": "skills-sh:gtmagents/gtm-agents/cxo-briefing-kit"
|
| 28 |
+
},
|
| 29 |
+
"omitted_entries": []
|
| 30 |
+
}
|
| 31 |
+
],
|
| 32 |
+
"default_skill_target": ".claude/skills",
|
| 33 |
+
"candidate_mode": "response"
|
| 34 |
+
},
|
| 35 |
+
"ground_truth_skills": [
|
| 36 |
+
"4bac2cf73b8f78c07589ae2091310bfee77b44f4d2f51c0f0950d2c968e0821f"
|
| 37 |
+
],
|
| 38 |
+
"evaluation": {
|
| 39 |
+
"type": "verified",
|
| 40 |
+
"ground_truth_answer": {
|
| 41 |
+
"answers": {
|
| 42 |
+
"q1": "150",
|
| 43 |
+
"q2": "pursuit-governance"
|
| 44 |
+
}
|
| 45 |
+
},
|
| 46 |
+
"verifier": {
|
| 47 |
+
"type": "atomic_json",
|
| 48 |
+
"version": 1,
|
| 49 |
+
"list_order": "ordered",
|
| 50 |
+
"float_tolerance": 0.01,
|
| 51 |
+
"completeness": {
|
| 52 |
+
"forbid_extra": true,
|
| 53 |
+
"shape": {
|
| 54 |
+
"type": "object",
|
| 55 |
+
"keys": {
|
| 56 |
+
"answers": {
|
| 57 |
+
"type": "object",
|
| 58 |
+
"keys": {
|
| 59 |
+
"q1": {
|
| 60 |
+
"type": "string"
|
| 61 |
+
},
|
| 62 |
+
"q2": {
|
| 63 |
+
"type": "string"
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
}
|
| 69 |
+
},
|
| 70 |
+
"assertions": [
|
| 71 |
+
{
|
| 72 |
+
"id": "leaf_001",
|
| 73 |
+
"path": "$.answers.q1",
|
| 74 |
+
"tokens": [
|
| 75 |
+
"answers",
|
| 76 |
+
"q1"
|
| 77 |
+
],
|
| 78 |
+
"operator": "eq",
|
| 79 |
+
"expected": "150"
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"id": "leaf_002",
|
| 83 |
+
"path": "$.answers.q2",
|
| 84 |
+
"tokens": [
|
| 85 |
+
"answers",
|
| 86 |
+
"q2"
|
| 87 |
+
],
|
| 88 |
+
"operator": "eq",
|
| 89 |
+
"expected": "pursuit-governance"
|
| 90 |
+
}
|
| 91 |
+
],
|
| 92 |
+
"self_test_passed": true
|
| 93 |
+
},
|
| 94 |
+
"dependency_contract": {
|
| 95 |
+
"version": 2,
|
| 96 |
+
"mode": "core_answer",
|
| 97 |
+
"dependency_type": "package_knowledge",
|
| 98 |
+
"requirement_ids": [
|
| 99 |
+
"skill_a017",
|
| 100 |
+
"skill_a019"
|
| 101 |
+
],
|
| 102 |
+
"forbid_meta_reference": true,
|
| 103 |
+
"forbid_answer_leakage": true
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
}
|
benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_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/01fce2e98fba4d0c_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/01fce2e98fba4d0c_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/01fce2e98fba4d0c_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/01fce2e98fba4d0c_q1/evaluator/legacy_tests/verifiers.py
ADDED
|
@@ -0,0 +1,544 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
return json.loads(text)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _strict_json_value(value):
|
| 53 |
+
"""Atomic answer contract: one complete JSON value, no extra prose/keys."""
|
| 54 |
+
def unique(pairs):
|
| 55 |
+
d={}
|
| 56 |
+
for k,v in pairs:
|
| 57 |
+
if k in d:raise ValueError('duplicate JSON key: '+k)
|
| 58 |
+
d[k]=v
|
| 59 |
+
return d
|
| 60 |
+
def invalid(s):raise ValueError('non-finite JSON number: '+s)
|
| 61 |
+
result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid)
|
| 62 |
+
if isinstance(value,str) else value)
|
| 63 |
+
def finite(v):
|
| 64 |
+
if isinstance(v,dict):return all(finite(x)for x in v.values())
|
| 65 |
+
if isinstance(v,list):return all(finite(x)for x in v)
|
| 66 |
+
return not isinstance(v,float)or math.isfinite(v)
|
| 67 |
+
if not finite(result):raise ValueError('non-finite JSON number')
|
| 68 |
+
return result
|
| 69 |
+
|
| 70 |
+
def _path_equal(actual, expected):
|
| 71 |
+
if not isinstance(actual,str)or not isinstance(expected,str):return False
|
| 72 |
+
# A trailing slash is not a harmless spelling for a named file.
|
| 73 |
+
suffix=posixpath.splitext(expected.rstrip('/'))[1]
|
| 74 |
+
if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False
|
| 75 |
+
return _path_value(actual)==_path_value(expected)
|
| 76 |
+
|
| 77 |
+
def _canonical_json(value):
|
| 78 |
+
if isinstance(value, dict):
|
| 79 |
+
return {key: _canonical_json(value[key]) for key in sorted(value)}
|
| 80 |
+
if isinstance(value, list):
|
| 81 |
+
values = [_canonical_json(item) for item in value]
|
| 82 |
+
return sorted(values, key=lambda item: json.dumps(
|
| 83 |
+
item, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
|
| 84 |
+
return value
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _atomic_prepare(value, list_order):
|
| 88 |
+
if isinstance(value, dict):
|
| 89 |
+
return {key: _atomic_prepare(value[key], list_order) for key in sorted(value)}
|
| 90 |
+
if isinstance(value, list):
|
| 91 |
+
values = [_atomic_prepare(item, list_order) for item in value]
|
| 92 |
+
if list_order == "unordered":
|
| 93 |
+
values.sort(key=lambda item: json.dumps(
|
| 94 |
+
item, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
|
| 95 |
+
return values
|
| 96 |
+
return value
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _atomic_shape(value):
|
| 100 |
+
if isinstance(value, dict):
|
| 101 |
+
return {"type": "object", "keys": {
|
| 102 |
+
key: _atomic_shape(item) for key, item in value.items()}}
|
| 103 |
+
if isinstance(value, list):
|
| 104 |
+
return {"type": "array", "length": len(value),
|
| 105 |
+
"items": [_atomic_shape(item) for item in value]}
|
| 106 |
+
if isinstance(value, bool):
|
| 107 |
+
return {"type": "boolean"}
|
| 108 |
+
if value is None:
|
| 109 |
+
return {"type": "null"}
|
| 110 |
+
if isinstance(value, (int, float)):
|
| 111 |
+
return {"type": "number"}
|
| 112 |
+
return {"type": "string"}
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _atomic_leaves(value, path="$", tokens=()):
|
| 116 |
+
if isinstance(value, dict):
|
| 117 |
+
out = []
|
| 118 |
+
for key, item in value.items():
|
| 119 |
+
out.extend(_atomic_leaves(
|
| 120 |
+
item, path + "." + key, tokens + (key,)))
|
| 121 |
+
return out
|
| 122 |
+
if isinstance(value, list):
|
| 123 |
+
out = []
|
| 124 |
+
for index, item in enumerate(value):
|
| 125 |
+
out.extend(_atomic_leaves(
|
| 126 |
+
item, f"{path}[{index}]", tokens + (index,)))
|
| 127 |
+
return out
|
| 128 |
+
return [(path, tokens, value)]
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _normalize_path_equivalence_tokens(values):
|
| 132 |
+
"""Freeze a stable set of scalar JSON paths allowed to ignore a final slash."""
|
| 133 |
+
normalized = []
|
| 134 |
+
for tokens in values or []:
|
| 135 |
+
if (not isinstance(tokens, (list, tuple)) or not tokens or
|
| 136 |
+
any(not isinstance(token, (str, int)) for token in tokens)):
|
| 137 |
+
raise ValueError("path equivalence tokens must be non-empty JSON paths")
|
| 138 |
+
item = list(tokens)
|
| 139 |
+
if item not in normalized:
|
| 140 |
+
normalized.append(item)
|
| 141 |
+
return sorted(normalized, key=lambda item: json.dumps(item, ensure_ascii=False))
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _path_value(value):
|
| 145 |
+
"""Normalize only portable path spelling, not general answer text."""
|
| 146 |
+
if not isinstance(value, str):
|
| 147 |
+
return None
|
| 148 |
+
text = value.strip().replace("\\", "/")
|
| 149 |
+
text = posixpath.normpath(text) if text else text
|
| 150 |
+
if text != "/":
|
| 151 |
+
text = text.rstrip("/")
|
| 152 |
+
return text
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def compile_atomic_verifier(expected, list_order="ordered", float_tolerance=0.01,
|
| 156 |
+
path_equivalence_tokens=None):
|
| 157 |
+
"""Freeze a complete JSON shape plus one assertion for every scalar leaf."""
|
| 158 |
+
if list_order not in {"ordered", "unordered"}:
|
| 159 |
+
raise ValueError(f"unsupported atomic list_order: {list_order}")
|
| 160 |
+
tolerance = float(float_tolerance)
|
| 161 |
+
prepared = _atomic_prepare(_json_value(expected), list_order)
|
| 162 |
+
path_tokens = _normalize_path_equivalence_tokens(path_equivalence_tokens)
|
| 163 |
+
assertions = []
|
| 164 |
+
for index, (path, tokens, value) in enumerate(_atomic_leaves(prepared), 1):
|
| 165 |
+
assertion = {"id": f"leaf_{index:03d}", "path": path,
|
| 166 |
+
"tokens": list(tokens), "operator": "eq", "expected": value}
|
| 167 |
+
if isinstance(value, float):
|
| 168 |
+
assertion.update({"operator": "abs_diff", "tolerance": tolerance})
|
| 169 |
+
elif list(tokens) in path_tokens:
|
| 170 |
+
if not isinstance(value, str):
|
| 171 |
+
raise ValueError("path equivalence can only target string leaves")
|
| 172 |
+
assertion["operator"] = "path_eq"
|
| 173 |
+
assertions.append(assertion)
|
| 174 |
+
compiled = {
|
| 175 |
+
"type": "atomic_json", "version": 2 if path_tokens else 1,
|
| 176 |
+
"list_order": list_order,
|
| 177 |
+
"float_tolerance": tolerance,
|
| 178 |
+
"completeness": {"forbid_extra": True, "shape": _atomic_shape(prepared)},
|
| 179 |
+
"assertions": assertions,
|
| 180 |
+
}
|
| 181 |
+
if path_tokens:
|
| 182 |
+
compiled["path_equivalence_tokens"] = path_tokens
|
| 183 |
+
return compiled
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def _shape_differences(expected, actual, path="$"):
|
| 187 |
+
if not isinstance(actual, dict) or actual.get("type") != expected.get("type"):
|
| 188 |
+
return [f"{path}: expected {expected.get('type')}, got "
|
| 189 |
+
f"{actual.get('type') if isinstance(actual, dict) else 'missing'}"]
|
| 190 |
+
kind = expected.get("type")
|
| 191 |
+
if kind == "object":
|
| 192 |
+
expected_keys = set((expected.get("keys") or {}))
|
| 193 |
+
actual_keys = set((actual.get("keys") or {}))
|
| 194 |
+
differences = [f"{path}: missing key {key}" for key in sorted(
|
| 195 |
+
expected_keys - actual_keys)]
|
| 196 |
+
differences.extend(f"{path}: extra key {key}" for key in sorted(
|
| 197 |
+
actual_keys - expected_keys))
|
| 198 |
+
for key in sorted(expected_keys & actual_keys):
|
| 199 |
+
differences.extend(_shape_differences(
|
| 200 |
+
expected["keys"][key], actual["keys"][key], path + "." + key))
|
| 201 |
+
return differences
|
| 202 |
+
if kind == "array":
|
| 203 |
+
differences = []
|
| 204 |
+
if actual.get("length") != expected.get("length"):
|
| 205 |
+
differences.append(
|
| 206 |
+
f"{path}: expected length {expected.get('length')}, got {actual.get('length')}")
|
| 207 |
+
for index, (expected_item, actual_item) in enumerate(zip(
|
| 208 |
+
expected.get("items") or [], actual.get("items") or [])):
|
| 209 |
+
differences.extend(_shape_differences(
|
| 210 |
+
expected_item, actual_item, f"{path}[{index}]"))
|
| 211 |
+
return differences
|
| 212 |
+
return []
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def _atomic_get(value, tokens):
|
| 216 |
+
current = value
|
| 217 |
+
for token in tokens:
|
| 218 |
+
current = current[token]
|
| 219 |
+
return current
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def _int_values(value):
|
| 223 |
+
if isinstance(value, (list, tuple)):
|
| 224 |
+
out = []
|
| 225 |
+
for item in value:
|
| 226 |
+
out.extend(_int_values(item))
|
| 227 |
+
return out
|
| 228 |
+
if isinstance(value, int) and not isinstance(value, bool):
|
| 229 |
+
return [value]
|
| 230 |
+
return [int(number) for number in re.findall(r"\d+", str(value or ""))]
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def _finding_type(value):
|
| 234 |
+
text = str(value or "").lower().replace("-", "_")
|
| 235 |
+
if "duplicate" in text:
|
| 236 |
+
return "duplicate_rows"
|
| 237 |
+
if ("none" in text or "null" in text) and "check" in text:
|
| 238 |
+
return "none_check"
|
| 239 |
+
if "missing" in text or "empty" in text or "null" in text:
|
| 240 |
+
return "missing"
|
| 241 |
+
if "outlier" in text or "large" in text or ">=" in text or "greater" in text:
|
| 242 |
+
return "outlier"
|
| 243 |
+
if "invalid" in text and "config" in text:
|
| 244 |
+
return "invalid_config"
|
| 245 |
+
if "off" in text and "one" in text:
|
| 246 |
+
return "off_by_one"
|
| 247 |
+
return text.strip().replace(" ", "_")
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def _normalized_findings(value, family):
|
| 251 |
+
obj = _json_value(value)
|
| 252 |
+
findings = obj.get("findings") if isinstance(obj, dict) else None
|
| 253 |
+
if not isinstance(findings, list):
|
| 254 |
+
raise ValueError("answer must contain a findings array")
|
| 255 |
+
normalized = set()
|
| 256 |
+
for finding in findings:
|
| 257 |
+
if not isinstance(finding, dict):
|
| 258 |
+
raise ValueError("each finding must be an object")
|
| 259 |
+
# The public contract uses type/function. Accept common semantically
|
| 260 |
+
# equivalent aliases as a robustness layer, while still comparing the
|
| 261 |
+
# normalized values and exact locations against generator-owned GT.
|
| 262 |
+
kind = _finding_type(finding.get("type", finding.get(
|
| 263 |
+
"defect_type", finding.get("defect"))))
|
| 264 |
+
if family == "csv":
|
| 265 |
+
if kind == "duplicate_rows":
|
| 266 |
+
rows = _int_values(finding.get("rows", finding.get("row")))
|
| 267 |
+
if len(rows) != 2:
|
| 268 |
+
raise ValueError("duplicate finding requires exactly two row numbers")
|
| 269 |
+
normalized.add((kind, *sorted(rows)))
|
| 270 |
+
elif kind in {"missing", "outlier"}:
|
| 271 |
+
rows = _int_values(finding.get("row"))
|
| 272 |
+
column = str(finding.get("column") or "").strip().lower()
|
| 273 |
+
if len(rows) != 1 or not column:
|
| 274 |
+
raise ValueError(f"{kind} requires one row and column")
|
| 275 |
+
normalized.add((kind, rows[0], column))
|
| 276 |
+
else:
|
| 277 |
+
raise ValueError(f"unsupported CSV finding type: {kind}")
|
| 278 |
+
elif family == "config":
|
| 279 |
+
if kind != "invalid_config":
|
| 280 |
+
raise ValueError(f"unsupported config finding type: {kind}")
|
| 281 |
+
normalized.add((kind, str(finding.get("path") or "").lower(),
|
| 282 |
+
json.dumps(finding.get("value"), sort_keys=True),
|
| 283 |
+
str(finding.get("expected") or "").lower()))
|
| 284 |
+
elif family == "code":
|
| 285 |
+
if kind not in {"off_by_one", "none_check"}:
|
| 286 |
+
raise ValueError(f"unsupported code finding type: {kind}")
|
| 287 |
+
function = finding.get("function", finding.get("function_name"))
|
| 288 |
+
function = str(function or "").strip().lower()
|
| 289 |
+
if not function:
|
| 290 |
+
raise ValueError(f"{kind} requires a function")
|
| 291 |
+
normalized.add((kind, function))
|
| 292 |
+
else:
|
| 293 |
+
raise ValueError(f"unsupported findings family: {family}")
|
| 294 |
+
return normalized
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def _normalized_facts(value):
|
| 298 |
+
obj = _json_value(value)
|
| 299 |
+
facts = obj.get("facts") if isinstance(obj, dict) else None
|
| 300 |
+
if not isinstance(facts, list):
|
| 301 |
+
raise ValueError("answer must contain a facts array")
|
| 302 |
+
def textual(item):
|
| 303 |
+
# The document generator serializes scalar values as visible text. JSON
|
| 304 |
+
# has no way to infer whether the source token "30" was authored from an
|
| 305 |
+
# integer or a string, so facts_match compares that surface text. Nested
|
| 306 |
+
# values retain structural JSON comparison.
|
| 307 |
+
if isinstance(item, (dict, list)):
|
| 308 |
+
return json.dumps(item, sort_keys=True, ensure_ascii=False,
|
| 309 |
+
separators=(",", ":"))
|
| 310 |
+
if item is None:
|
| 311 |
+
return "None"
|
| 312 |
+
return str(item)
|
| 313 |
+
return {(str(fact.get("key") or ""), textual(fact.get("value")))
|
| 314 |
+
for fact in facts if isinstance(fact, dict)}
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def verify(verifier, gt_answer, solver_output, material_paths=None):
|
| 318 |
+
"""执行 verifier。返回 (passed, detail)。"""
|
| 319 |
+
vtype = verifier.get("type")
|
| 320 |
+
try:
|
| 321 |
+
if vtype == WORKSPACE_EVALUATOR:
|
| 322 |
+
return evaluate_candidate(verifier, solver_output)
|
| 323 |
+
|
| 324 |
+
if vtype == "json_exact":
|
| 325 |
+
pred = _canonical_json(_json_value(solver_output))
|
| 326 |
+
gold = _canonical_json(_json_value(gt_answer))
|
| 327 |
+
ok = pred == gold
|
| 328 |
+
return ok, "json_exact: pass" if ok else f"json_exact mismatch: pred={pred!r}"
|
| 329 |
+
|
| 330 |
+
if vtype == "atomic_json":
|
| 331 |
+
pred = _atomic_prepare(_strict_json_value(solver_output),
|
| 332 |
+
verifier.get("list_order", "ordered"))
|
| 333 |
+
compiled = compile_atomic_verifier(
|
| 334 |
+
gt_answer, verifier.get("list_order", "ordered"),
|
| 335 |
+
verifier.get("float_tolerance", 0.01),
|
| 336 |
+
verifier.get("path_equivalence_tokens"))
|
| 337 |
+
frozen = {key: verifier.get(key) for key in
|
| 338 |
+
("type", "version", "list_order", "float_tolerance",
|
| 339 |
+
"completeness", "assertions", "path_equivalence_tokens")}
|
| 340 |
+
expected_frozen = {key: compiled.get(key) for key in frozen}
|
| 341 |
+
if frozen != expected_frozen:
|
| 342 |
+
return False, {"error": "atomic verifier does not match ground truth"}
|
| 343 |
+
shape_failures = _shape_differences(
|
| 344 |
+
verifier["completeness"]["shape"], _atomic_shape(pred))
|
| 345 |
+
assertion_results = []
|
| 346 |
+
for assertion in verifier.get("assertions") or []:
|
| 347 |
+
try:
|
| 348 |
+
actual = _atomic_get(pred, assertion["tokens"])
|
| 349 |
+
if assertion["operator"] == "abs_diff":
|
| 350 |
+
passed = abs(float(actual) - float(assertion["expected"])) <= float(
|
| 351 |
+
assertion.get("tolerance", 0.0))
|
| 352 |
+
elif assertion["operator"] == "path_eq":
|
| 353 |
+
passed = _path_equal(actual, assertion["expected"])
|
| 354 |
+
else:
|
| 355 |
+
passed = (actual is assertion["expected"] if
|
| 356 |
+
isinstance(assertion["expected"], bool) else
|
| 357 |
+
actual == assertion["expected"])
|
| 358 |
+
message = "" if passed else (
|
| 359 |
+
f"actual={actual!r} expected={assertion['expected']!r}")
|
| 360 |
+
except (KeyError, IndexError, TypeError, ValueError) as exc:
|
| 361 |
+
actual, passed, message = None, False, f"lookup/compare failed: {exc}"
|
| 362 |
+
assertion_results.append({
|
| 363 |
+
"id": assertion["id"], "path": assertion["path"],
|
| 364 |
+
"operator": assertion["operator"], "expected": assertion["expected"],
|
| 365 |
+
"actual": actual, "passed": passed, "message": message})
|
| 366 |
+
passed_count = sum(item["passed"] for item in assertion_results)
|
| 367 |
+
ok = not shape_failures and passed_count == len(assertion_results)
|
| 368 |
+
return ok, {
|
| 369 |
+
"type": "atomic_json", "completeness_passed": not shape_failures,
|
| 370 |
+
"completeness_failures": shape_failures,
|
| 371 |
+
"assertions_passed": passed_count,
|
| 372 |
+
"assertions_total": len(assertion_results),
|
| 373 |
+
"assertion_pass_rate": (passed_count / len(assertion_results)
|
| 374 |
+
if assertion_results else 1.0),
|
| 375 |
+
"assertions": assertion_results,
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
if vtype == "findings_match":
|
| 379 |
+
family = verifier.get("family")
|
| 380 |
+
pred = _normalized_findings(solver_output, family)
|
| 381 |
+
gold = _normalized_findings(gt_answer, family)
|
| 382 |
+
ok = pred == gold
|
| 383 |
+
return ok, ("findings_match: pass" if ok else
|
| 384 |
+
f"findings_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}")
|
| 385 |
+
|
| 386 |
+
if vtype == "facts_match":
|
| 387 |
+
pred, gold = _normalized_facts(solver_output), _normalized_facts(gt_answer)
|
| 388 |
+
ok = pred == gold
|
| 389 |
+
return ok, ("facts_match: pass" if ok else
|
| 390 |
+
f"facts_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}")
|
| 391 |
+
|
| 392 |
+
if vtype == "exact_match":
|
| 393 |
+
ok = _norm(solver_output) == _norm(gt_answer)
|
| 394 |
+
return ok, f"exact_match: {'pass' if ok else 'mismatch'}"
|
| 395 |
+
|
| 396 |
+
if vtype == "numeric":
|
| 397 |
+
tol = verifier.get("tolerance") or 1e-6
|
| 398 |
+
pred = float(str(solver_output).strip().split()[0])
|
| 399 |
+
gold = float(gt_answer)
|
| 400 |
+
ok = abs(pred - gold) <= tol
|
| 401 |
+
return ok, f"numeric: pred={pred} gold={gold} tol={tol}"
|
| 402 |
+
|
| 403 |
+
if vtype == "set_match":
|
| 404 |
+
pred = set(_as_list(solver_output))
|
| 405 |
+
gold = set(_as_list(gt_answer))
|
| 406 |
+
ok = pred == gold
|
| 407 |
+
return ok, f"set_match: extra={list(pred - gold)[:5]} missing={list(gold - pred)[:5]}"
|
| 408 |
+
|
| 409 |
+
if vtype == "structured_match":
|
| 410 |
+
pred = _json_value(solver_output)
|
| 411 |
+
gold = _json_value(gt_answer)
|
| 412 |
+
if not isinstance(pred, dict) or not isinstance(gold, dict):
|
| 413 |
+
return False, "structured_match requires JSON objects"
|
| 414 |
+
missing = [f for f in verifier.get("required_fields", []) if f not in pred]
|
| 415 |
+
wrong = [f for f in verifier.get("required_fields", [])
|
| 416 |
+
if f in pred and f in gold and pred[f] != gold[f]]
|
| 417 |
+
ok = not missing and not wrong
|
| 418 |
+
return ok, f"structured_match: missing_fields={missing} wrong_values={wrong}"
|
| 419 |
+
|
| 420 |
+
if vtype == "execution":
|
| 421 |
+
return False, "execution verifier is disabled in verified-first v2"
|
| 422 |
+
|
| 423 |
+
if vtype == "constraint":
|
| 424 |
+
fails = _check_constraints(verifier.get("criteria", []), solver_output)
|
| 425 |
+
return not fails, f"constraint: failed={fails[:5]}"
|
| 426 |
+
|
| 427 |
+
if vtype == "file_inspection":
|
| 428 |
+
fails = _inspect_files(verifier.get("expected_files", []), material_paths or [])
|
| 429 |
+
return not fails, f"file_inspection: failed={fails[:5]}"
|
| 430 |
+
|
| 431 |
+
return False, f"unknown verifier type: {vtype}"
|
| 432 |
+
except Exception as e:
|
| 433 |
+
return False, f"verifier error: {e}"
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
def _as_list(x):
|
| 437 |
+
if isinstance(x, list):
|
| 438 |
+
return [_norm(i) for i in x]
|
| 439 |
+
# 逗号/换行分隔的字符串
|
| 440 |
+
return [_norm(i) for i in str(x).replace("\n", ",").split(",") if i.strip()]
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def _check_constraints(criteria, solver_output):
|
| 444 |
+
"""criteria: ["must contain X", "must be valid json", "length <= 500"]"""
|
| 445 |
+
fails = []
|
| 446 |
+
text = str(solver_output)
|
| 447 |
+
for c in criteria:
|
| 448 |
+
cl = c.lower()
|
| 449 |
+
if cl.startswith("must contain "):
|
| 450 |
+
needle = c[len("must contain "):]
|
| 451 |
+
if needle.lower() not in text.lower():
|
| 452 |
+
fails.append(c)
|
| 453 |
+
elif "valid json" in cl:
|
| 454 |
+
try:
|
| 455 |
+
json.loads(text)
|
| 456 |
+
except Exception:
|
| 457 |
+
fails.append(c)
|
| 458 |
+
elif cl.startswith("length <="):
|
| 459 |
+
limit = int(cl.split("<=")[1].strip())
|
| 460 |
+
if len(text) > limit:
|
| 461 |
+
fails.append(c)
|
| 462 |
+
else:
|
| 463 |
+
# Deterministic verifier DSL is closed-world: unknown checks fail.
|
| 464 |
+
fails.append(f"unsupported criterion: {c}")
|
| 465 |
+
return fails
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def _inspect_files(expected, material_paths):
|
| 469 |
+
fails = []
|
| 470 |
+
paths = set(material_paths or [])
|
| 471 |
+
for e in expected:
|
| 472 |
+
fname = e.get("filename") if isinstance(e, dict) else str(e)
|
| 473 |
+
if not any(os.path.basename(p) == os.path.basename(fname) for p in paths):
|
| 474 |
+
fails.append(f"missing file: {fname}")
|
| 475 |
+
return fails
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
# ---------------- 自测 ----------------
|
| 479 |
+
|
| 480 |
+
def build_correct_solution(verifier, gt_answer, planted_info):
|
| 481 |
+
"""由埋点/ground truth 直接构造正确解。"""
|
| 482 |
+
vtype = verifier.get("type")
|
| 483 |
+
if vtype == WORKSPACE_EVALUATOR:
|
| 484 |
+
return reference_bundle(verifier)
|
| 485 |
+
if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match", "exact_match", "numeric",
|
| 486 |
+
"set_match", "structured_match"):
|
| 487 |
+
return gt_answer
|
| 488 |
+
if vtype == "constraint":
|
| 489 |
+
parts = [c[len("must contain "):] for c in verifier.get("criteria", [])
|
| 490 |
+
if c.lower().startswith("must contain ")]
|
| 491 |
+
return " ".join(parts) if parts else str(gt_answer)
|
| 492 |
+
# execution / file_inspection 复杂场景:返回 None 表示跳过正确解构造
|
| 493 |
+
return None
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
def build_perturbed_solution(verifier, gt_answer, planted_info):
|
| 497 |
+
"""破坏埋点构造扰动解。"""
|
| 498 |
+
vtype = verifier.get("type")
|
| 499 |
+
if vtype == WORKSPACE_EVALUATOR:
|
| 500 |
+
files = list(reference_bundle(verifier).get("files") or [])
|
| 501 |
+
return {"files": files[1:] if len(files) > 1 else []}
|
| 502 |
+
if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match"):
|
| 503 |
+
gold = _json_value(gt_answer)
|
| 504 |
+
if isinstance(gold, dict):
|
| 505 |
+
perturbed = dict(gold)
|
| 506 |
+
key = next(iter(perturbed), "__missing__")
|
| 507 |
+
if key in perturbed:
|
| 508 |
+
perturbed.pop(key)
|
| 509 |
+
else:
|
| 510 |
+
perturbed["__wrong__"] = True
|
| 511 |
+
return perturbed
|
| 512 |
+
if isinstance(gold, list):
|
| 513 |
+
return gold[:-1] if gold else ["__wrong__"]
|
| 514 |
+
return "__wrong__"
|
| 515 |
+
if vtype in ("exact_match", "numeric"):
|
| 516 |
+
return "0" if vtype == "numeric" else "PERTURBED_WRONG_ANSWER"
|
| 517 |
+
if vtype == "set_match":
|
| 518 |
+
gold = _as_list(gt_answer)
|
| 519 |
+
return gold[: max(0, len(gold) - 1)] + ["perturbed_item"]
|
| 520 |
+
if vtype == "structured_match":
|
| 521 |
+
fields = verifier.get("required_fields", [])
|
| 522 |
+
return {f: None for i, f in enumerate(fields) if i > 0} # 缺第一个字段
|
| 523 |
+
if vtype == "constraint":
|
| 524 |
+
return "perturbed output lacking required content"
|
| 525 |
+
return None
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def self_test(verifier, gt_answer, planted_info, material_paths):
|
| 529 |
+
"""返回 (passed, detail)。无法构造正确/扰动解的 verifier 类型 = 未通过(不算数)。
|
| 530 |
+
|
| 531 |
+
之前这里对 execution / file_inspection 直接 return True("skipped"),等于坏 verifier
|
| 532 |
+
可无证据通过 S5;改为按未通过处理,由 S5 转 open 支路或丢弃。
|
| 533 |
+
"""
|
| 534 |
+
if verifier.get("type") == WORKSPACE_EVALUATOR:
|
| 535 |
+
return self_test_workspace_evaluator(verifier)
|
| 536 |
+
correct = build_correct_solution(verifier, gt_answer, planted_info)
|
| 537 |
+
perturbed = build_perturbed_solution(verifier, gt_answer, planted_info)
|
| 538 |
+
if correct is None or perturbed is None:
|
| 539 |
+
return False, (f"cannot self-test verifier type {verifier.get('type')} "
|
| 540 |
+
"(execution/file_inspection need real correct/perturbed solutions)")
|
| 541 |
+
ok1, d1 = verify(verifier, gt_answer, correct, material_paths)
|
| 542 |
+
ok2, d2 = verify(verifier, gt_answer, perturbed, material_paths)
|
| 543 |
+
passed = ok1 and not ok2
|
| 544 |
+
return passed, {"correct": d1, "perturbed": d2}
|
benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_q1/grading/verified_config.json
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema": "audited-verified-grader-v1",
|
| 3 |
+
"query_id": "01fce2e98fba4d0c_q1",
|
| 4 |
+
"selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
|
| 5 |
+
"grader_file_sha256": {
|
| 6 |
+
"auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa",
|
| 7 |
+
"check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
|
| 8 |
+
"legacy-task.json": "2ad3b1bc940583a769b04140cbc71559681c50030b589fa93a3f34cf13859f22",
|
| 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": "170f6c86b91adfb8c10f0f1833ed5219d814b8723ee0e605327c31fdbf64fb70"
|
| 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/01fce2e98fba4d0c_q1/instruction.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
We're standardizing how our sales team writes executive pursuit updates, and I need to lock down two conventions this team has already declared. First, what's the word limit our CXO one-slide briefing is supposed to stay under? Second, when we ship that briefing kit, which companion should be paired with it so pursuit cadences stay consistent across the team? Please answer both questions and return exactly one JSON object in this shape, replacing each placeholder with the bare value: {"answers":{"q1":"string","q2":"string"}}
|
benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_q1/skill/SKILL.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: cxo-briefing-kit
|
| 3 |
+
description: Use to package concise executive updates, decks, and decision logs for
|
| 4 |
+
enterprise pursuits.
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
# CXO Briefing Kit Skill
|
| 8 |
+
|
| 9 |
+
## When to Use
|
| 10 |
+
- Preparing executive sponsor briefings ahead of milestone meetings.
|
| 11 |
+
- Summarizing pursuit status for CRO, COO, CFO, or CEO stakeholders.
|
| 12 |
+
- Logging decisions, risks, and asks after executive reviews.
|
| 13 |
+
|
| 14 |
+
## Framework
|
| 15 |
+
1. **Audience Snapshot** – note executive priorities, role, and preferred format.
|
| 16 |
+
2. **Headline & Status** – articulate deal stage, confidence, and key wins/risks.
|
| 17 |
+
3. **Value Story** – highlight quantified impact + proof tied to executive objectives.
|
| 18 |
+
4. **Decision & Ask** – specify approvals, resources, or unblockers required.
|
| 19 |
+
5. **Action & Follow-up** – capture owners, due dates, and communication plan.
|
| 20 |
+
|
| 21 |
+
## Templates
|
| 22 |
+
- One-slide exec update (headline, metrics, risks, asks).
|
| 23 |
+
- Briefing memo outline with context, status, decisions, next steps.
|
| 24 |
+
- Decision log sheet with timestamp, owner, outcome.
|
| 25 |
+
|
| 26 |
+
## Tips
|
| 27 |
+
- Keep main slide under 150 words; push detail to appendix.
|
| 28 |
+
- Tailor numbers to executive KPIs (margin, risk, innovation, customer impact).
|
| 29 |
+
- Pair with `pursuit-governance` to keep cadences consistent.
|
| 30 |
+
|
| 31 |
+
---
|
benchmarks/skillbench-venus-e/tasks/01fce2e98fba4d0c_q1/task.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": "skill-search-synthesis-v1",
|
| 3 |
+
"task_id": "01fce2e98fba4d0c",
|
| 4 |
+
"query_id": "01fce2e98fba4d0c_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": "8d6d6b291ec28a5216222f4bcbecc7b583b3060af74612efdd11d2d5fdeb8f75",
|
| 22 |
+
"name": "cxo-briefing-kit",
|
| 23 |
+
"package_path": "skill",
|
| 24 |
+
"install_name": "cxo-briefing-kit-4bac2cf7"
|
| 25 |
+
}
|
| 26 |
+
],
|
| 27 |
+
"default_skill_target": ".claude/skills",
|
| 28 |
+
"candidate_mode": "response"
|
| 29 |
+
},
|
| 30 |
+
"source_skill": {
|
| 31 |
+
"sha256": "8d6d6b291ec28a5216222f4bcbecc7b583b3060af74612efdd11d2d5fdeb8f75",
|
| 32 |
+
"files": {
|
| 33 |
+
"SKILL.md": "5e7520d2b098b27311d857ace1ab4bed604ab1c98f657931f856e6a1ba54c5ad"
|
| 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 |
+
"4bac2cf73b8f78c07589ae2091310bfee77b44f4d2f51c0f0950d2c968e0821f"
|
| 44 |
+
]
|
| 45 |
+
}
|
| 46 |
+
}
|
benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/evaluator/auto_contract.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"expected_check_ids": [
|
| 3 |
+
"0",
|
| 4 |
+
"1",
|
| 5 |
+
"2",
|
| 6 |
+
"3",
|
| 7 |
+
"4",
|
| 8 |
+
"5",
|
| 9 |
+
"6"
|
| 10 |
+
],
|
| 11 |
+
"criterion_weights": {
|
| 12 |
+
"0": 1,
|
| 13 |
+
"1": 1,
|
| 14 |
+
"2": 1,
|
| 15 |
+
"3": 1,
|
| 16 |
+
"4": 1,
|
| 17 |
+
"5": 1,
|
| 18 |
+
"6": 1
|
| 19 |
+
}
|
| 20 |
+
}
|
benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/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/02d150d26f11effa96aacc72/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 |
+
"5"
|
| 9 |
+
],
|
| 10 |
+
"runtime_owner_ids": [
|
| 11 |
+
"0",
|
| 12 |
+
"5"
|
| 13 |
+
],
|
| 14 |
+
"execution_budget_seconds": 60,
|
| 15 |
+
"total_evaluation_budget_seconds": 420
|
| 16 |
+
}
|
benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/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/02d150d26f11effa96aacc72/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/02d150d26f11effa96aacc72/evaluator/autograde_task_check.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 2 |
+
from r9_contract import main
|
| 3 |
+
main('02d150d26f11effa96aacc72')
|
benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/evaluator/check.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from auto_entry import main
|
| 2 |
+
raise SystemExit(main())
|
benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/evaluator/dependency_scan.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Private static dependency validation, including local Python namespace packages.
|
| 2 |
+
|
| 3 |
+
This module only parses source. It never imports or runs candidate modules.
|
| 4 |
+
"""
|
| 5 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 6 |
+
import _imp
|
| 7 |
+
import ast
|
| 8 |
+
import sys
|
| 9 |
+
import tokenize
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def scan_stdlib(root,entries,external=()):
|
| 14 |
+
return True,set(),'Static imports are not scored; bounded runtime policy is independently observed'
|
benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/evaluator/old_check.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 2 |
+
import json, os, re, shutil, subprocess, tempfile
|
| 3 |
+
|
| 4 |
+
STATE = '''project: taskboard
|
| 5 |
+
vm_host: 10.0.0.42
|
| 6 |
+
vm_user: devops
|
| 7 |
+
project_path: /mnt/nas/project/taskboard
|
| 8 |
+
tmux_socket: /tmp/openclaw-tmux-sockets/openclaw.sock
|
| 9 |
+
tmux_session: bmad-taskboard
|
| 10 |
+
current_phase: 3
|
| 11 |
+
current_workflow: bmad-bmm-create-architecture
|
| 12 |
+
artifacts:
|
| 13 |
+
brainstorming_report: _bmad-output/brainstorming-report.md
|
| 14 |
+
product_brief: _bmad-output/product-brief.md
|
| 15 |
+
prd: _bmad-output/planning-artifacts/prd.md
|
| 16 |
+
ux_spec: null
|
| 17 |
+
architecture: null
|
| 18 |
+
epics: null
|
| 19 |
+
sprint_status: null
|
| 20 |
+
project_context: null
|
| 21 |
+
'''
|
| 22 |
+
|
| 23 |
+
STATE_P4 = STATE.replace('current_phase: 3', 'current_phase: 4').replace(
|
| 24 |
+
'sprint_status: null', 'sprint_status: _bmad-output/sprint-status.yaml')
|
| 25 |
+
|
| 26 |
+
def run_script(src, state_text, tmp):
|
| 27 |
+
with open(os.path.join(tmp, 'orchestrator-state.yaml'), 'w') as f:
|
| 28 |
+
f.write(state_text)
|
| 29 |
+
script = os.path.join(tmp, 'next_step.py')
|
| 30 |
+
shutil.copy(src, script)
|
| 31 |
+
p = subprocess.run(['python3', 'next_step.py'], cwd=tmp,
|
| 32 |
+
capture_output=True, text=True, timeout=60)
|
| 33 |
+
out = None
|
| 34 |
+
for name in ('next-step.txt', 'next_step.txt'):
|
| 35 |
+
path = os.path.join(tmp, name)
|
| 36 |
+
if os.path.exists(path):
|
| 37 |
+
out = open(path).read()
|
| 38 |
+
break
|
| 39 |
+
return p, out
|
| 40 |
+
|
| 41 |
+
def main():
|
| 42 |
+
checks = [None]*7
|
| 43 |
+
cand = '/candidate'
|
| 44 |
+
src = os.path.join(cand, 'next_step.py')
|
| 45 |
+
plan_path = None
|
| 46 |
+
for name in ('next-step.txt', 'next_step.txt'):
|
| 47 |
+
p = os.path.join(cand, name)
|
| 48 |
+
if os.path.exists(p):
|
| 49 |
+
plan_path = p
|
| 50 |
+
break
|
| 51 |
+
plan = open(plan_path).read() if plan_path else None
|
| 52 |
+
|
| 53 |
+
# Check 0: runs with stdlib only, exits successfully
|
| 54 |
+
if not os.path.exists(src):
|
| 55 |
+
checks[0] = (False, 'next_step.py not found in /candidate')
|
| 56 |
+
else:
|
| 57 |
+
try:
|
| 58 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 59 |
+
p, _ = run_script(src, STATE, tmp)
|
| 60 |
+
if p.returncode == 0:
|
| 61 |
+
checks[0] = (True, 'script ran and exited 0')
|
| 62 |
+
else:
|
| 63 |
+
checks[0] = (False, 'script exited %d: %s' % (p.returncode, (p.stderr or p.stdout)[:300]))
|
| 64 |
+
except Exception as e:
|
| 65 |
+
checks[0] = (False, 'failed to run script: %s' % e)
|
| 66 |
+
|
| 67 |
+
def plan_has(needle):
|
| 68 |
+
return plan is not None and needle in plan
|
| 69 |
+
|
| 70 |
+
# Check 1: command
|
| 71 |
+
if plan is None:
|
| 72 |
+
for i in range(1, 5):
|
| 73 |
+
checks[i] = (False, 'next-step.txt not found in /candidate')
|
| 74 |
+
else:
|
| 75 |
+
checks[1] = (True, '/bmad-bmm-create-architecture present') if plan_has('/bmad-bmm-create-architecture') else (False, 'next-step.txt missing /bmad-bmm-create-architecture')
|
| 76 |
+
checks[2] = (True, 'architecture.md present') if plan_has('architecture.md') else (False, 'next-step.txt missing architecture.md')
|
| 77 |
+
# Check 3: send-keys line with socket, session, target, -l
|
| 78 |
+
lines = plan.splitlines()
|
| 79 |
+
ok3 = any(('-l' in l and 'send-keys' in l and '/tmp/openclaw-tmux-sockets/openclaw.sock' in l
|
| 80 |
+
and 'bmad-taskboard' in l and 'bmad-taskboard:0.0' in l) for l in lines)
|
| 81 |
+
checks[3] = (True, 'send-keys -l line with socket/session/target found') if ok3 else (False, 'no send-keys line with -l, socket /tmp/openclaw-tmux-sockets/openclaw.sock, session bmad-taskboard and target bmad-taskboard:0.0')
|
| 82 |
+
# Check 4: Enter line after, with 0.3 delay
|
| 83 |
+
ok4 = False
|
| 84 |
+
for i, l in enumerate(lines):
|
| 85 |
+
if 'send-keys' in l and '-l' in l and '/bmad-bmm-create-architecture' in l:
|
| 86 |
+
rest = '\n'.join(lines[i+1:])
|
| 87 |
+
if re.search(r'sleep\s+0?\.3', rest) and re.search(r'send-keys[^\n]*Enter', rest):
|
| 88 |
+
ok4 = True
|
| 89 |
+
break
|
| 90 |
+
if not ok4:
|
| 91 |
+
# also accept a one-liner: send-keys -l ... && sleep 0.3 && send-keys Enter
|
| 92 |
+
if re.search(r'send-keys[^\n]*-l[^\n]*/bmad-bmm-create-architecture[^\n]*&&[^\n]*sleep\s+0?\.3[^\n]*&&[^\n]*send-keys[^\n]*Enter', plan):
|
| 93 |
+
ok4 = True
|
| 94 |
+
checks[4] = (True, 'Enter send-keys with 0.3s delay after text send') if ok4 else (False, 'missing Enter send-keys line after a 0.3s sleep following the text send-keys')
|
| 95 |
+
|
| 96 |
+
# Check 5: no third-party YAML library
|
| 97 |
+
if not os.path.exists(src):
|
| 98 |
+
checks[5] = (False, 'next_step.py missing')
|
| 99 |
+
else:
|
| 100 |
+
code = open(src).read()
|
| 101 |
+
bad = re.findall(r'^\s*(?:import|from)\s+(yaml|ruamel|pyyaml)\b', code, re.M)
|
| 102 |
+
checks[5] = (False, 'imports YAML library: %s' % bad) if bad else (True, 'no YAML library imported')
|
| 103 |
+
|
| 104 |
+
# Check 6: data-driven rule — phase 4 with sprint_status set -> create-story
|
| 105 |
+
if not os.path.exists(src):
|
| 106 |
+
checks[6] = (False, 'next_step.py missing')
|
| 107 |
+
else:
|
| 108 |
+
try:
|
| 109 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 110 |
+
p, out = run_script(src, STATE_P4, tmp)
|
| 111 |
+
if p.returncode != 0:
|
| 112 |
+
checks[6] = (False, 'script failed on modified state: %s' % (p.stderr or '')[:300])
|
| 113 |
+
elif out and '/bmad-bmm-create-story' in out:
|
| 114 |
+
checks[6] = (True, 'phase-4 state yields /bmad-bmm-create-story')
|
| 115 |
+
else:
|
| 116 |
+
checks[6] = (False, 'modified state (phase 4, sprint_status set) did not yield /bmad-bmm-create-story')
|
| 117 |
+
except Exception as e:
|
| 118 |
+
checks[6] = (False, 'failed testing modified state: %s' % e)
|
| 119 |
+
|
| 120 |
+
print(json.dumps({'checks': [{'id': str(i), 'passed': bool(p), 'reason': r} for i, (p, r) in enumerate(checks)]}))
|
| 121 |
+
|
| 122 |
+
main()
|
benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/evaluator/r9_contract.py
ADDED
|
@@ -0,0 +1,723 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Independent checks derived from each public task, with full-workspace probes.
|
| 2 |
+
|
| 3 |
+
This file is authored for the R9 release. It never reads reference solutions,
|
| 4 |
+
historical scores, solver identities, or private expected-answer payloads.
|
| 5 |
+
"""
|
| 6 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 7 |
+
import ast, collections, configparser, csv, datetime, io, json, math, os
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import re, resource, shlex, shutil, signal, stat, subprocess, sys
|
| 10 |
+
|
| 11 |
+
C = Path(os.environ.get('MYBENCH_CANDIDATE', '/candidate'))
|
| 12 |
+
S = Path(os.environ.get('MYBENCH_SOURCE_TASK', '/source'))
|
| 13 |
+
DIAG = []
|
| 14 |
+
|
| 15 |
+
def tri(values):
|
| 16 |
+
values=list(values)
|
| 17 |
+
return False if any(v is False for v in values) else None if any(v is None for v in values) else True
|
| 18 |
+
|
| 19 |
+
def unique(pairs):
|
| 20 |
+
out={}
|
| 21 |
+
for key,value in pairs:
|
| 22 |
+
if key in out: raise ValueError('duplicate JSON key')
|
| 23 |
+
out[key]=value
|
| 24 |
+
return out
|
| 25 |
+
|
| 26 |
+
def load(path):
|
| 27 |
+
try:return json.loads(Path(path).read_text(encoding='utf-8-sig'),object_pairs_hook=unique,parse_constant=lambda s:(_ for _ in ()).throw(ValueError(s)))
|
| 28 |
+
except(FileNotFoundError,IsADirectoryError,UnicodeError,ValueError):return False
|
| 29 |
+
|
| 30 |
+
def source_inputs():
|
| 31 |
+
task=json.loads((S/'task.json').read_text())
|
| 32 |
+
return {m['workspace_target']:(S/m['source']).read_bytes() for m in task['workspace'].get('input_mappings',[])}
|
| 33 |
+
|
| 34 |
+
def reset(path):
|
| 35 |
+
path=Path(path)
|
| 36 |
+
if path.is_symlink() or path.is_file():path.unlink()
|
| 37 |
+
elif path.is_dir():shutil.rmtree(path)
|
| 38 |
+
|
| 39 |
+
def limit():
|
| 40 |
+
os.setsid()
|
| 41 |
+
resource.setrlimit(resource.RLIMIT_AS,(512*1024*1024,512*1024*1024))
|
| 42 |
+
|
| 43 |
+
def run(script,updates,outputs,args=(),cwd_index=0):
|
| 44 |
+
roots=[Path('/app'),Path('/workspace')]
|
| 45 |
+
for root in roots:
|
| 46 |
+
root.mkdir(exist_ok=True)
|
| 47 |
+
for p in root.iterdir():reset(p)
|
| 48 |
+
shutil.copytree(C,root,symlinks=True,dirs_exist_ok=True)
|
| 49 |
+
for name,body in source_inputs().items():
|
| 50 |
+
p=root/name;reset(p);p.parent.mkdir(parents=True,exist_ok=True);p.write_bytes(body)
|
| 51 |
+
for name,body in updates.items():
|
| 52 |
+
p=root/name;reset(p)
|
| 53 |
+
if body is not None:p.parent.mkdir(parents=True,exist_ok=True);p.write_bytes(body if isinstance(body,bytes) else body.encode())
|
| 54 |
+
for name in outputs:reset(root/name)
|
| 55 |
+
cwd=roots[cwd_index%2]
|
| 56 |
+
proc=None
|
| 57 |
+
try:
|
| 58 |
+
proc=subprocess.Popen([sys.executable,script]+list(args),cwd=cwd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,preexec_fn=limit)
|
| 59 |
+
try:stdout,stderr=proc.communicate(timeout=8);rc=proc.returncode
|
| 60 |
+
except subprocess.TimeoutExpired:
|
| 61 |
+
os.killpg(proc.pid,signal.SIGKILL);stdout,stderr=proc.communicate();rc=-124
|
| 62 |
+
docs=[root for root in roots if any((root/name).is_file() for name in outputs)]
|
| 63 |
+
result={'rc':rc,'stdout':stdout.decode('utf-8','replace'),'stderr':stderr.decode('utf-8','replace'),'roots':docs,'cwd':cwd}
|
| 64 |
+
DIAG.append({'script':script,'cwd':str(cwd),'exit':rc,'output_roots':[str(p) for p in docs]})
|
| 65 |
+
return result
|
| 66 |
+
except OSError as exc:
|
| 67 |
+
DIAG.append({'script':script,'error':type(exc).__name__})
|
| 68 |
+
return {'rc':None,'stdout':'','stderr':'','roots':[],'cwd':cwd}
|
| 69 |
+
finally:
|
| 70 |
+
if proc is not None:
|
| 71 |
+
try:os.killpg(proc.pid,signal.SIGKILL)
|
| 72 |
+
except ProcessLookupError:pass
|
| 73 |
+
|
| 74 |
+
def stdlib(script):
|
| 75 |
+
"""Reachable stdlib scanner copied from the already validated task helper."""
|
| 76 |
+
try:
|
| 77 |
+
from dependency_scan import scan_stdlib
|
| 78 |
+
value,_,why=scan_stdlib(C,[script])
|
| 79 |
+
return None if why.startswith('unknown:') else value
|
| 80 |
+
except ImportError:
|
| 81 |
+
names=set(getattr(sys,'stdlib_module_names',()))|{'__future__'};seen=set();todo=[C/script]
|
| 82 |
+
while todo:
|
| 83 |
+
p=todo.pop()
|
| 84 |
+
if p in seen:continue
|
| 85 |
+
seen.add(p)
|
| 86 |
+
try:tree=ast.parse(p.read_text())
|
| 87 |
+
except(SyntaxError,UnicodeError,FileNotFoundError):return False
|
| 88 |
+
for n in ast.walk(tree):
|
| 89 |
+
mods=[a.name for a in n.names] if isinstance(n,ast.Import) else [n.module] if isinstance(n,ast.ImportFrom) and n.module else []
|
| 90 |
+
for mod in mods:
|
| 91 |
+
first=mod.split('.')[0]
|
| 92 |
+
if first in names:continue
|
| 93 |
+
local=C/(mod.replace('.','/')+'.py');pkg=C/mod.replace('.','/')/'__init__.py'
|
| 94 |
+
if local.is_file():todo.append(local)
|
| 95 |
+
elif pkg.is_file():todo.append(pkg)
|
| 96 |
+
else:return False
|
| 97 |
+
return True
|
| 98 |
+
|
| 99 |
+
def complete(r):return None if r['rc'] is None else r['rc']==0
|
| 100 |
+
|
| 101 |
+
def files_text():return {k:v.decode('utf-8') for k,v in source_inputs().items()}
|
| 102 |
+
|
| 103 |
+
def check_kegg():
|
| 104 |
+
src=files_text();panels=[src]
|
| 105 |
+
# More than two batches, malformed columns/empty fields, tied maximum,
|
| 106 |
+
# renamed IDs, missing join and lexicographic gene sorting.
|
| 107 |
+
links=[];names=[]
|
| 108 |
+
for i in range(1,24):
|
| 109 |
+
pid='hsa%05d'%i;links.append('hsa:g%02d\t%s'%(i,pid));names.append(pid+'\tName '+str(i))
|
| 110 |
+
links+=['hsa:z\thsa00002','hsa:a\thsa00002','hsa:a\thsa00002','hsa:y\thsa00003','hsa:b\thsa00003','\thsa00999','hsa:q\t','hsa:q\thsa00999\textra','bad','hsa:q\tmap00001']
|
| 111 |
+
panels.append({'link_pathway_hsa.txt':'\n'.join(reversed(links))+'\n','list_pathway_hsa.txt':'\n'.join(names[:-1])+'\n'})
|
| 112 |
+
panels.append({'link_pathway_hsa.txt':'hsa:z\thsa90100\nhsa:a\thsa90100\nhsa:a\thsa90100\nhsa:r\thsa90200\n','list_pathway_hsa.txt':'hsa90100\tRenamed\n'})
|
| 113 |
+
flags=[True]*6
|
| 114 |
+
for i,inputs in enumerate(panels):
|
| 115 |
+
mapping={};names={}
|
| 116 |
+
for line in inputs['link_pathway_hsa.txt'].splitlines():
|
| 117 |
+
a=line.split('\t')
|
| 118 |
+
if len(a)==2 and all(v.strip() for v in a) and a[1].strip().startswith('hsa'):mapping.setdefault(a[1].strip(),set()).add(a[0].strip())
|
| 119 |
+
for line in inputs['list_pathway_hsa.txt'].splitlines():
|
| 120 |
+
a=line.split('\t')
|
| 121 |
+
if len(a)==2 and all(v.strip() for v in a):names[a[0].strip()]=a[1].strip()
|
| 122 |
+
ids=sorted(mapping);want=[[pid,names.get(pid,'N/A'),str(len(mapping[pid])),','.join(sorted(mapping[pid]))] for pid in ids]
|
| 123 |
+
batches=['get/'+'+'.join(ids[j:j+10]) for j in range(0,len(ids),10)]
|
| 124 |
+
top=min(ids,key=lambda p:(-len(mapping[p]),p));r=run('kegg_map.py',inputs,['pathway_genes.tsv','get_batches.txt'],cwd_index=i)
|
| 125 |
+
values=[]
|
| 126 |
+
for root in r['roots']:
|
| 127 |
+
try:rows=list(csv.reader((root/'pathway_genes.tsv').open(),delimiter='\t'));batch=(root/'get_batches.txt').read_text().splitlines()
|
| 128 |
+
except(OSError,UnicodeError):rows=None;batch=None
|
| 129 |
+
rowok=rows==want
|
| 130 |
+
validrows=isinstance(rows,list) and all(len(row)==4 for row in rows)
|
| 131 |
+
uniqueok=validrows and [(row[0],row[2],row[3]) for row in rows]==[(row[0],row[2],row[3]) for row in want]
|
| 132 |
+
skipok=validrows and [row[0] for row in rows]==ids and complete(r)
|
| 133 |
+
values.append([rowok,uniqueok,skipok,batch==batches,'TOTAL: '+str(len(ids)) in r['stdout'].splitlines() and 'TOP: %s %s'%(top,len(mapping[top])) in r['stdout'].splitlines(),complete(r)])
|
| 134 |
+
if not values:values=[[None]*6] if r['rc'] is None else [[False]*6]
|
| 135 |
+
for j in range(6):flags[j]=tri([flags[j]]+[v[j] for v in values])
|
| 136 |
+
return flags
|
| 137 |
+
|
| 138 |
+
def allocate(rows):
|
| 139 |
+
position={r['id']:0 for r in rows};pref={r['id']:r['prefs'] for r in rows}
|
| 140 |
+
for _ in range(1+sum(len(p) for p in pref.values())):
|
| 141 |
+
groups=collections.defaultdict(list)
|
| 142 |
+
for eid,p in pref.items():groups[p[position[eid]]].append(eid)
|
| 143 |
+
advance={eid for group in groups.values() if len(group)>1 for eid in group if position[eid]+1<len(pref[eid])}
|
| 144 |
+
if not advance:break
|
| 145 |
+
for eid in advance:position[eid]+=1
|
| 146 |
+
result={}
|
| 147 |
+
for name,group in groups.items():
|
| 148 |
+
for i,eid in enumerate(sorted(group)):
|
| 149 |
+
final=name+('_'+str(i) if i else '')
|
| 150 |
+
result[eid]={'snake':final,'camel':''.join(p.capitalize() for p in final.split('_'))}
|
| 151 |
+
return result
|
| 152 |
+
|
| 153 |
+
def check_allocator():
|
| 154 |
+
src=files_text();a=json.loads(src['input_a.']);b=json.loads(src['input_b.'])
|
| 155 |
+
x=[{'id':'zebra','prefs':['same','second']},{'id':'ant','prefs':['same']},{'id':'bee','prefs':['second']},{'id':'c','prefs':['second']},{'id':'alone','prefs':['two_parts']}]
|
| 156 |
+
y=[{'id':'final-z','prefs':['solo']},{'id':'final-a','prefs':['solo']},{'id':'final-c','prefs':['solo']}]
|
| 157 |
+
panels=[(a,b),(b,a),(x,y),(list(reversed(y)),list(reversed(x)))]
|
| 158 |
+
flags=[True]*9
|
| 159 |
+
for i,(left,last) in enumerate(panels):
|
| 160 |
+
want=allocate(last);inputs={'input_a.':json.dumps(left),'input_b.':json.dumps(last)};r=run('allocator.py',inputs,['allocated_names.'],['input_a.','input_b.'],i)
|
| 161 |
+
bits=[]
|
| 162 |
+
for root in r['roots']:
|
| 163 |
+
got=load(root/'allocated_names.');shape=isinstance(got,dict) and set(got)==set(want) and all(isinstance(v,dict) and set(v)=={'snake','camel'} and all(isinstance(x,str) for x in v.values()) for v in got.values())
|
| 164 |
+
exact=shape and got==want;out=['%s -> %s (%s)'%(row['id'],want[row['id']]['snake'],want[row['id']]['camel']) for row in last]
|
| 165 |
+
snake=lambda eid: isinstance(got,dict) and isinstance(got.get(eid),dict) and got[eid].get('snake')==want[eid]['snake']
|
| 166 |
+
baseline=i<2
|
| 167 |
+
owners=[snake(eid) if baseline else True for eid in ('pet_owner','owner_user','user_model')]
|
| 168 |
+
trio=all(snake(eid) for eid in ('page_a','page_b','page_c')) if baseline else True
|
| 169 |
+
unchanged=snake('tag') if baseline else True
|
| 170 |
+
camel=isinstance(got,dict) and all(isinstance(got.get(eid),dict) and got[eid].get('camel')==want[eid]['camel'] for eid in want)
|
| 171 |
+
bits.append([complete(r)]+owners+[trio,unchanged,camel,shape,exact and r['stdout'].splitlines()==out])
|
| 172 |
+
if not bits:bits=[[None]*9] if r['rc'] is None else [[False]*9]
|
| 173 |
+
for j in range(9):flags[j]=tri([flags[j]]+[v[j] for v in bits])
|
| 174 |
+
return flags
|
| 175 |
+
|
| 176 |
+
def check_banner():
|
| 177 |
+
src=files_text();font=src['font.txt'];changed='GLYPH A\n#\n##\n###\n####\n#####\nGLYPH B\n.##\n#..\n#.#\n##.\n###\nGLYPH W\n#####\n#####\n#####\n#####\n#####\n'
|
| 178 |
+
cases=[(font,[]),(font,['HI']),(font,['AZA']),(font,['A Z A']),(font,['W'+'A'*15]),(font,['WW'+'A'*14]),(changed,['A B']),(changed,['W'*13+'A'*3]),(changed,['W'*14])]
|
| 179 |
+
flags=[True]*7;flags[0]=stdlib('banner.py')
|
| 180 |
+
for i,(body,args) in enumerate(cases):
|
| 181 |
+
glyphs={};key=None
|
| 182 |
+
for line in body.splitlines():
|
| 183 |
+
if line.startswith('GLYPH '):key=line[6:];glyphs[key]=[]
|
| 184 |
+
elif key is not None and len(glyphs[key])<5:glyphs[key].append(line.replace('.',' '))
|
| 185 |
+
# The supplied GLYPH D2 is a non-character label; it does not override D.
|
| 186 |
+
r=run('banner.py',{'font.txt':body},[],args,i)
|
| 187 |
+
if not args:flags[0]=tri([flags[0],None if r['rc'] is None else r['rc']==2 and bool(r['stderr'].strip()) and not r['stdout'].strip()]);continue
|
| 188 |
+
text=args[0];parts=[glyphs.get(c,[' '*4]*5) for c in text];art=[' '.join(g[j] for g in parts) for j in range(5)];width=max(map(len,art))
|
| 189 |
+
if width>80:
|
| 190 |
+
flags[6]=tri([flags[6],None if r['rc'] is None else r['rc']==0 and r['stdout'].strip()=='TOO WIDE']);continue
|
| 191 |
+
lines=r['stdout'].splitlines();artok=lines[:5]==art
|
| 192 |
+
for j in [1,2]:flags[j]=tri([flags[j],artok])
|
| 193 |
+
flags[3]=tri([flags[3],len(lines)==7 and lines[5]=='-'*80]);flags[4]=tri([flags[4],len(lines)==7 and lines[6]==text.center(80)])
|
| 194 |
+
if any(c not in glyphs for c in text):flags[5]=tri([flags[5],artok])
|
| 195 |
+
return flags
|
| 196 |
+
|
| 197 |
+
def check_policy():
|
| 198 |
+
src=files_text();names=list(src);request=json.loads(src[next(k for k in names if 'request' in k)]);policy=json.loads(src[next(k for k in names if 'policy' in k)])
|
| 199 |
+
cases=[(request,policy,1)]
|
| 200 |
+
for updates,owner in [({'allowAutoPay':False},4),({'autoPayDomains':[]},7),({'dailyLimit':.01,'perTxLimit':1},5),({'perTxLimit':.01,'dailyLimit':1},5),({'allowedChains':[]},6),({'allowedTokens':[]},6),({'dailyLimit':request['amount'],'perTxLimit':request['amount']},5)]:
|
| 201 |
+
p=dict(policy);p.update(updates);cases.append((request,p,owner))
|
| 202 |
+
for updates,owner in [({'domain':'changed.example'},7),({'chain':'changed-chain'},6),({'token':'changed-token'},6),({'amount':.75},5)]:
|
| 203 |
+
r=dict(request);r.update(updates);cases.append((r,policy,owner))
|
| 204 |
+
flags=[True]*8;flags[3]=stdlib('policy_check.py')
|
| 205 |
+
for i,(req,pol,owner) in enumerate(cases):
|
| 206 |
+
limited=req['amount']>pol['perTxLimit'] or req['amount']>pol['dailyLimit'] or req['chain']not in pol['allowedChains'] or req['token']not in pol['allowedTokens']
|
| 207 |
+
expected='rejected' if limited else 'autopay' if pol['allowAutoPay'] and req['domain']in pol['autoPayDomains'] else 'confirmationRequired'
|
| 208 |
+
rp='probe-request-%d.json'%i;pp='probe-policy-%d.json'%i;runres=run('policy_check.py',{rp:json.dumps(req),pp:json.dumps(pol)},['decision.'],[rp,pp],i)
|
| 209 |
+
bits=[]
|
| 210 |
+
for root in runres['roots']:
|
| 211 |
+
d=load(root/'decision.');shape=isinstance(d,dict) and all(k in d for k in ('decision','reason','amount','domain','chain','token')) and isinstance(d['decision'],str) and isinstance(d['reason'],str) and bool(d['reason'].strip())
|
| 212 |
+
echo=shape and all(type(d[k]) is type(req[k]) and d[k]==req[k] for k in ('domain','chain','token')) and type(d['amount'])in(int,float) and not isinstance(d['amount'],bool) and d['amount']==req['amount']
|
| 213 |
+
bits.append((shape and echo,shape and d['decision']==expected))
|
| 214 |
+
flags[0]=tri([flags[0]]+[v[0]for v in bits] if bits else [flags[0],None if runres['rc']is None else False]);flags[2]=tri([flags[2],complete(runres)])
|
| 215 |
+
flags[owner]=tri([flags[owner]]+[v[1]for v in bits] if bits else [flags[owner],None if runres['rc']is None else False])
|
| 216 |
+
return flags
|
| 217 |
+
|
| 218 |
+
def check_merge():
|
| 219 |
+
src=files_text();panels=[(json.loads(src['local.']),json.loads(src['incoming.']))]
|
| 220 |
+
panels.extend([({'patterns':[{'id':'z','updated_at':'2025-01-01','v':1},{'id':'b','updated_at':'2026-01-01','v':2}]},{'patterns':[{'id':'z','updated_at':'2026-01-01','v':3},{'id':'a','updated_at':'2024-01-01','v':4}]}),({'patterns':[]},{'patterns':[{'id':'new','updated_at':'2020-01-01','payload':{'x':3}}]}),({'patterns':[{'id':'left','updated_at':'2021-01-01'}]},{'patterns':[]})])
|
| 221 |
+
flags=[True]*7;flags[6]=stdlib('merge_patterns.py')
|
| 222 |
+
for i,(local,incoming) in enumerate(panels):
|
| 223 |
+
a={r['id']:r for r in local['patterns']};b={r['id']:r for r in incoming['patterns']};merged=dict(a)
|
| 224 |
+
for key,value in b.items():
|
| 225 |
+
if key not in merged or value['updated_at']>merged[key]['updated_at']:merged[key]=value
|
| 226 |
+
want=[merged[key] for key in sorted(merged)];r=run('merge_patterns.py',{'probe-local.':json.dumps(local),'probe-incoming.':json.dumps(incoming)},['probe-merged.'],['probe-local.','probe-incoming.','probe-merged.'],i)
|
| 227 |
+
documents=[load(root/'probe-merged.') for root in r['roots']]
|
| 228 |
+
bits=[]
|
| 229 |
+
for document in documents:
|
| 230 |
+
pats=document.get('patterns') if isinstance(document,dict) else None
|
| 231 |
+
shape=isinstance(pats,list) and all(isinstance(p,dict) and isinstance(p.get('id'),str) for p in pats)
|
| 232 |
+
byid={p['id']:p for p in pats} if shape else {}
|
| 233 |
+
ids=[p['id'] for p in pats] if shape else []
|
| 234 |
+
incoming_wins=[k for k in set(a)&set(b) if b[k]['updated_at']>a[k]['updated_at']]
|
| 235 |
+
local_wins=[k for k in set(a)&set(b) if a[k]['updated_at']>b[k]['updated_at']]
|
| 236 |
+
only=(set(a)^set(b))
|
| 237 |
+
bits.append([shape and ids==sorted(merged),all(byid.get(k)==merged[k]for k in incoming_wins),all(byid.get(k)==merged[k]for k in local_wins),all(byid.get(k)==merged[k]for k in only)])
|
| 238 |
+
try:stdout=json.loads(r['stdout'],object_pairs_hook=unique);outok=type(stdout.get('total'))is int and type(stdout.get('conflicts_resolved'))is int and stdout=={'total':len(want),'conflicts_resolved':len(set(a)&set(b))}
|
| 239 |
+
except(ValueError,AttributeError,TypeError):outok=False
|
| 240 |
+
flags[0]=tri([flags[0],complete(r),bool(r['roots'])])
|
| 241 |
+
for j in (1,2,3,4):flags[j]=tri([flags[j]]+[v[j-1]for v in bits] if bits else [flags[j],None if r['rc']is None else False])
|
| 242 |
+
flags[5]=tri([flags[5],outok])
|
| 243 |
+
return flags
|
| 244 |
+
|
| 245 |
+
def nist_want(inputs):
|
| 246 |
+
date=datetime.date.fromisoformat(next(line.split(':',1)[1].strip() for line in inputs['ssp_excerpt.md'].splitlines() if line.startswith('Assessment Date:')))
|
| 247 |
+
objectives=[]
|
| 248 |
+
for line in inputs['objectives.txt'].splitlines():
|
| 249 |
+
if line.strip():key,text=line.split(':',1);objectives.append((key.strip(),text.strip()))
|
| 250 |
+
events=[json.loads(line) for line in inputs['test_records.l'].splitlines() if line.strip()]
|
| 251 |
+
rows=[]
|
| 252 |
+
for key,text in objectives:
|
| 253 |
+
matching=[e for e in events if e.get('objective_id')==key and e.get('status')=='completed' and e.get('site_type')=='alternate']
|
| 254 |
+
support=[e['event_id'] for e in matching if 0<=(date-datetime.date.fromisoformat(e['date'])).days<=365]
|
| 255 |
+
stale=[e['event_id'] for e in matching if (date-datetime.date.fromisoformat(e['date'])).days>365]
|
| 256 |
+
rows.append(dict(objective_id=key,objective_text=text,satisfied=bool(support),supporting_events=support,stale_events=stale))
|
| 257 |
+
return date.isoformat(),rows
|
| 258 |
+
|
| 259 |
+
def nist_assess(data,inputs):
|
| 260 |
+
date,want=nist_want(inputs)
|
| 261 |
+
if not isinstance(data,dict):return [False]*5
|
| 262 |
+
rows=data.get('objectives');shape=isinstance(rows,list) and len(rows)==len(want) and all(isinstance(r,dict) and isinstance(r.get('objective_id'),str) for r in rows)
|
| 263 |
+
found={r['objective_id']:r for r in rows} if shape else {}
|
| 264 |
+
keys={r['objective_id'] for r in want};textok=shape and len(found)==len(rows) and set(found)==keys and all(found[r['objective_id']].get('objective_text')==r['objective_text'] for r in want)
|
| 265 |
+
owned=[]
|
| 266 |
+
for row in want:
|
| 267 |
+
got=found.get(row['objective_id'],{});arrays=all(isinstance(got.get(k),list) and all(isinstance(x,str) for x in got[k]) and len(got[k])==len(set(got[k])) and set(got[k])==set(row[k]) for k in ('supporting_events','stale_events'))
|
| 268 |
+
owned.append(type(got.get('satisfied'))is bool and got['satisfied']==row['satisfied'] and arrays)
|
| 269 |
+
return [data.get('assessment_date')==date,textok,owned[0] if owned else True,all(owned[1:]),type(data.get('overall_compliant'))is bool and data['overall_compliant']==all(r['satisfied'] for r in want)]
|
| 270 |
+
|
| 271 |
+
def check_nist():
|
| 272 |
+
src=files_text();panels=[src]
|
| 273 |
+
date='2026-01-01';cut=datetime.date.fromisoformat(date)-datetime.timedelta(days=365)
|
| 274 |
+
events=[{'event_id':'boundary','objective_id':'NEW-A','site_type':'alternate','status':'completed','date':cut.isoformat()},{'event_id':'older','objective_id':'NEW-A','site_type':'alternate','status':'completed','date':(cut-datetime.timedelta(days=1)).isoformat()},{'event_id':'today','objective_id':'NEW-B','site_type':'alternate','status':'completed','date':date},{'event_id':'future','objective_id':'NEW-B','site_type':'alternate','status':'completed','date':'2026-01-02'},{'event_id':'primary','objective_id':'NEW-B','site_type':'primary','status':'completed','date':date},{'event_id':'planned','objective_id':'NEW-A','site_type':'alternate','status':'planned','date':date}]
|
| 275 |
+
variant={'ssp_excerpt.md':'Title\nAssessment Date: '+date+'\n','objectives.txt':'\nNEW-A: First: with a colon\n\nNEW-B: Second goal\n','test_records.l':'\n'.join(json.dumps(e)for e in events)+'\n'};panels.append(variant)
|
| 276 |
+
missing=dict(variant);missing['test_records.l']='\n'.join(json.dumps(e)for e in events if e['event_id']not in ('today','future'))+'\n';panels.append(missing)
|
| 277 |
+
flags=[stdlib('assess.py')]+nist_assess(load(C/'report.'),src)+[True]
|
| 278 |
+
for i,inputs in enumerate(panels):
|
| 279 |
+
r=run('assess.py',inputs,['report.'],cwd_index=i);flags[0]=tri([flags[0],complete(r),bool(r['roots'])])
|
| 280 |
+
for root in r['roots'] or [None]:
|
| 281 |
+
bits=nist_assess(load(root/'report.'),inputs) if root is not None else [None]*5 if r['rc']is None else [False]*5
|
| 282 |
+
for j in range(5):flags[j+1]=tri([flags[j+1],bits[j]])
|
| 283 |
+
_,want=nist_want(inputs);line='CP-4(2): %d/%d objectives satisfied'%(sum(row['satisfied']for row in want),len(want));flags[6]=tri([flags[6],r['stdout'].splitlines()==[line]])
|
| 284 |
+
return flags
|
| 285 |
+
|
| 286 |
+
def deploy_want(inputs):
|
| 287 |
+
names=sorted(set(line.strip() for line in inputs['inventory.txt'].splitlines() if line.strip()));events={}
|
| 288 |
+
for line in inputs['deploy.log'].splitlines():
|
| 289 |
+
if not line.strip():continue
|
| 290 |
+
date,name,status=line.split()
|
| 291 |
+
if name not in events or date>events[name][0]:events[name]=(date,status)
|
| 292 |
+
states={'SUCCEEDED':'OK','STARTED':'IN_PROGRESS','FAILED':'BROKEN','ROLLED_BACK':'ROLLED_BACK'}
|
| 293 |
+
rows=[{'service':name,'status':states[events[name][1]] if name in events else 'MISSING','last_timestamp':events[name][0] if name in events else None}for name in names]
|
| 294 |
+
return rows,all(row['status']=='OK'for row in rows)
|
| 295 |
+
|
| 296 |
+
def deploy_assess(data,inputs,fresh=False):
|
| 297 |
+
want,healthy=deploy_want(inputs)
|
| 298 |
+
if not isinstance(data,dict):return [False]*8
|
| 299 |
+
rows=data.get('services');shape=isinstance(rows,list)and all(isinstance(row,dict)and isinstance(row.get('service'),str)for row in rows)
|
| 300 |
+
byid={row.get('service'):row for row in rows}if shape else {}
|
| 301 |
+
order=shape and [row.get('service')for row in rows]==[row['service']for row in want]
|
| 302 |
+
if set(byid)!=set(row['service']for row in want):order=False
|
| 303 |
+
owners=[]
|
| 304 |
+
baseline=set(row['service']for row in want)=={'api','worker','frontend','cache','auth'}
|
| 305 |
+
for name in ('api','worker','frontend','cache','auth'):
|
| 306 |
+
expected=next((row for row in want if row['service']==name),None)
|
| 307 |
+
owners.append(byid.get(name)==expected if expected is not None else True)
|
| 308 |
+
if not baseline:owners=[all(byid.get(row['service'])==row for row in want)]*5
|
| 309 |
+
healthyok=type(data.get('healthy'))is bool and data['healthy']==healthy
|
| 310 |
+
timeok=False
|
| 311 |
+
if isinstance(data.get('generated_at'),str):
|
| 312 |
+
try:
|
| 313 |
+
stamp=datetime.datetime.fromisoformat(data['generated_at'].replace('Z','+00:00'));timeok=stamp.utcoffset()==datetime.timedelta(0)
|
| 314 |
+
if fresh:timeok=timeok and abs((datetime.datetime.now(datetime.timezone.utc)-stamp).total_seconds())<=180
|
| 315 |
+
except ValueError:pass
|
| 316 |
+
return [order]+owners+[healthyok,timeok]
|
| 317 |
+
|
| 318 |
+
def check_deployment():
|
| 319 |
+
src=files_text();panels=[src]
|
| 320 |
+
panels.append({'inventory.txt':'delta\nalpha\nbravo\ncharlie\necho\n','deploy.log':'2026-01-02T10:00:00Z alpha SUCCEEDED\n2026-01-01T10:00:00Z alpha FAILED\n2026-01-02T10:00:00Z bravo STARTED\n2026-01-02T10:00:00Z charlie FAILED\n2026-01-02T10:00:00Z delta ROLLED_BACK\n2026-01-03T10:00:00Z outsider SUCCEEDED\n'})
|
| 321 |
+
panels.append({'inventory.txt':'api\nworker\nfrontend\ncache\nauth\n','deploy.log':'\n'.join('2026-01-02T10:00:00Z '+name+' SUCCEEDED'for name in ['worker','cache','auth','api','frontend'])+'\n'})
|
| 322 |
+
saved=deploy_assess(load(C/'report.'),src);flags=[stdlib('check_deployment.py')]+saved[:7]+[True,saved[7]]
|
| 323 |
+
for i,inputs in enumerate(panels):
|
| 324 |
+
r=run('check_deployment.py',inputs,['report.'],cwd_index=i);flags[0]=tri([flags[0],complete(r),bool(r['roots'])])
|
| 325 |
+
for root in r['roots']or[None]:
|
| 326 |
+
bits=deploy_assess(load(root/'report.'),inputs,True)if root else [None]*8 if r['rc']is None else [False]*8
|
| 327 |
+
for j in range(7):flags[j+1]=tri([flags[j+1],bits[j]])
|
| 328 |
+
flags[9]=tri([flags[9],bits[7]])
|
| 329 |
+
_,healthy=deploy_want(inputs);flags[8]=tri([flags[8],None if r['rc']is None else r['rc']==(0 if healthy else 1)])
|
| 330 |
+
return flags
|
| 331 |
+
|
| 332 |
+
CATALOG=[('CF2',49.996806),('C2F4',99.993613),('C3F6',149.990419)]
|
| 333 |
+
|
| 334 |
+
def pfas_want(data):
|
| 335 |
+
rows=[];counts={f['feature_id']:0 for f in data['features']}
|
| 336 |
+
for f in data['features']:
|
| 337 |
+
for frag in f['fragment_mz']:
|
| 338 |
+
difference=f['precursor_mz']-frag
|
| 339 |
+
for loss,mass in CATALOG:
|
| 340 |
+
ppm=(difference-mass)/mass*1e6
|
| 341 |
+
if abs(ppm)<=5:
|
| 342 |
+
rows.append([f['feature_id'],format(frag,'.4f'),format(difference,'.4f'),loss,format(ppm,'.2f')]);counts[f['feature_id']]+=1
|
| 343 |
+
rows.sort(key=lambda row:(row[0],float(row[1])))
|
| 344 |
+
return rows,counts
|
| 345 |
+
|
| 346 |
+
def pfas_assess(root,data):
|
| 347 |
+
want,counts=pfas_want(data)
|
| 348 |
+
try:allrows=list(csv.reader((root/'hits.csv').open(newline='')))
|
| 349 |
+
except(OSError,UnicodeError,csv.Error):allrows=[]
|
| 350 |
+
header=allrows[:1]==[['feature_id','fragment_mz','mass_difference','loss_type','ppm_error']];rows=allrows[1:]if header else[]
|
| 351 |
+
full=header and rows==want
|
| 352 |
+
# ppm is computed before display rounding. Recomputing it from a four-place
|
| 353 |
+
# displayed mass difference wrongly rejects valid near-boundary output.
|
| 354 |
+
ppmok=header and len(rows)==len(want)and all(len(a)==5 and a[0]==b[0]and a[3:]==b[3:]for a,b in zip(rows,want))
|
| 355 |
+
actual=load(root/'scores.');scoreok=isinstance(actual,dict)and list(actual)==list(counts)and all(type(actual.get(k))is int and actual[k]==v for k,v in counts.items())
|
| 356 |
+
return[full,ppmok,scoreok,header]
|
| 357 |
+
|
| 358 |
+
def check_pfas():
|
| 359 |
+
src=files_text();base=json.loads(src['spectra.']);features=[]
|
| 360 |
+
for i,(name,mass)in enumerate(CATALOG):
|
| 361 |
+
features.append({'feature_id':'R'+str(3-i),'precursor_mz':500.123456,'fragment_mz':[500.123456-mass*(1+p/1e6)for p in (-5.01,-4.99,0,4.99,5.01)]})
|
| 362 |
+
features.append({'feature_id':'ZERO','precursor_mz':10,'fragment_mz':[1,9]})
|
| 363 |
+
panels=[base,{'tolerance_ppm':5,'features':features}]
|
| 364 |
+
flags=[stdlib('annotate.py')]+pfas_assess(C,base)
|
| 365 |
+
for i,data in enumerate(panels):
|
| 366 |
+
r=run('annotate.py',{'spectra.':json.dumps(data)},['hits.csv','scores.'],cwd_index=i);flags[0]=tri([flags[0],complete(r)])
|
| 367 |
+
for root in r['roots']or[None]:
|
| 368 |
+
bits=pfas_assess(root,data)if root else [None]*4 if r['rc']is None else [False]*4
|
| 369 |
+
for j in range(4):flags[j+1]=tri([flags[j+1],bits[j]])
|
| 370 |
+
return flags
|
| 371 |
+
|
| 372 |
+
def k3s_assess(root,server,token):
|
| 373 |
+
cfgpath=root/'out/etc/rancher/k3s/config.yaml';unitpath=root/'out/etc/systemd/system/k3s-agent.service'
|
| 374 |
+
try:
|
| 375 |
+
text=cfgpath.read_text();pairs={};valid=True
|
| 376 |
+
try:
|
| 377 |
+
import yaml
|
| 378 |
+
class UniqueLoader(yaml.SafeLoader):pass
|
| 379 |
+
def mapping(loader,node,deep=False):
|
| 380 |
+
return unique([(loader.construct_object(k,deep=deep),loader.construct_object(v,deep=deep))for k,v in node.value])
|
| 381 |
+
UniqueLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,mapping)
|
| 382 |
+
pairs=yaml.load(text,Loader=UniqueLoader)
|
| 383 |
+
except ImportError:
|
| 384 |
+
try:pairs=json.loads(text,object_pairs_hook=unique)
|
| 385 |
+
except ValueError:
|
| 386 |
+
for line in text.splitlines():
|
| 387 |
+
if not line.strip()or line.lstrip().startswith('#'):continue
|
| 388 |
+
match=re.fullmatch(r'(server|token):\s*(.+?)\s*',line)
|
| 389 |
+
if not match or match[1]in pairs:valid=False;break
|
| 390 |
+
value=match[2]
|
| 391 |
+
if len(value)>1 and value[0]in ('"',"'")and value[-1]==value[0]:value=value[1:-1]
|
| 392 |
+
pairs[match[1]]=value
|
| 393 |
+
valid=valid and isinstance(pairs,dict)and set(pairs)=={'server','token'}and all(isinstance(v,str)for v in pairs.values())
|
| 394 |
+
except Exception:valid=False;pairs={}
|
| 395 |
+
try:
|
| 396 |
+
unit=configparser.RawConfigParser(strict=True);unit.optionxform=str;unit.read_string(unitpath.read_text())
|
| 397 |
+
exact=unit.get('Service','ExecStart',fallback='')=='/usr/local/bin/k3s agent'
|
| 398 |
+
required={'Unit':{'Description':'k3s agent','After':'network-online.target','Wants':'network-online.target'},'Service':{'Type':'exec','Restart':'always','RestartSec':'5'},'Install':{'WantedBy':'multi-user.target'}}
|
| 399 |
+
fields=all(unit.get(section,key,fallback=None)==value for section,fields in required.items()for key,value in fields.items())
|
| 400 |
+
except(configparser.Error,OSError,UnicodeError):exact=False;fields=False
|
| 401 |
+
try:modes=stat.S_IMODE(cfgpath.stat().st_mode)==0o600 and stat.S_IMODE(unitpath.stat().st_mode)==0o600
|
| 402 |
+
except OSError:modes=False
|
| 403 |
+
return[valid and pairs.get('server')==server,valid and pairs.get('token')==token.strip(),exact,fields,modes]
|
| 404 |
+
|
| 405 |
+
def check_k3s():
|
| 406 |
+
src=files_text();server=re.search(r'K3S_SERVER_URL=([^\s\n]+)',src['charly.yml']).group(1);token=src['cluster_token.txt']
|
| 407 |
+
scripts=sorted(p.relative_to(C).as_posix()for p in C.rglob('*.py')if not any(x in p.parts for x in ('.skill-search','.claude','.git','__pycache__')))
|
| 408 |
+
if not scripts:return[False]*6
|
| 409 |
+
panels=[(src,server,token)]
|
| 410 |
+
changed=dict(src);changed['charly.yml']=src['charly.yml'].replace(server,'https://changed-r9.example:9443');changed['cluster_token.txt']='r9-private-agent-token\n';panels.append((changed,'https://changed-r9.example:9443',changed['cluster_token.txt']))
|
| 411 |
+
# A decoy deployment appears first; the actual selector is add_candy.
|
| 412 |
+
decoy=' ignored:\n "vm:decoy":\n target: vm\n add_candy: [other-service]\n env:\n - K3S_SERVER_URL=https://must-not-use.example:9999\n'
|
| 413 |
+
branch=dict(changed);branch['charly.yml']=changed['charly.yml'].replace('deployments:\n','deployments:\n'+decoy);panels.append((branch,panels[1][1],panels[1][2]))
|
| 414 |
+
output=['out/etc/rancher/k3s/config.yaml','out/etc/systemd/system/k3s-agent.service']
|
| 415 |
+
chosen=None
|
| 416 |
+
for script in scripts:
|
| 417 |
+
for args in ((),('--out','out'),('--output-root','out'),('out',)):
|
| 418 |
+
r=run(script,src,output,args)
|
| 419 |
+
if any(all(k3s_assess(root,server,token))for root in r['roots']):chosen=(script,args);break
|
| 420 |
+
if chosen:break
|
| 421 |
+
if chosen is None:return[False]*6
|
| 422 |
+
script,args=chosen;flags=k3s_assess(C,server,token)+[stdlib(script)]
|
| 423 |
+
for i,(inputs,sv,tv)in enumerate(panels):
|
| 424 |
+
r=run(script,inputs,output,args,i)
|
| 425 |
+
for root in r['roots']or[None]:
|
| 426 |
+
bits=k3s_assess(root,sv,tv)if root else [None]*5 if r['rc']is None else [False]*5
|
| 427 |
+
for j in range(5):flags[j]=tri([flags[j],bits[j]])
|
| 428 |
+
flags[5]=tri([flags[5],complete(r)])
|
| 429 |
+
return flags
|
| 430 |
+
|
| 431 |
+
def route_want(files):
|
| 432 |
+
routes=[];skipped=0
|
| 433 |
+
for filename in sorted(files):
|
| 434 |
+
parts=filename.split('/')
|
| 435 |
+
if not filename.startswith('webapp/app/'):continue
|
| 436 |
+
base=parts[-1]
|
| 437 |
+
page=re.fullmatch(r'page\.(tsx|ts|jsx|js)',base)is not None
|
| 438 |
+
handler=base=='route.ts'
|
| 439 |
+
if not page and not handler:continue
|
| 440 |
+
if 'api'in parts[2:-1]or handler:skipped+=1;continue
|
| 441 |
+
dirs=parts[2:-1];visible=[p for p in dirs if not(p.startswith('(')and p.endswith(')'))];url='/'+'/'.join(visible)
|
| 442 |
+
dynamic=any('['in p and']'in p for p in visible)
|
| 443 |
+
auth='(protected)'in dirs or any(p in('admin','host','dashboard')for p in visible)
|
| 444 |
+
routes.append(dict(url=url,file=filename,classification='auth-walled'if auth else'dynamic'if dynamic else'public',dynamic=dynamic))
|
| 445 |
+
routes.sort(key=lambda row:row['url'])
|
| 446 |
+
counts=dict(routes_walked=len(routes),routes_404=0,routes_auth_walled=sum(row['classification']=='auth-walled'for row in routes),dynamic_routes_unvalidated=sum(row['dynamic']for row in routes),routes_api_skipped=skipped)
|
| 447 |
+
plan=[dict(row,bogus_id_probe=re.sub(r'\[[^\]]+\]','__bogus__',row['url'])if row['dynamic']else None)for row in routes]
|
| 448 |
+
return routes,counts,plan
|
| 449 |
+
|
| 450 |
+
def route_assess(data,files):
|
| 451 |
+
if not isinstance(data,dict):return[False]*6
|
| 452 |
+
expected,counts,plans=route_want(files);rows=data.get('routes');shape=isinstance(rows,list)and len(rows)==len(expected)and all(isinstance(r,dict)for r in rows)
|
| 453 |
+
identity=shape and all(all(got.get(k)==want[k]for k in('url','file'))for got,want in zip(rows,expected))
|
| 454 |
+
classifications=shape and all(got.get('classification')==want['classification']for got,want in zip(rows,expected))
|
| 455 |
+
dynamics=shape and all(type(got.get('dynamic'))is bool and got['dynamic']==want['dynamic']for got,want in zip(rows,expected))
|
| 456 |
+
seen=data.get('counts');countok=isinstance(seen,dict)and set(seen)==set(counts)and all(type(seen.get(k))is int and seen[k]==v for k,v in counts.items())
|
| 457 |
+
plan=data.get('walk_plan');planok=isinstance(plan,list)and len(plan)==len(plans)and all(isinstance(got,dict)and got.get('url')==want['url']and'bogus_id_probe'in got and got['bogus_id_probe']==want['bogus_id_probe']for got,want in zip(plan,plans))
|
| 458 |
+
return[shape,identity,classifications,dynamics,countok,planok]
|
| 459 |
+
|
| 460 |
+
def check_routes():
|
| 461 |
+
baseline=files_text();changed=dict(baseline)
|
| 462 |
+
for path in ['webapp/app/(public)/reports/page.js','webapp/app/(protected)/projects/[team]/[item]/page.jsx','webapp/app/host/[id]/page.ts','webapp/app/search/page.js','webapp/app/api/hidden/page.tsx','webapp/app/service/route.ts']:
|
| 463 |
+
changed[path]='export default function Page(){}\n'
|
| 464 |
+
changed.pop('webapp/app/about/page.tsx',None)
|
| 465 |
+
panels=[baseline,changed];flags=[stdlib('discover_routes.py')]+[True]*6
|
| 466 |
+
for i,files in enumerate(panels):
|
| 467 |
+
updates={k:None for k in baseline if k not in files};updates.update(files)
|
| 468 |
+
r=run('discover_routes.py',updates,['routes.json'],cwd_index=i);flags[0]=tri([flags[0],None if r['rc']is None else r['rc']==0])
|
| 469 |
+
for root in r['roots']or[None]:
|
| 470 |
+
bits=route_assess(load(root/'routes.json'),files)if root else[None]*6 if r['rc']is None else[False]*6
|
| 471 |
+
for j in range(6):flags[j+1]=tri([flags[j+1],bits[j]])
|
| 472 |
+
for root in [Path('/app'),Path('/workspace')]:
|
| 473 |
+
unchanged=all((root/path).is_file()and(root/path).read_bytes()==body.encode()for path,body in files.items())
|
| 474 |
+
flags[0]=tri([flags[0],unchanged])
|
| 475 |
+
return flags
|
| 476 |
+
|
| 477 |
+
def manifest_valid(obj):
|
| 478 |
+
if not isinstance(obj,dict):return False
|
| 479 |
+
kind=obj.get('kind');version=obj.get('apiVersion')
|
| 480 |
+
if (version,kind)not in [('agents.x-k8s.io/v1alpha1','Sandbox')]+[('extensions.agents.x-k8s.io/v1alpha1',k)for k in ('SandboxTemplate','SandboxClaim','SandboxWarmPool')]:return False
|
| 481 |
+
metadata=obj.get('metadata');spec=obj.get('spec')
|
| 482 |
+
if not isinstance(metadata,dict)or not isinstance(metadata.get('name'),str)or not metadata['name'].strip()or not isinstance(spec,dict):return False
|
| 483 |
+
if kind in('Sandbox','SandboxTemplate'):
|
| 484 |
+
pod=spec.get('podTemplate');body=pod.get('spec')if isinstance(pod,dict)else None;containers=body.get('containers')if isinstance(body,dict)else None
|
| 485 |
+
if not isinstance(containers,list)or not containers or not all(isinstance(c,dict)and all(isinstance(c.get(key),str)and c[key].strip()for key in('name','image'))for c in containers):return False
|
| 486 |
+
if kind=='Sandbox':
|
| 487 |
+
if 'replicas'in spec and(type(spec['replicas'])is not int or spec['replicas']not in(0,1)):return False
|
| 488 |
+
if 'shutdownTime'in spec:
|
| 489 |
+
value=spec['shutdownTime']
|
| 490 |
+
if not isinstance(value,str)or not re.fullmatch(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z',value):return False
|
| 491 |
+
try:datetime.datetime.strptime(value,'%Y-%m-%dT%H:%M:%SZ')
|
| 492 |
+
except ValueError:return False
|
| 493 |
+
if kind=='SandboxTemplate'and'networkPolicy'in spec:
|
| 494 |
+
net=spec['networkPolicy']
|
| 495 |
+
if not isinstance(net,dict)or set(net)-{'ingress','egress'}or not all(isinstance(v,list)for v in net.values()):return False
|
| 496 |
+
if kind in('SandboxClaim','SandboxWarmPool'):
|
| 497 |
+
ref=spec.get('sandboxTemplateRef')
|
| 498 |
+
if not isinstance(ref,dict)or not isinstance(ref.get('name'),str)or not ref['name'].strip():return False
|
| 499 |
+
if kind=='SandboxWarmPool'and(type(spec.get('replicas'))is not int or spec['replicas']<0):return False
|
| 500 |
+
return True
|
| 501 |
+
|
| 502 |
+
def manifest_cases():
|
| 503 |
+
pod={'spec':{'containers':[{'name':'run','image':'python:3.12'}]}}
|
| 504 |
+
clean={
|
| 505 |
+
'sandbox':{'apiVersion':'agents.x-k8s.io/v1alpha1','kind':'Sandbox','metadata':{'name':'s'},'spec':{'podTemplate':pod,'replicas':1,'shutdownTime':'2026-01-01T00:00:00Z'}},
|
| 506 |
+
'template':{'apiVersion':'extensions.agents.x-k8s.io/v1alpha1','kind':'SandboxTemplate','metadata':{'name':'t'},'spec':{'podTemplate':pod,'networkPolicy':{'ingress':[],'egress':[]}}},
|
| 507 |
+
'claim':{'apiVersion':'extensions.agents.x-k8s.io/v1alpha1','kind':'SandboxClaim','metadata':{'name':'c'},'spec':{'sandboxTemplateRef':{'name':'t'}}},
|
| 508 |
+
'pool':{'apiVersion':'extensions.agents.x-k8s.io/v1alpha1','kind':'SandboxWarmPool','metadata':{'name':'p'},'spec':{'replicas':0,'sandboxTemplateRef':{'name':'t'}}}}
|
| 509 |
+
out={key+'-valid.json':value for key,value in clean.items()}
|
| 510 |
+
changes=[('sandbox','apiVersion','bad/v1'),('sandbox','metadata',{}),('sandbox','metadata',{'name':''}),('sandbox','metadata',{'name':0}),('sandbox','spec.replicas',True),('sandbox','spec.replicas',2),('sandbox','spec.replicas',0),('sandbox','spec.shutdownTime','2025-02-30T00:00:00Z'),('sandbox','spec.shutdownTime','2026-01-01T00:00:00+00:00'),('sandbox','spec.podTemplate.spec.containers',[]),('sandbox','spec.podTemplate.spec.containers',[{'name':'x'}]),('sandbox','spec.podTemplate.spec.containers',[{'image':'x'}]),('template','spec.networkPolicy',{'policyTypes':[]}),('template','spec.networkPolicy',{'ingress':{}}),('template','spec.networkPolicy',{'egress':{}}),('template','spec.podTemplate',{}),('claim','spec.sandboxTemplateRef',{}),('claim','spec.sandboxTemplateRef',{'name':False}),('pool','spec.replicas',-1),('pool','spec.replicas',True),('pool','spec.sandboxTemplateRef',{'name':''})]
|
| 511 |
+
for i,(kind,path,value)in enumerate(changes):
|
| 512 |
+
obj=json.loads(json.dumps(clean[kind]));parts=path.split('.');parent=obj
|
| 513 |
+
for key in parts[:-1]:parent=parent[key]
|
| 514 |
+
parent[parts[-1]]=value;out['probe-%s-%02d.json'%(kind,i)]=obj
|
| 515 |
+
return out
|
| 516 |
+
|
| 517 |
+
def manifest_assess(text,files):
|
| 518 |
+
if not isinstance(text,str):return[False]*5
|
| 519 |
+
lines=text.splitlines();expected=sorted(files);parsed={};formatok=len(lines)==len(expected)
|
| 520 |
+
for name,line in zip(expected,lines):
|
| 521 |
+
match=re.fullmatch(re.escape(name)+r': (PASS|FAIL)(?:: (.+))?',line)
|
| 522 |
+
if not match:formatok=False;continue
|
| 523 |
+
state,reason=match.groups();good=state=='PASS'and reason is None or state=='FAIL'and bool(reason and reason.strip())
|
| 524 |
+
if not good:formatok=False
|
| 525 |
+
parsed[name]=state
|
| 526 |
+
correct={key:('PASS'if manifest_valid(value)else'FAIL')for key,value in files.items()}
|
| 527 |
+
exact=parsed==correct
|
| 528 |
+
group=lambda kind:all(parsed.get(name)==state for name,state in correct.items()if files[name].get('kind')==kind)
|
| 529 |
+
return[formatok,exact,group('Sandbox'),group('SandboxTemplate'),group('SandboxClaim')and group('SandboxWarmPool')]
|
| 530 |
+
|
| 531 |
+
def check_manifests():
|
| 532 |
+
source=files_text();baseline={name.split('/',1)[1]:json.loads(body)for name,body in source.items()if name.startswith('manifests/')};changed=manifest_cases();valid={key:value for key,value in changed.items()if manifest_valid(value)}
|
| 533 |
+
try:saved=(C/'report.txt').read_text()
|
| 534 |
+
except(OSError,UnicodeError):saved=None
|
| 535 |
+
flags=[stdlib('validate_manifests.py')]+manifest_assess(saved,baseline)+[True]
|
| 536 |
+
for i,files in enumerate([baseline,changed,valid]):
|
| 537 |
+
updates={name:None for name in source if name.startswith('manifests/')};updates.update({'manifests/'+name:json.dumps(value)for name,value in files.items()});r=run('validate_manifests.py',updates,['report.txt'],cwd_index=i)
|
| 538 |
+
flags[0]=tri([flags[0],complete(r)])
|
| 539 |
+
for root in r['roots']or[None]:
|
| 540 |
+
try:body=(root/'report.txt').read_text()if root else None
|
| 541 |
+
except(OSError,UnicodeError):body=None
|
| 542 |
+
bits=manifest_assess(body,files)if r['rc']is not None else[None]*5
|
| 543 |
+
for j in range(5):flags[j+1]=tri([flags[j+1],bits[j]])
|
| 544 |
+
flags[6]=tri([flags[6],None if r['rc']is None else r['rc']==(0 if all(manifest_valid(v)for v in files.values())else 1)])
|
| 545 |
+
return flags
|
| 546 |
+
|
| 547 |
+
BMAD={1:[('brainstorming_report','/bmad-brainstorming','brainstorming-report.md'),('product_brief','/bmad-bmm-create-product-brief','product-brief.md')],2:[('prd','/bmad-bmm-create-prd','prd.md')],3:[('architecture','/bmad-bmm-create-architecture','architecture.md'),('epics','/bmad-bmm-create-epics-and-stories','epics.md')],4:[('sprint_status','/bmad-bmm-sprint-planning','sprint-status.yaml')]}
|
| 548 |
+
|
| 549 |
+
def bmad_state(text):
|
| 550 |
+
out={}
|
| 551 |
+
for line in text.splitlines():
|
| 552 |
+
if ':'in line and not line.lstrip().startswith('#'):
|
| 553 |
+
key,value=line.strip().split(':',1);out[key]=value.strip().strip('"\'')
|
| 554 |
+
return out
|
| 555 |
+
|
| 556 |
+
def bmad_shape(text):
|
| 557 |
+
# No public line layout is prescribed. Field semantics belong to1..4;
|
| 558 |
+
# completion0 observes only a nonempty readable generated text artifact.
|
| 559 |
+
return isinstance(text,str)and bool(text.strip())
|
| 560 |
+
|
| 561 |
+
def bmad_artifact_line(line):
|
| 562 |
+
# Artifact fields are forbidden even when their value says none/null.
|
| 563 |
+
# Ordinary completion prose is allowed; mentioning an existing file in a
|
| 564 |
+
# sentence is not itself a declaration of a newly produced artifact.
|
| 565 |
+
value=re.sub(r'^\s*[-*]\s+','',line).strip()
|
| 566 |
+
label=r'(?:produced\s+)?(?:artifacts?|output(?:[_ -]files?)?|filenames?)'
|
| 567 |
+
if re.match(r'^'+label+r'\s*[:=]',value,re.I):return True
|
| 568 |
+
path=value.strip('`"\'')
|
| 569 |
+
file_pattern=r'(?:[A-Za-z]:[\\/])?[\w./\\[\]-]+\.[A-Za-z][A-Za-z0-9]{0,11}'
|
| 570 |
+
if re.fullmatch(file_pattern,path):return True
|
| 571 |
+
declared=re.fullmatch(label+r'\s+(.+)',value,re.I)
|
| 572 |
+
return bool(declared and re.fullmatch(file_pattern,declared[1].strip('`"\'')))
|
| 573 |
+
|
| 574 |
+
def bmad_assess(text,state_text):
|
| 575 |
+
if not isinstance(text,str):return[False]*4
|
| 576 |
+
state=bmad_state(state_text);phase=int(state['current_phase']);command='PHASE_COMPLETE';artifact=None
|
| 577 |
+
for key,cmd,out in BMAD[phase]:
|
| 578 |
+
if state.get(key)in(None,'null'):command=cmd;artifact=out;break
|
| 579 |
+
if command=='PHASE_COMPLETE'and phase==4:command='/bmad-bmm-create-story';artifact='story-[slug].md'
|
| 580 |
+
commands=re.findall(r'/bmad-[a-z-]+',text);first=bool(re.search(r'(?<![\w-])PHASE_COMPLETE(?![\w-])',text)) and not commands if command=='PHASE_COMPLETE'else bool(commands)and set(commands)=={command}
|
| 581 |
+
second=bool(re.search(r'(?<![\w.-])'+re.escape(artifact)+r'(?![\w./-])',text)) if artifact else not any(bmad_artifact_line(line) for line in text.splitlines())
|
| 582 |
+
statements=[]
|
| 583 |
+
for part in re.split(r'&&|;|\n',text.replace('\\\n',' ')):
|
| 584 |
+
try:tokens=shlex.split(part,comments=True)
|
| 585 |
+
except ValueError:continue
|
| 586 |
+
if tokens:statements.append(tokens)
|
| 587 |
+
def option(tokens,name):
|
| 588 |
+
try:return tokens[tokens.index(name)+1]
|
| 589 |
+
except(ValueError,IndexError):return None
|
| 590 |
+
def tmux(tokens):
|
| 591 |
+
if tokens[0]=='tmux':return tokens
|
| 592 |
+
if tokens[0]!='ssh':return None
|
| 593 |
+
for i,value in enumerate(tokens[1:],1):
|
| 594 |
+
try:inner=shlex.split(value)
|
| 595 |
+
except ValueError:continue
|
| 596 |
+
if inner and inner[0]=='tmux':return inner+tokens[i+1:]
|
| 597 |
+
return None
|
| 598 |
+
if command=='PHASE_COMPLETE':
|
| 599 |
+
clean=not any(tmux(tokens)for tokens in statements);return[first,second,clean,clean]
|
| 600 |
+
pane=state.get('target_pane','0.0');session=state['tmux_session'];target=pane if pane.startswith(session+':')else session+':'+pane
|
| 601 |
+
text_packets=[];timing_text_packets=[];enter_packets=[];sleep_indices=[];routes=[];literal_payloads=[];literal_format=True
|
| 602 |
+
for i,tokens in enumerate(statements):
|
| 603 |
+
if tokens[:1]==['sleep']and len(tokens)==2:
|
| 604 |
+
try:
|
| 605 |
+
if float(tokens[1])==.3:sleep_indices.append(i)
|
| 606 |
+
except ValueError:pass
|
| 607 |
+
values=tmux(tokens)
|
| 608 |
+
if not values or 'send-keys'not in values:continue
|
| 609 |
+
route=(option(values,'-S'),option(values,'-t'));routes.append(route)
|
| 610 |
+
tail=values[values.index('send-keys')+1:];payload=[];j=0;valid=True
|
| 611 |
+
while j<len(tail):
|
| 612 |
+
token=tail[j]
|
| 613 |
+
if token in ('-t','-S'):
|
| 614 |
+
if j+1>=len(tail):valid=False;break
|
| 615 |
+
j+=2;continue
|
| 616 |
+
if token in ('-l','--'):j+=1;continue
|
| 617 |
+
if token.startswith('-'):valid=False;break
|
| 618 |
+
payload.append(token);j+=1
|
| 619 |
+
if '-l'in values:
|
| 620 |
+
# Exact literal identity is a command fact (owner1). A single
|
| 621 |
+
# quoted string with UNREQUESTED text is still a wrong command.
|
| 622 |
+
literal_payloads.append(payload if valid else None)
|
| 623 |
+
if valid and payload:timing_text_packets.append((i,route))
|
| 624 |
+
if valid and len(payload)==1:text_packets.append((i,route))
|
| 625 |
+
else:literal_format=False
|
| 626 |
+
elif valid and payload in (['Enter'],['C-m']):enter_packets.append((i,route))
|
| 627 |
+
else:literal_format=False
|
| 628 |
+
first=first and all(payload==[command]for payload in literal_payloads)
|
| 629 |
+
transport=bool(text_packets)and literal_format and all(route==(state['tmux_socket'],target)for route in routes)
|
| 630 |
+
# Text/Enter sequencing uses their actual shared route. Expected command
|
| 631 |
+
# identity and the configured route are owned independently above.
|
| 632 |
+
timing=any(i<j<k and text_route==enter_route for i,text_route in timing_text_packets for j in sleep_indices for k,enter_route in enter_packets)
|
| 633 |
+
return[first,second,transport,timing]
|
| 634 |
+
|
| 635 |
+
def check_bmad():
|
| 636 |
+
src=files_text();base=src['orchestrator-state.yaml'];flags=[True]+[True]*4+[stdlib('next_step.py'),True]
|
| 637 |
+
try:saved=(C/'next-step.txt').read_text()
|
| 638 |
+
except(OSError,UnicodeError):saved=None
|
| 639 |
+
for j,value in enumerate(bmad_assess(saved,base),1):flags[j]=value
|
| 640 |
+
panels=[base]
|
| 641 |
+
def replace(text,key,value):return re.sub(r'(?m)^(\s*'+re.escape(key)+r':)\s*[^\n]*$',lambda m:m[1]+' '+value,text)
|
| 642 |
+
variants=[(1,{'brainstorming_report':'null','product_brief':'null'}),(1,{'brainstorming_report':'done.md','product_brief':'null'}),(1,{'brainstorming_report':'done.md','product_brief':'done.md'}),(2,{'prd':'null'}),(2,{'prd':'done.md'}),(3,{'architecture':'done.md','epics':'null'}),(3,{'architecture':'done.md','epics':'done.md'}),(4,{'sprint_status':'null'}),(4,{'sprint_status':'done.yaml'})]
|
| 643 |
+
for phase,values in variants:
|
| 644 |
+
text=replace(base,'current_phase',str(phase))
|
| 645 |
+
for key,value in values.items():text=replace(text,key,value)
|
| 646 |
+
text=replace(text,'tmux_socket','/tmp/r9-bmad.sock');text=replace(text,'tmux_session','r9-bmad');text+='\ntarget_pane: 1.2\n';panels.append(text)
|
| 647 |
+
for i,text in enumerate(panels):
|
| 648 |
+
r=run('next_step.py',{'orchestrator-state.yaml':text},['next-step.txt'],cwd_index=i);bits=[];shapes=[]
|
| 649 |
+
for root in r['roots']:
|
| 650 |
+
try:body=(root/'next-step.txt').read_text()
|
| 651 |
+
except(OSError,UnicodeError):body=None
|
| 652 |
+
bits.append(bmad_assess(body,text));shapes.append(bmad_shape(body))
|
| 653 |
+
if not bits:bits=[[None]*4]if r['rc']is None else[[False]*4]
|
| 654 |
+
if i==0:
|
| 655 |
+
flags[0]=tri([complete(r),bool(r['roots'])]+shapes)
|
| 656 |
+
for j in range(4):flags[j+1]=tri([flags[j+1]]+[row[j]for row in bits])
|
| 657 |
+
else:flags[6]=tri([flags[6],complete(r)]+[v for row in bits for v in row])
|
| 658 |
+
return flags
|
| 659 |
+
|
| 660 |
+
def audit_entries(report):
|
| 661 |
+
if not isinstance(report,dict):return{}
|
| 662 |
+
rows=next((report.get(key)for key in('functions','results','audit')if isinstance(report.get(key),list)),None)
|
| 663 |
+
if rows is None:return{key:value for key,value in report.items()if key in('handle_download','handle_export')and isinstance(value,dict)}
|
| 664 |
+
result={}
|
| 665 |
+
for row in rows:
|
| 666 |
+
if not isinstance(row,dict):continue
|
| 667 |
+
name=row.get('name',row.get('function',row.get('function_name')))
|
| 668 |
+
if name in result:return{}
|
| 669 |
+
if name in('handle_download','handle_export'):result[name]=row
|
| 670 |
+
return result
|
| 671 |
+
|
| 672 |
+
def probe_boolean(entry,which):
|
| 673 |
+
if not isinstance(entry,dict):return None
|
| 674 |
+
values=[]
|
| 675 |
+
for key,value in entry.items():
|
| 676 |
+
if which not in key.lower():continue
|
| 677 |
+
if type(value)is bool:values.append(value)
|
| 678 |
+
elif isinstance(value,dict):values.extend(v for k,v in value.items()if'escap'in k.lower()and type(v)is bool)
|
| 679 |
+
return values[0]if len(values)==1 else None
|
| 680 |
+
|
| 681 |
+
def check_traversal():
|
| 682 |
+
source=files_text();app=source['app.py'];tree=ast.parse(app);definitions={node.name:ast.get_source_segment(app,node)for node in tree.body if isinstance(node,ast.FunctionDef)}
|
| 683 |
+
vulnerable=definitions['handle_download'];safe=definitions['handle_export'];panels=[]
|
| 684 |
+
for dl,ex in [(True,False),(False,True),(False,False),(True,True)]:
|
| 685 |
+
def function(name,bad):
|
| 686 |
+
original=vulnerable if bad else safe
|
| 687 |
+
return re.sub(r'^def\s+\w+\(', 'def '+name+'(',original,count=1)
|
| 688 |
+
body='import os\n\n'+function('handle_download',dl)+'\n\n'+function('handle_export',ex)+'\n';panels.append((body,{'handle_download':dl,'handle_export':ex}))
|
| 689 |
+
wrapper='''import json,runpy,sys\nfrom pathlib import Path\nrecords=[]\ndef profile(frame,event,arg):\n if event=='call'and Path(frame.f_code.co_filename).name=='app.py'and frame.f_code.co_name in('handle_download','handle_export'):\n records.append({'function':frame.f_code.co_name,'filename':frame.f_locals.get('filename')})\nsys.setprofile(profile)\ntry:runpy.run_path('audit.py',run_name='__main__')\nfinally:\n sys.setprofile(None)\n Path('r9-instrument.json').write_text(json.dumps(records))\n'''
|
| 690 |
+
flags=[stdlib('audit.py')]+[True]*6
|
| 691 |
+
flags[0]=tri([flags[0],(C/'app.py').is_file()and(C/'app.py').read_bytes()==source['app.py'].encode()])
|
| 692 |
+
for i,(body,want)in enumerate(panels):
|
| 693 |
+
r=run('r9-audit-launch.py',{'app.py':body,'r9-audit-launch.py':wrapper},['report.json','r9-instrument.json'],cwd_index=i)
|
| 694 |
+
flags[0]=tri([flags[0],complete(r)])
|
| 695 |
+
for root in r['roots']or[None]:
|
| 696 |
+
report=load(root/'report.json')if root else False;entries=audit_entries(report)
|
| 697 |
+
classifications=set(entries)==set(want)and all(entries[name].get('classification')==('vulnerable'if bad else'safe')for name,bad in want.items())
|
| 698 |
+
positive=all(probe_boolean(entries.get(name),'positive')is bad for name,bad in want.items())
|
| 699 |
+
negative=all(probe_boolean(entries.get(name),'negative')is False for name in want)
|
| 700 |
+
vulnerable_list=isinstance(report,dict)and isinstance(report.get('vulnerable_functions'),list)and len(report['vulnerable_functions'])==sum(want.values())and set(report['vulnerable_functions'])=={name for name,bad in want.items()if bad}
|
| 701 |
+
cvss=isinstance(report,dict)and report.get('cvss_vector')=='CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N'
|
| 702 |
+
records=load(root/'r9-instrument.json')if root else False
|
| 703 |
+
observed=isinstance(records,list)and all(any(isinstance(row,dict)and row.get('function')==name and row.get('filename')==payload for row in records)for name in want for payload in('sub/../../../../etc/hostname','report.txt'))
|
| 704 |
+
unchanged=root is not None and(root/'app.py').read_text()==body
|
| 705 |
+
bits=[classifications,positive,negative,vulnerable_list,cvss,observed and classifications and positive and negative]
|
| 706 |
+
flags[0]=tri([flags[0],unchanged])
|
| 707 |
+
for j,value in enumerate(bits,1):flags[j]=tri([flags[j],None if r['rc']is None else value])
|
| 708 |
+
return flags
|
| 709 |
+
|
| 710 |
+
CASES={'06eea0d8e610e14830b34ea3':check_kegg,'26c0c4a3d8ec896c85d87184':check_allocator,'29cb2fcdd5ed6fbaf043d06f':check_banner,'2f48f72392367b36096c41b5':check_policy,'316f12f46c0fa2dd1e64e7c6':check_merge,'304f08d634d266386fc2ce28':check_nist,'4a55ba05e4a1f59da2069fbe':check_deployment,'47584a6607d931302da530b7':check_pfas,'4ba53aee5a959415186227b4':check_k3s,'4601158b1f5a0fd53923e02b':check_routes,'36c255f9ff9c064fff901b0d':check_manifests,'02d150d26f11effa96aacc72':check_bmad,'423312940e92e60036449f83':check_traversal}
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
def main(qid):
|
| 714 |
+
try:flags=CASES[qid]()
|
| 715 |
+
except(OSError,KeyError)as exc:
|
| 716 |
+
DIAG.append({'infrastructure_or_contract':type(exc).__name__});flags=[None]*COUNTS[qid]
|
| 717 |
+
except Exception as exc:
|
| 718 |
+
DIAG.append({'grader_error':type(exc).__name__});flags=[None]*COUNTS[qid]
|
| 719 |
+
print(json.dumps({'scoreable':None not in flags,'checks':[{'id':str(i),'passed':v,'reason':'R9 public requirement with independent input variants; see private control/requirement ledger, owner '+str(i)} for i,v in enumerate(flags)],'grading_metadata':{'version':'r9-public-quality-20261023','diagnostics':DIAG}}))
|
| 720 |
+
|
| 721 |
+
COUNTS={'06eea0d8e610e14830b34ea3':6,'26c0c4a3d8ec896c85d87184':9,'29cb2fcdd5ed6fbaf043d06f':7,'2f48f72392367b36096c41b5':8,'316f12f46c0fa2dd1e64e7c6':7,'304f08d634d266386fc2ce28':7,'4a55ba05e4a1f59da2069fbe':10,'47584a6607d931302da530b7':5,'4ba53aee5a959415186227b4':6,'4601158b1f5a0fd53923e02b':7,'36c255f9ff9c064fff901b0d':7,'02d150d26f11effa96aacc72':7,'423312940e92e60036449f83':7}
|
| 722 |
+
|
| 723 |
+
assert set(CASES) == set(COUNTS), "R9 case dispatch must cover every declared task"
|
benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/evaluator/repair_manifest.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"query_id": "02d150d26f11effa96aacc72",
|
| 3 |
+
"sample_index": 11,
|
| 4 |
+
"status": "implemented_pending_isolated_validation",
|
| 5 |
+
"repair_scope": "grader_only",
|
| 6 |
+
"root_cause": "Fresh execution checks only exit code, while a stale correct plan hides wrong phase-3 command generation.",
|
| 7 |
+
"modified_check_ids": [
|
| 8 |
+
"0",
|
| 9 |
+
"1",
|
| 10 |
+
"2",
|
| 11 |
+
"3",
|
| 12 |
+
"4",
|
| 13 |
+
"5",
|
| 14 |
+
"6"
|
| 15 |
+
],
|
| 16 |
+
"canonical_check_ids": [
|
| 17 |
+
"0",
|
| 18 |
+
"1",
|
| 19 |
+
"2",
|
| 20 |
+
"3",
|
| 21 |
+
"4",
|
| 22 |
+
"5",
|
| 23 |
+
"6"
|
| 24 |
+
],
|
| 25 |
+
"preserve_all_original_check_ids": true,
|
| 26 |
+
"rubric": "original equal weights",
|
| 27 |
+
"public_constraints": [
|
| 28 |
+
"Fresh and submitted plan both match current phase, command and artifact.",
|
| 29 |
+
"Shell statements send exact slash text literally, then sleep 0.3, then Enter to the correct socket/session/pane.",
|
| 30 |
+
"Every explicitly stated public phase rule including PHASE_COMPLETE is data driven.",
|
| 31 |
+
"Manual state parsing uses only standard library, without running tmux or any external command."
|
| 32 |
+
],
|
| 33 |
+
"equivalence_policy": "validate required semantic values and ordered outputs; permit insignificant formatting and alternative implementations",
|
| 34 |
+
"source_hashes": {
|
| 35 |
+
"instruction.md": "5ec71bb9ad673f0762a3ded4433ffa658f3f03f1059eff4b6bbe71ef359b2971",
|
| 36 |
+
"task.json": "b103e805517c64e2b452ef082cf209531d47f8299be034d15503f3b9163ec2eb",
|
| 37 |
+
"evaluator/check.py": "4f40d7f2884290b49b8059448d95665f5afb7621d025a091edae766bd27a50c5",
|
| 38 |
+
"inputs/bmad-commands.md": "7c750bf367cb21c84a0c01d2976910c4537731d7d366f87a04f7f94418ff68c9",
|
| 39 |
+
"inputs/orchestrator-state.yaml": "2e385fbb00c1529640d07b185d3701ed21c960ad67ddbd1ebe9075dcea9f1961",
|
| 40 |
+
"reference/workspace/bmad-commands.md": "7c750bf367cb21c84a0c01d2976910c4537731d7d366f87a04f7f94418ff68c9",
|
| 41 |
+
"reference/workspace/instruction.md": "5ec71bb9ad673f0762a3ded4433ffa658f3f03f1059eff4b6bbe71ef359b2971",
|
| 42 |
+
"reference/workspace/next-step.txt": "e32a3ea53731415a1da40f4ef8d23a9242685a22af7f45355d901829665ce080",
|
| 43 |
+
"reference/workspace/next_step.py": "a34a40ffa747078cb442a627eebda62b461929f8498b4e29f64f6474c380982e",
|
| 44 |
+
"reference/workspace/orchestrator-state.yaml": "2e385fbb00c1529640d07b185d3701ed21c960ad67ddbd1ebe9075dcea9f1961"
|
| 45 |
+
},
|
| 46 |
+
"checker_sha256": "db00fd06d28ce401bc04aee48e78dc31d5259fe346c9a278902ecd33f3034b53",
|
| 47 |
+
"local_validation": "own new checker AST parsed and compiled only; no original/candidate/reference code executed",
|
| 48 |
+
"runtime_validation": "pending_isolated_docker",
|
| 49 |
+
"historical_rescore": "pending",
|
| 50 |
+
"solver_or_arm_conditioned": false,
|
| 51 |
+
"notes": [
|
| 52 |
+
"Independent review found skill/references/tmux-setup.md explicitly supports ssh USER@HOST \"tmux ...\". Validator parses wrapper and verifies state vm_user/vm_host, then validates inner tmux socket/pane/literal payload/order without executing SSH or shell. Added equivalent SSH positive and wrong-host negative. No historical arm scores used."
|
| 53 |
+
],
|
| 54 |
+
"revision": "r2_authorized_ssh_wrapper_equivalence"
|
| 55 |
+
}
|
benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/grading/verified_config.json
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema": "audited-verified-grader-v1",
|
| 3 |
+
"query_id": "02d150d26f11effa96aacc72",
|
| 4 |
+
"selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
|
| 5 |
+
"grader_file_sha256": {
|
| 6 |
+
"auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa",
|
| 7 |
+
"check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
|
| 8 |
+
"auto_policy.json": "45629b3bcbba791f80d84093708f835f72710dbc8a0b5936d543d9c1d19e4f93",
|
| 9 |
+
"old_check.py": "02a0ceb4e979129bfd631458b059a3a368fb13154136332b0e0a583252a84480",
|
| 10 |
+
"repair_manifest.json": "09ebaea5655036f1c7767632aa08c9b985eda0a03c3f38f696709dfc72e46bed",
|
| 11 |
+
"dependency_scan.py": "6196b667b8494069b859cc5b1f2f18374cefbde917267666bf36f2d6da145b22",
|
| 12 |
+
"auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0",
|
| 13 |
+
"autograde_task_check.py": "d526d9008ff174ce9777c00b6760a3e1948aa94721343a65f4b1971eee3b7feb",
|
| 14 |
+
"auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932",
|
| 15 |
+
"r9_contract.py": "98220003588dae954f51efcd1a302a2f6bd642dd276a8d0f206fb5dd73aaccdf",
|
| 16 |
+
"auto_contract.json": "cd1a3cf8f6adc127040758d67438be38f63486fb5c9c9d0faad4d4c7328dc67e"
|
| 17 |
+
},
|
| 18 |
+
"runtime_requirements": {
|
| 19 |
+
"approved_per_task_contract": {
|
| 20 |
+
"external_final_answer": {
|
| 21 |
+
"direct_grader_read_required": false,
|
| 22 |
+
"environment": "MYBENCH_ANSWER_FILE=/answer.txt",
|
| 23 |
+
"mount": "/answer.txt:ro",
|
| 24 |
+
"payload": "verbatim actual agent final response UTF-8, never reference answer or candidate-generated proxy",
|
| 25 |
+
"replay_historical_preflight_captures_for_every_task": true,
|
| 26 |
+
"required_before_e2e_grading": false
|
| 27 |
+
},
|
| 28 |
+
"external_trusted_trajectory": {
|
| 29 |
+
"direct_grader_read_required": false,
|
| 30 |
+
"environment_aliases": [],
|
| 31 |
+
"missing_context_behavior": "not directly consumed",
|
| 32 |
+
"mount": "/tool_trajectory.json:ro",
|
| 33 |
+
"original_cwd_source": null,
|
| 34 |
+
"required_before_e2e_grading": false,
|
| 35 |
+
"sha256_environment": null
|
| 36 |
+
},
|
| 37 |
+
"required_private_helpers": [],
|
| 38 |
+
"source": "<local-home>/Documents/Codex/2026-10-11/swift-data-shared-datasets-mybench-portable/work/verified1000_round3_repairs_20261013/grader_runtime_contract.json"
|
| 39 |
+
},
|
| 40 |
+
"candidate_mode": "workspace",
|
| 41 |
+
"candidate_snapshot_copy_to_ephemeral_app": true,
|
| 42 |
+
"container_private_entry": "/grader/check.py",
|
| 43 |
+
"environment": {
|
| 44 |
+
"CANDIDATE_DIR": "/candidate",
|
| 45 |
+
"CANDIDATE_ROOT": "/candidate",
|
| 46 |
+
"MYBENCH_ANSWER": "/answer.txt",
|
| 47 |
+
"MYBENCH_ANSWER_FILE": "/answer.txt",
|
| 48 |
+
"MYBENCH_CANDIDATE": "/candidate",
|
| 49 |
+
"MYBENCH_EPHEMERAL_APP": "1",
|
| 50 |
+
"MYBENCH_EPHEMERAL_WORKSPACE": "1",
|
| 51 |
+
"MYBENCH_RUN_METADATA": "/run_metadata.json",
|
| 52 |
+
"MYBENCH_SOURCE_TASK": "/source",
|
| 53 |
+
"SOURCE_TASK_DIR": "/source"
|
| 54 |
+
},
|
| 55 |
+
"expected_check_ids": [
|
| 56 |
+
"0",
|
| 57 |
+
"1",
|
| 58 |
+
"2",
|
| 59 |
+
"3",
|
| 60 |
+
"4",
|
| 61 |
+
"5",
|
| 62 |
+
"6"
|
| 63 |
+
],
|
| 64 |
+
"external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer",
|
| 65 |
+
"external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored",
|
| 66 |
+
"image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
|
| 67 |
+
"image_included": false,
|
| 68 |
+
"legacy_adapter": false,
|
| 69 |
+
"mounts_readonly": [
|
| 70 |
+
"/candidate",
|
| 71 |
+
"/source",
|
| 72 |
+
"/grader",
|
| 73 |
+
"/answer.txt"
|
| 74 |
+
],
|
| 75 |
+
"network": "none",
|
| 76 |
+
"original_declared_resources": {
|
| 77 |
+
"agent": {
|
| 78 |
+
"cpu_memory_basis": "source_runtime_container_limits",
|
| 79 |
+
"cpus": 2,
|
| 80 |
+
"disk_mib": 10240,
|
| 81 |
+
"memory_mib": 4096,
|
| 82 |
+
"timeout_disk_basis": "advisory_not_measured_or_enforced",
|
| 83 |
+
"timeout_sec": 1200
|
| 84 |
+
},
|
| 85 |
+
"oracle": {
|
| 86 |
+
"basis": "advisory_reference_copy",
|
| 87 |
+
"timeout_sec": 120
|
| 88 |
+
},
|
| 89 |
+
"source_agent": {
|
| 90 |
+
"command_timeout_sec": 60,
|
| 91 |
+
"max_steps": 16
|
| 92 |
+
},
|
| 93 |
+
"verifier": {
|
| 94 |
+
"basis": "original_python_evaluator_enforced_limits",
|
| 95 |
+
"cpus": 1,
|
| 96 |
+
"memory_mib": 1024,
|
| 97 |
+
"pids": 64,
|
| 98 |
+
"timeout_sec": 60,
|
| 99 |
+
"tmpfs_mib": 128
|
| 100 |
+
}
|
| 101 |
+
},
|
| 102 |
+
"private_entry": "evaluator/check.py",
|
| 103 |
+
"private_tree_environment_tokens": [],
|
| 104 |
+
"trusted_trace_environment_aliases": [
|
| 105 |
+
"MYBENCH_TOOL_TRAJECTORY",
|
| 106 |
+
"MYBENCH_TRUSTED_TRACE",
|
| 107 |
+
"TOOL_TRAJECTORY",
|
| 108 |
+
"TOOL_TRAJECTORY_FILE"
|
| 109 |
+
],
|
| 110 |
+
"trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256",
|
| 111 |
+
"working_directory": "/candidate",
|
| 112 |
+
"writable_ephemeral_roots": [
|
| 113 |
+
"/app",
|
| 114 |
+
"/workspace",
|
| 115 |
+
"/tmp"
|
| 116 |
+
],
|
| 117 |
+
"criterion_weights": {
|
| 118 |
+
"0": 1,
|
| 119 |
+
"1": 1,
|
| 120 |
+
"2": 1,
|
| 121 |
+
"3": 1,
|
| 122 |
+
"4": 1,
|
| 123 |
+
"5": 1,
|
| 124 |
+
"6": 1
|
| 125 |
+
},
|
| 126 |
+
"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."
|
| 127 |
+
},
|
| 128 |
+
"engine": "portable_verified_v1"
|
| 129 |
+
}
|
benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/inputs/orchestrator-state.yaml
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
project: taskboard
|
| 2 |
+
vm_host: 10.0.0.42
|
| 3 |
+
vm_user: devops
|
| 4 |
+
project_path: /mnt/nas/project/taskboard
|
| 5 |
+
tmux_socket: /tmp/openclaw-tmux-sockets/openclaw.sock
|
| 6 |
+
tmux_session: bmad-taskboard
|
| 7 |
+
current_phase: 3
|
| 8 |
+
artifacts:
|
| 9 |
+
brainstorming_report: _bmad-output/brainstorming-report.md
|
| 10 |
+
product_brief: _bmad-output/product-brief.md
|
| 11 |
+
prd: _bmad-output/planning-artifacts/prd.md
|
| 12 |
+
ux_spec: null
|
| 13 |
+
architecture: null
|
| 14 |
+
epics: null
|
| 15 |
+
sprint_status: null
|
| 16 |
+
project_context: null
|
benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/instruction.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Write a Python 3 standard-library script `next_step.py` that reads `orchestrator-state.yaml` and prepares the next BMAD action using the frozen bmad-orchestrator Skill. Use the Skill's phase order, workflow commands, produced artifact names, and documented tmux text/Enter timing pattern; this offline adapter does not contact a VM or run tmux.
|
| 2 |
+
|
| 3 |
+
Adapter scope and interface:
|
| 4 |
+
- The state uses simple `key: value` YAML-like lines, with an indented artifacts section. Parse it manually. `current_phase` is 1, 2, 3, or 4; artifact values are `null` or completed paths. Evaluate the current phase only, choosing the first incomplete core artifact in the Skill's documented order. The core artifact fields are brainstorming_report, product_brief, prd, architecture, epics, and sprint_status. Optional research, UX, readiness checks and project-context generation are outside this adapter.
|
| 5 |
+
- In phases before implementation, when all participating work products for the current phase exist, emit `PHASE_COMPLETE` and no artifact or tmux lines. In implementation, use sprint planning while its tracked artifact is missing, and otherwise select the initial create-story action from the Skill's story loop. Keep any placeholder in a documented output filename literally, without inventing a story slug.
|
| 6 |
+
- Write `next-step.txt` containing the exact next slash command, its produced artifact filename, and the tmux command lines that follow the Skill's send pattern. Resolve `-S` from tmux_socket and `-t` from tmux_session plus target_pane; a missing target_pane defaults to `0.0`, and an already session-qualified target must not be prefixed again. Either a local tmux plan or the Skill's SSH-wrapped transport is allowed. Quote shell values when needed.
|
| 7 |
+
Run `python3 next_step.py` from the workspace root, exit 0 on success, and submit both the script and the produced `next-step.txt`.
|
| 8 |
+
|
| 9 |
+
Bounded automatic runtime policy: Only standard-library and submitted local Python modules may be imported during these executions. This policy applies only while the grader executes your submitted Python entry points and the code they actually call; dead code and source strings are not statically judged. Network operations and FFI/native-library loading or calls (ctypes) are forbidden during those executions. External processes are not forbidden unless explicitly prohibited elsewhere in this task. Original expected nonzero exit codes remain legal; each functional check owns its exit convention. Every bounded invocation must finish within its existing finite per-panel timeout; original mode budgets are preserved, including 8-second R9 workflow probes, 40-second added workflow probes, and the existing task-specific budgets stated above. Exceeding that timeout or abnormal candidate execution fails the relevant behavior. Submit regular readable UTF-8 artifacts of the stated format. Missing/corrupt/unreadable candidate artifacts fail their schema checks; trusted fixture setup, runner or observation failures are separate infrastructure errors with no model score.
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
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/02d150d26f11effa96aacc72/skill/SKILL.md
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: bmad-orchestrator
|
| 3 |
+
description: Orchestrate the full BMAD Method workflow across OpenClaw and Claude Code. Use when starting a new project with BMAD methodology, running BMAD phases (brainstorming, PRD, architecture, implementation), or managing Claude Code agents through BMAD workflows. Handles interactive phases (1-3) with the user and delegates implementation (phase 4) to Claude Code via tmux.
|
| 4 |
+
---
|
| 5 |
+
|
| 6 |
+
# BMAD Orchestrator
|
| 7 |
+
|
| 8 |
+
Orchestrate the 4-phase BMAD Method (Breakthrough Method of Agile AI Driven Development) across OpenClaw ↔ Claude Code.
|
| 9 |
+
|
| 10 |
+
## Architecture
|
| 11 |
+
|
| 12 |
+
- **Phases 1-3 (Interactive)**: Run through OpenClaw chat with the user. You facilitate brainstorming, refine the PRD, debate architecture. The user's ideas matter most here.
|
| 13 |
+
- **Party Mode**: At key decision points, suggest running party mode on Claude Code — multiple BMAD agents debate the topic and produce richer output.
|
| 14 |
+
- **Phase 4 (Automated)**: Delegate to Claude Code via tmux on the dev VM. Monitor progress, report back.
|
| 15 |
+
|
| 16 |
+
## Prerequisites
|
| 17 |
+
|
| 18 |
+
- Claude Code installed on dev VM (accessible via SSH)
|
| 19 |
+
- BMAD framework installed in the project (`_bmad/` directory with agents, workflows, commands)
|
| 20 |
+
- tmux available on the dev VM
|
| 21 |
+
|
| 22 |
+
## State Tracking
|
| 23 |
+
|
| 24 |
+
Track workflow state in `_bmad-output/orchestrator-state.yaml`:
|
| 25 |
+
|
| 26 |
+
```yaml
|
| 27 |
+
project: <name>
|
| 28 |
+
vm_host: <ip>
|
| 29 |
+
vm_user: <user>
|
| 30 |
+
project_path: <path>
|
| 31 |
+
tmux_socket: /tmp/openclaw-tmux-sockets/openclaw.sock
|
| 32 |
+
tmux_session: bmad-<project>
|
| 33 |
+
current_phase: 1|2|3|4
|
| 34 |
+
current_workflow: <workflow-name>
|
| 35 |
+
artifacts:
|
| 36 |
+
brainstorming_report: null|path
|
| 37 |
+
product_brief: null|path
|
| 38 |
+
prd: null|path
|
| 39 |
+
ux_spec: null|path
|
| 40 |
+
architecture: null|path
|
| 41 |
+
epics: null|path
|
| 42 |
+
sprint_status: null|path
|
| 43 |
+
project_context: null|path
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
## Phase 1: Analysis (Interactive with User)
|
| 47 |
+
|
| 48 |
+
### 1.1 Brainstorming (`bmad-brainstorming`)
|
| 49 |
+
|
| 50 |
+
Run this conversationally with the user in OpenClaw chat:
|
| 51 |
+
|
| 52 |
+
1. Ask: "What project are we building? Give me the elevator pitch."
|
| 53 |
+
2. Explore the problem space — ask about users, pain points, existing solutions
|
| 54 |
+
3. Challenge assumptions — play devil's advocate
|
| 55 |
+
4. **Suggest Party Mode**: "Want me to run party mode on Claude Code? The BMAD agents (analyst, architect, PM, dev) will debate your idea and surface things we might miss."
|
| 56 |
+
5. If party mode → send `/bmad-brainstorming` to Claude Code, capture output, share highlights
|
| 57 |
+
6. Synthesize into key decisions and themes
|
| 58 |
+
7. Produce: `brainstorming-report.md`
|
| 59 |
+
|
| 60 |
+
### 1.2 Research (`bmad-bmm-research`) — Optional
|
| 61 |
+
|
| 62 |
+
If the project needs market/technical/domain validation:
|
| 63 |
+
|
| 64 |
+
1. Discuss with user what needs validation
|
| 65 |
+
2. Send research workflow to Claude Code for heavy lifting
|
| 66 |
+
3. Review findings together
|
| 67 |
+
|
| 68 |
+
### 1.3 Product Brief (`bmad-bmm-create-product-brief`)
|
| 69 |
+
|
| 70 |
+
1. Start from brainstorming output
|
| 71 |
+
2. Walk through with user: vision, target users, success metrics, scope
|
| 72 |
+
3. **Suggest Party Mode**: "The PM and analyst agents can stress-test this brief. Run it?"
|
| 73 |
+
4. If party mode → send command, capture debate highlights
|
| 74 |
+
5. Iterate until user approves
|
| 75 |
+
6. Produce: `product-brief.md`
|
| 76 |
+
|
| 77 |
+
## Phase 2: Planning (Interactive with User)
|
| 78 |
+
|
| 79 |
+
### 2.1 PRD (`bmad-bmm-create-prd`)
|
| 80 |
+
|
| 81 |
+
1. Load product brief as context
|
| 82 |
+
2. Walk through requirements with user section by section:
|
| 83 |
+
- Functional requirements (FRs)
|
| 84 |
+
- Non-functional requirements (NFRs)
|
| 85 |
+
- User journeys
|
| 86 |
+
- Success metrics
|
| 87 |
+
3. **Suggest Party Mode**: "PM + architect + QA can review these requirements together. Good time to catch gaps."
|
| 88 |
+
4. If party mode → send command, share findings
|
| 89 |
+
5. Iterate until user signs off
|
| 90 |
+
6. Produce: `prd.md`
|
| 91 |
+
|
| 92 |
+
### 2.2 UX Design (`bmad-bmm-create-ux-design`) — If applicable
|
| 93 |
+
|
| 94 |
+
Only for projects with UI. Skip for backend/infrastructure tools.
|
| 95 |
+
|
| 96 |
+
## Phase 3: Solutioning (Interactive with User)
|
| 97 |
+
|
| 98 |
+
### 3.1 Architecture (`bmad-bmm-create-architecture`)
|
| 99 |
+
|
| 100 |
+
1. Load PRD as context
|
| 101 |
+
2. Discuss technical decisions with user:
|
| 102 |
+
- Language/framework choices
|
| 103 |
+
- Deployment model
|
| 104 |
+
- Key patterns and trade-offs
|
| 105 |
+
- ADRs (Architecture Decision Records)
|
| 106 |
+
3. **Suggest Party Mode**: "Architect + dev + QA debating the architecture will surface implementation risks early."
|
| 107 |
+
4. If party mode → send command, share the debate
|
| 108 |
+
5. Iterate with user
|
| 109 |
+
6. Produce: `architecture.md` with ADRs
|
| 110 |
+
|
| 111 |
+
### 3.2 Epics & Stories (`bmad-bmm-create-epics-and-stories`)
|
| 112 |
+
|
| 113 |
+
1. Load architecture + PRD
|
| 114 |
+
2. Present epic breakdown to user for review
|
| 115 |
+
3. Discuss story sizing, priorities, dependencies
|
| 116 |
+
4. Produce: `epics.md` with stories
|
| 117 |
+
|
| 118 |
+
### 3.3 Readiness Check (`bmad-bmm-check-implementation-readiness`)
|
| 119 |
+
|
| 120 |
+
1. Send to Claude Code for automated gate check
|
| 121 |
+
2. Share result: PASS / CONCERNS / FAIL
|
| 122 |
+
3. If CONCERNS/FAIL → discuss with user, fix gaps
|
| 123 |
+
4. Produce: readiness report
|
| 124 |
+
|
| 125 |
+
### 3.4 Project Context (`bmad-bmm-generate-project-context`)
|
| 126 |
+
|
| 127 |
+
1. Send to Claude Code after architecture is finalized
|
| 128 |
+
2. Review output with user
|
| 129 |
+
3. Produce: `project-context.md`
|
| 130 |
+
|
| 131 |
+
## Phase 4: Implementation (Automated via Claude Code)
|
| 132 |
+
|
| 133 |
+
### 4.0 Setup
|
| 134 |
+
|
| 135 |
+
See [references/tmux-setup.md](references/tmux-setup.md) for tmux session initialization.
|
| 136 |
+
|
| 137 |
+
### 4.1 Sprint Planning
|
| 138 |
+
|
| 139 |
+
Send to Claude Code:
|
| 140 |
+
```
|
| 141 |
+
/bmad-bmm-sprint-planning
|
| 142 |
+
```
|
| 143 |
+
Capture and save `sprint-status.yaml`.
|
| 144 |
+
|
| 145 |
+
### 4.2 Story Loop (per epic)
|
| 146 |
+
|
| 147 |
+
For each epic, for each story:
|
| 148 |
+
|
| 149 |
+
1. **Create Story**: Send `/bmad-bmm-create-story` → produces `story-[slug].md`
|
| 150 |
+
2. **Dev Story**: Send `/bmad-bmm-dev-story` → implements code + tests
|
| 151 |
+
3. **Code Review**: Send `/bmad-bmm-code-review` → validates quality
|
| 152 |
+
4. If review fails → send fixes back, re-review
|
| 153 |
+
5. Update sprint status
|
| 154 |
+
6. Commit after each story
|
| 155 |
+
|
| 156 |
+
### 4.3 Epic Completion
|
| 157 |
+
|
| 158 |
+
After all stories in an epic:
|
| 159 |
+
1. Send `/bmad-bmm-retrospective` for lessons learned
|
| 160 |
+
2. Optionally run `/bmad-bmm-automate` for E2E test generation
|
| 161 |
+
3. Commit and update sprint status
|
| 162 |
+
|
| 163 |
+
### 4.4 Monitoring
|
| 164 |
+
|
| 165 |
+
Set up a cron job to monitor Claude Code progress every 15 minutes.
|
| 166 |
+
Report status updates to user via chat.
|
| 167 |
+
|
| 168 |
+
## Party Mode Integration
|
| 169 |
+
|
| 170 |
+
Party mode simulates a multi-agent discussion in Claude Code. Use it at these moments:
|
| 171 |
+
|
| 172 |
+
| When | Why | Command |
|
| 173 |
+
|------|-----|---------|
|
| 174 |
+
| After brainstorming | Surface blind spots | `/bmad-party-mode` with brainstorming context |
|
| 175 |
+
| After product brief | Stress-test the vision | `/bmad-party-mode` with brief |
|
| 176 |
+
| During PRD review | Catch requirement gaps | `/bmad-party-mode` with PRD draft |
|
| 177 |
+
| Architecture decisions | Debate trade-offs | `/bmad-party-mode` with architecture |
|
| 178 |
+
|
| 179 |
+
To trigger party mode on Claude Code:
|
| 180 |
+
```bash
|
| 181 |
+
tmux send-keys -l -- "/bmad-party-mode" && sleep 0.3 && tmux send-keys Enter
|
| 182 |
+
```
|
| 183 |
+
Capture output, extract key insights, present to user.
|
| 184 |
+
|
| 185 |
+
## Claude Code Commands Reference
|
| 186 |
+
|
| 187 |
+
See [references/bmad-commands.md](references/bmad-commands.md) for the full command list.
|
| 188 |
+
|
| 189 |
+
## Quick Flow (Skip Phases 1-3)
|
| 190 |
+
|
| 191 |
+
For small, well-understood work:
|
| 192 |
+
1. `/bmad-bmm-quick-spec` → tech-spec.md
|
| 193 |
+
2. `/bmad-bmm-quick-dev` → implementation
|
| 194 |
+
|
| 195 |
+
Only use when user explicitly says the project is simple and well-understood.
|
| 196 |
+
|
| 197 |
+
## Sending Commands to Claude Code
|
| 198 |
+
|
| 199 |
+
See [references/tmux-setup.md](references/tmux-setup.md) for the tmux interaction patterns.
|
| 200 |
+
|
| 201 |
+
Key rules:
|
| 202 |
+
- Split text and Enter with a delay (Claude Code TUI timing)
|
| 203 |
+
- Use `capture-pane -S -200` to read output
|
| 204 |
+
- Wait for idle prompt before sending next command
|
| 205 |
+
- Use `C-c` to interrupt if stuck
|
benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/skill/_export_skill_meta.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"slug": "bmad-orchestrator",
|
| 3 |
+
"displayName": "BMAD Orchestrator",
|
| 4 |
+
"sourceRef": "public-clawhub",
|
| 5 |
+
"version": "1.0.0",
|
| 6 |
+
"createdAt": 1772120512366,
|
| 7 |
+
"updatedAt": 1779077345065,
|
| 8 |
+
"stats": {
|
| 9 |
+
"comments": 0,
|
| 10 |
+
"downloads": 1160,
|
| 11 |
+
"installsAllTime": 35,
|
| 12 |
+
"installsCurrent": 0,
|
| 13 |
+
"stars": 0,
|
| 14 |
+
"versions": 1
|
| 15 |
+
},
|
| 16 |
+
"owner": {
|
| 17 |
+
"handle": "henrikrexed",
|
| 18 |
+
"displayName": "henrikrexed"
|
| 19 |
+
}
|
| 20 |
+
}
|
benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/skill/references/bmad-commands.md
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# BMAD Claude Code Commands
|
| 2 |
+
|
| 3 |
+
All commands are available as `/bmad-*` slash commands in Claude Code when the `_bmad/` framework is installed.
|
| 4 |
+
|
| 5 |
+
## Phase 1: Analysis
|
| 6 |
+
| Command | Purpose | Produces |
|
| 7 |
+
|---------|---------|----------|
|
| 8 |
+
| `/bmad-brainstorming` | Guided brainstorming session | brainstorming-report.md |
|
| 9 |
+
| `/bmad-bmm-domain-research` | Domain research | Research findings |
|
| 10 |
+
| `/bmad-bmm-market-research` | Market research | Research findings |
|
| 11 |
+
| `/bmad-bmm-technical-research` | Technical research | Research findings |
|
| 12 |
+
| `/bmad-bmm-create-product-brief` | Capture strategic vision | product-brief.md |
|
| 13 |
+
|
| 14 |
+
## Phase 2: Planning
|
| 15 |
+
| Command | Purpose | Produces |
|
| 16 |
+
|---------|---------|----------|
|
| 17 |
+
| `/bmad-bmm-create-prd` | Define requirements (FRs/NFRs) | prd.md |
|
| 18 |
+
| `/bmad-bmm-validate-prd` | Validate PRD quality | Validation report |
|
| 19 |
+
| `/bmad-bmm-edit-prd` | Edit existing PRD | Updated prd.md |
|
| 20 |
+
| `/bmad-bmm-create-ux-design` | Design UX (if applicable) | ux-spec.md |
|
| 21 |
+
|
| 22 |
+
## Phase 3: Solutioning
|
| 23 |
+
| Command | Purpose | Produces |
|
| 24 |
+
|---------|---------|----------|
|
| 25 |
+
| `/bmad-bmm-create-architecture` | Technical architecture + ADRs | architecture.md |
|
| 26 |
+
| `/bmad-bmm-create-epics-and-stories` | Break work into epics/stories | epics.md |
|
| 27 |
+
| `/bmad-bmm-check-implementation-readiness` | Gate check | PASS/CONCERNS/FAIL |
|
| 28 |
+
| `/bmad-bmm-generate-project-context` | Generate project context | project-context.md |
|
| 29 |
+
|
| 30 |
+
## Phase 4: Implementation
|
| 31 |
+
| Command | Purpose | Produces |
|
| 32 |
+
|---------|---------|----------|
|
| 33 |
+
| `/bmad-bmm-sprint-planning` | Initialize sprint tracking | sprint-status.yaml |
|
| 34 |
+
| `/bmad-bmm-create-story` | Prepare next story | story-[slug].md |
|
| 35 |
+
| `/bmad-bmm-dev-story` | Implement a story | Working code + tests |
|
| 36 |
+
| `/bmad-bmm-code-review` | Review implementation | Approved/changes requested |
|
| 37 |
+
| `/bmad-bmm-correct-course` | Handle mid-sprint changes | Updated plan |
|
| 38 |
+
| `/bmad-bmm-automate` | Generate E2E tests (after epic) | Test suite |
|
| 39 |
+
| `/bmad-bmm-retrospective` | Epic retrospective | Lessons learned |
|
| 40 |
+
| `/bmad-bmm-sprint-status` | Check sprint status | Status report |
|
| 41 |
+
|
| 42 |
+
## Multi-Agent
|
| 43 |
+
| Command | Purpose |
|
| 44 |
+
|---------|---------|
|
| 45 |
+
| `/bmad-party-mode` | Multi-agent discussion (all BMAD agents debate a topic) |
|
| 46 |
+
| `/bmad-help` | Interactive help — what to do next |
|
| 47 |
+
|
| 48 |
+
## Quick Flow
|
| 49 |
+
| Command | Purpose | Produces |
|
| 50 |
+
|---------|---------|----------|
|
| 51 |
+
| `/bmad-bmm-quick-spec` | Quick tech spec | tech-spec.md |
|
| 52 |
+
| `/bmad-bmm-quick-dev` | Quick implementation | Working code |
|
| 53 |
+
|
| 54 |
+
## Agent-Specific Commands
|
| 55 |
+
Load a specific agent persona for manual interaction:
|
| 56 |
+
| Command | Agent Role |
|
| 57 |
+
|---------|-----------|
|
| 58 |
+
| `/bmad-agent-bmm-analyst` | Business/market analyst |
|
| 59 |
+
| `/bmad-agent-bmm-architect` | Technical architect |
|
| 60 |
+
| `/bmad-agent-bmm-dev` | Developer |
|
| 61 |
+
| `/bmad-agent-bmm-pm` | Product manager |
|
| 62 |
+
| `/bmad-agent-bmm-qa` | QA engineer |
|
| 63 |
+
| `/bmad-agent-bmm-sm` | Scrum master |
|
| 64 |
+
| `/bmad-agent-bmm-tech-writer` | Technical writer |
|
| 65 |
+
| `/bmad-agent-bmm-ux-designer` | UX designer |
|
benchmarks/skillbench-venus-e/tasks/02d150d26f11effa96aacc72/skill/references/tmux-setup.md
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# tmux Setup & Interaction Patterns
|
| 2 |
+
|
| 3 |
+
## Session Initialization
|
| 4 |
+
|
| 5 |
+
```bash
|
| 6 |
+
VM_HOST="10.0.0.189"
|
| 7 |
+
VM_USER="hrexed"
|
| 8 |
+
SOCKET="/tmp/openclaw-tmux-sockets/openclaw.sock"
|
| 9 |
+
SESSION="bmad-<project-name>"
|
| 10 |
+
PROJECT_PATH="/mnt/nas/project/<project-name>"
|
| 11 |
+
|
| 12 |
+
# Create socket dir and session
|
| 13 |
+
ssh ${VM_USER}@${VM_HOST} "mkdir -p /tmp/openclaw-tmux-sockets && tmux -S ${SOCKET} new -d -s ${SESSION} -n shell -c ${PROJECT_PATH}"
|
| 14 |
+
|
| 15 |
+
# Launch Claude Code
|
| 16 |
+
ssh ${VM_USER}@${VM_HOST} "tmux -S ${SOCKET} send-keys -t ${SESSION}:0.0 'npx @anthropic-ai/claude-code --dangerously-skip-permissions' Enter"
|
| 17 |
+
|
| 18 |
+
# Accept permissions (select option 2)
|
| 19 |
+
sleep 10
|
| 20 |
+
ssh ${VM_USER}@${VM_HOST} "tmux -S ${SOCKET} send-keys -t ${SESSION}:0.0 Down && sleep 0.2 && tmux -S ${SOCKET} send-keys -t ${SESSION}:0.0 Enter"
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
## Sending Commands
|
| 24 |
+
|
| 25 |
+
Always split text and Enter for Claude Code TUI:
|
| 26 |
+
|
| 27 |
+
```bash
|
| 28 |
+
# Send a slash command
|
| 29 |
+
ssh ${VM_USER}@${VM_HOST} "tmux -S ${SOCKET} send-keys -t ${SESSION}:0.0 -l -- '/bmad-bmm-create-prd'" && \
|
| 30 |
+
sleep 0.3 && \
|
| 31 |
+
ssh ${VM_USER}@${VM_HOST} "tmux -S ${SOCKET} send-keys -t ${SESSION}:0.0 Enter"
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
For multi-line prompts, write to a temp file and use `cat`:
|
| 35 |
+
|
| 36 |
+
```bash
|
| 37 |
+
scp /tmp/prompt.txt ${VM_USER}@${VM_HOST}:/tmp/prompt.txt
|
| 38 |
+
ssh ${VM_USER}@${VM_HOST} "tmux -S ${SOCKET} send-keys -t ${SESSION}:0.0 -l -- \"\$(cat /tmp/prompt.txt)\"" && \
|
| 39 |
+
sleep 0.3 && \
|
| 40 |
+
ssh ${VM_USER}@${VM_HOST} "tmux -S ${SOCKET} send-keys -t ${SESSION}:0.0 Enter"
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
## Reading Output
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
# Last 200 lines
|
| 47 |
+
ssh ${VM_USER}@${VM_HOST} "tmux -S ${SOCKET} capture-pane -p -J -t ${SESSION}:0.0 -S -200"
|
| 48 |
+
|
| 49 |
+
# Check if idle (prompt visible)
|
| 50 |
+
ssh ${VM_USER}@${VM_HOST} "tmux -S ${SOCKET} capture-pane -p -J -t ${SESSION}:0.0 -S -5" | grep -q "❯"
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
## Interrupting
|
| 54 |
+
|
| 55 |
+
```bash
|
| 56 |
+
ssh ${VM_USER}@${VM_HOST} "tmux -S ${SOCKET} send-keys -t ${SESSION}:0.0 C-c"
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
## Reading Generated Files
|
| 60 |
+
|
| 61 |
+
```bash
|
| 62 |
+
ssh ${VM_USER}@${VM_HOST} "cat ${PROJECT_PATH}/_bmad-output/planning-artifacts/prd.md"
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
## Monitoring Cron Pattern
|
| 66 |
+
|
| 67 |
+
Set up a cron job every 15 minutes to:
|
| 68 |
+
1. Capture pane output
|
| 69 |
+
2. Check if Claude Code is idle or working
|
| 70 |
+
3. Report status to user
|
| 71 |
+
4. Auto-remove cron when task completes
|