diff --git a/.gitattributes b/.gitattributes index bed0738c7eeb449bca98b5d2f33c89a1ee56349a..ba095b682d95fa0c7f6c86483adbba90a7cd723d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -58,3 +58,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text # Video files - compressed *.mp4 filter=lfs diff=lfs merge=lfs -text *.webm filter=lfs diff=lfs merge=lfs -text +task_141/environment/assets/explorer.glb filter=lfs diff=lfs merge=lfs -text +task_141/solution/assets/explorer.glb filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md index 154df8298fab5ecf322016157858e08cd1bccbe1..f67113536301325e629ab979689c301dab35d7ca 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,87 @@ --- -license: apache-2.0 +pretty_name: UXInteract +license: other +language: + - en --- + +# UXInteract 0.1 + +UXInteract contains 141 tasks for coding agents working on interactive software and practical development workflows. Each task includes an instruction, an initial environment, a reference solution and an executable verifier. + +[Website](https://uxinteract.pages.dev/) · [GitHub](https://github.com/LegoX/UXInteract) · [Hugging Face](https://huggingface.co/datasets/Lego-X/UXInteract) · [Discord](https://discord.gg/sKHZTzVShG) + +## Release identity + +The dataset revision is **ux_bench_0.1-v3.4-review.3**. Task IDs run from `task_001` through `task_141`. The inventory is in [task_map.json](task_map.json). [task_id_map.json](task_id_map.json) preserves the historical ID mapping for tasks 001–139; [Sky Orchard](task_140/) and [Lantern Run](task_141/) were added after the historical snapshot. + +The same release files are distributed at the root of the Hugging Face dataset and under `datasets/ux_bench_0.1` on GitHub. Record the exact repository commit with evaluation results. + +This revision appends Lantern Run to the 140-task snapshot. Model-free checks and remaining verifier limitations are documented in [VALIDATION.md](VALIDATION.md). + +## Task layout + +```text +task_001/ +├── instruction.md +├── task.toml +├── environment/ +├── solution/ +└── tests/ +``` + +`instruction.md` is the agent-visible task specification. The environment supplies the starting files. Reference solutions and verifier assets belong to evaluation and must be withheld from the tested agent until verification. + +## Time budgets + +All 141 tasks declare these base limits in `task.toml`. + +| Stage | Seconds | +| --- | ---: | +| Agent execution | 3600 | +| Verifier | 300 | +| Environment build | 1200 | + +The standard multi-turn runner uses `agent_timeout_multiplier: 1.0`, so each agent round has a 3,600-second limit. Record explicit overrides as part of the evaluation configuration. + +## Download and verify + +Install the Hugging Face CLI and authenticate with an account that has repository access. + +```bash +hf auth login +hf download Lego-X/UXInteract \ + --type dataset \ + --revision main \ + --local-dir ./uxinteract-data +cd ./uxinteract-data +sha256sum -c SHA256SUMS +``` + +Use `shasum -a 256 -c SHA256SUMS` on macOS. For a reproducible download, replace `main` with the release commit SHA. The checksum list covers every distributed file except itself. + +## Run with Harbor + +Use Harbor 0.24.0 and a Docker execution host. Container builds may download task dependencies. + +```bash +uvx --from 'harbor==0.24.0' harbor run \ + -p ./task_001 -a oracle -n 1 -k 1 --jobs-dir ../runs/oracle + +uvx --from 'harbor==0.24.0' harbor run \ + -p ./task_001 -a nop -n 1 -k 1 --jobs-dir ../runs/nop +``` + +Replace the task path with `.` for the full inventory. Configure a supported agent and model provider to evaluate a coding model. The project repository includes the separately configured [multi-turn runner](https://github.com/LegoX/UXInteract/tree/main/scripts). + +## Scoring and results + +Reward 1 denotes complete success under the bundled verifier. Some tasks preserve fractional rewards. Report attempted trials, full successes, partial rewards and execution exceptions together, with the dataset commit, Harbor version, agent, model, concurrency and protocol settings. + +The 2026-11 instruction and verifier revisions require new evaluations before assigning model scores to this release. Historical scores retain their original dataset and evaluator identities. + +## Validation and privacy + +[VALIDATION.md](VALIDATION.md) describes the 139-task static review, previous regressions, and separate Sky Orchard and Lantern Run controls. The checks establish their recorded cases and scope. Visual appearance and open-ended reasoning have documented coverage limits. + +The distribution removes unused personal result paths from 25 admission metadata files. Instructions retain the reviewed technical specifications. Task authorship, source metadata and existing notices are preserved. The project repository explains [provenance and license boundaries](https://github.com/LegoX/UXInteract/blob/main/docs/provenance.md). diff --git a/SHA256SUMS b/SHA256SUMS new file mode 100644 index 0000000000000000000000000000000000000000..3039186eaf029d55c0439e93429be9a492823b17 --- /dev/null +++ b/SHA256SUMS @@ -0,0 +1,3137 @@ +7cfdde38cb83c638cf92858ce8dd84706ac0f641fa4b659f4cb670256a32ce0c README.md +4b9f40b420de3b1129956e1c1fe50d940dc80344d6667c909112e830c99bd05e VALIDATION.md +888017c24377b2da51b5a7014d1922dd4c46ccfab2c606a51c6d18ed1c24531a task_001/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_001/environment/Dockerfile +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_001/environment/code/.gitkeep +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_001/environment/docker-compose.yaml +40779cbb4254a3de84ad28e99e376f8de79f91e8feccd0deb89100bd1a6c18d8 task_001/instruction.md +9b205103fdfd1976115d27beb0b53841fd563f14560c2977cfbca97c6576cae8 task_001/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_001/solution/README.md +9438c286556129e4afe0f1a6cd5904fd439501edddefd82f27f1a1344ec21be5 task_001/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_001/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_001/task.toml +c77169fdfb1362d428f87274ed0a7a16ff4cafc9cef32d41c35a06d50d323986 task_001/task_meta.json +2efd7867d07af967c186f24453403a49328d60471124a151808e592d28fd5520 task_001/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_001/tests/_shared/static_enhancer.sh +e902de0ef89e2cddd1e738d71ab8f881fdf09697105eec7cffe04c3cc587d5dd task_001/tests/enhancement_cases.json +35af8f7e1d582b169fb09945595ac7f3325e052ec6e8a38ecc7898e746a67515 task_001/tests/pixel_changes.js +adfe8bc70a4a17449ebc2066eeaaa8a65438b8b93df10e03299f44429f1ea102 task_001/tests/task_contract.json +e944eeffe3639ac94c6cf03d22eaec88af51b2a37a653aadb9430800bfdf9e18 task_001/tests/test.sh +1e0e0d59283869d614045007d3d5980facef20500bd8246c6051936254ecae32 task_001/tests/validate_aaav_dynamic.js +e0c777377ca0ecc905b9c033a15c4f3324fc3fd29eabc76bff80e2480419bce1 task_001/tests/validate_browser_smoke.js +a4b631d6bb4a724775894fe3ae4a841d3cd1a1ef9dbfdaa8438a9a61a5b687f8 task_001/tests/validate_enhanced_cases.js +a797c17f9ee5efbc7ef42fcaefe14afd1f7e9d32c34083e3e76749d970a2605b task_001/tests/validate_lines.js +c03ec90084b1d1c29fac580a98081ac1b24b409e43af031e14db41c9df9fb2ba task_001/tests/validate_semantics.js +1b96da5423a74094d884edabb6792e9a04cd7ca124fc2277421e9a37c70cdfd1 task_002/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_002/environment/Dockerfile +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_002/environment/code/.gitkeep +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_002/environment/docker-compose.yaml +27af861d2160046d3b88adda8506cc46b5917b4f48a07ddb75b062ee3b37a55b task_002/instruction.md +f231b1f1d0e6aad99d336a2428619024d0376c817f2d99286511e8d87889053d task_002/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_002/solution/README.md +e4bb37aaece42f5897bffeed8f90df99be649a03d0e71e3e4bdb250a7d9caa7b task_002/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_002/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_002/task.toml +c9b6def092aa6688d8988a49332a2c400772b87fed3c943325b9f688f12f9920 task_002/task_meta.json +33e1e0506f7b9bee596b524c76a48a63a85805d583723c5663521fd0de025126 task_002/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_002/tests/_shared/static_enhancer.sh +ab5ec79c73957ddb8db2d896df86ade5b5751c2698bbc8abf6137ce58842c102 task_002/tests/enhancement_cases.json +35af8f7e1d582b169fb09945595ac7f3325e052ec6e8a38ecc7898e746a67515 task_002/tests/pixel_changes.js +ce6cae00cc4afd2fac1f6dbb1571d1bccd1655a10e7b07ccf8e9d90bb32a02e2 task_002/tests/task_contract.json +611862cc887b0b0592ba26e896bc47ebd5e1b9f011fa783cf5d4a28441279997 task_002/tests/test.sh +e6ece534bc685d468b8891b5c37d43fd39e67db09558c078d3bf4d55c3ff0daf task_002/tests/validate_aaav_dynamic.js +e0c777377ca0ecc905b9c033a15c4f3324fc3fd29eabc76bff80e2480419bce1 task_002/tests/validate_browser_smoke.js +6efe70e02a5da84f5dae6271c9f09b3221a3588c13326bfb3560b63812252779 task_002/tests/validate_enhanced_cases.js +c03ec90084b1d1c29fac580a98081ac1b24b409e43af031e14db41c9df9fb2ba task_002/tests/validate_semantics.js +b40fadcefb5b4dd2a672eb4994f463858c6e4d25d827652e0fba3fdf81338eb9 task_003/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_003/environment/Dockerfile +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_003/environment/code/.gitkeep +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_003/environment/docker-compose.yaml +83f214d18cf58b3f39914749cdc63169713ffcc8c054c8c1acf537b55af934cc task_003/instruction.md +f231b1f1d0e6aad99d336a2428619024d0376c817f2d99286511e8d87889053d task_003/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_003/solution/README.md +ecb54ee53cf865fe6f2489ec34a5602634a796990a7384edead09f05ac92e6ae task_003/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_003/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_003/task.toml +af6fc0bf49bf8f73b1298ad2406feb823af5af8f929119f05559b9e18c797ebd task_003/task_meta.json +eab27293be4927747c1a74961c97d5578db6f4a736910be1f56ad9b2f040e4cb task_003/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_003/tests/_shared/static_enhancer.sh +d74bd709478faea473d58675d5af2245ea438d82dcb0520fdd1cb5a0ec783b88 task_003/tests/enhancement_cases.json +afa079d2e66becdeb6593a245b75d63796d7abf36d130cb29ac2e2511a2cfe24 task_003/tests/task_contract.json +611862cc887b0b0592ba26e896bc47ebd5e1b9f011fa783cf5d4a28441279997 task_003/tests/test.sh +4bdfb4e8a5c669a6335c6666ae71fdb22c7b519f9a36f4e67d18351673970e33 task_003/tests/validate_aaav_dynamic.js +e0c777377ca0ecc905b9c033a15c4f3324fc3fd29eabc76bff80e2480419bce1 task_003/tests/validate_browser_smoke.js +ef00d8f1e30cd738609d963c00202e3a2eea11fa0a2bba16cdb384897ce1acc3 task_003/tests/validate_enhanced_cases.js +c03ec90084b1d1c29fac580a98081ac1b24b409e43af031e14db41c9df9fb2ba task_003/tests/validate_semantics.js +288409197e4c9851e2c7815af74fa827ce163cf63675ed7f32e96bf3a16edda8 task_004/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_004/environment/Dockerfile +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_004/environment/code/.gitkeep +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_004/environment/docker-compose.yaml +13822b23f2d7a4f0f57beeb591d54be6e9fd13e9522551bdf9a3a141312ea7ad task_004/instruction.md +f231b1f1d0e6aad99d336a2428619024d0376c817f2d99286511e8d87889053d task_004/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_004/solution/README.md +8a13effb811efcc7bddeb868680b74897bff32212b3c2a2ed3608844b6593e72 task_004/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_004/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_004/task.toml +e89e202c8663c4258c9ad3e5c73fd82c7be4deb08206fccfafcce1c7098a5e32 task_004/task_meta.json +c0a980572586e8f2d0ccc77422130c9826b2df6503178cc4b8c77e5b0fe05b04 task_004/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_004/tests/_shared/static_enhancer.sh +1d0fb6ee6804fae54c1273b9d42b95649d75d44f9419170825e419edb7d4b4bb task_004/tests/enhancement_cases.json +4b426cdf7c3688f45a4e2fc492b23684ff43a3c752944efdf41e0ee6487064d2 task_004/tests/task_contract.json +392cc7ca013bbff3f55da7951e277496af86a6649c99fc83d633d7ddece70fe6 task_004/tests/test.sh +a59883f949aa8442dc946e5e5f9e69943ffa6ca7da19e11e6fe1b9e635b38ff4 task_004/tests/validate_aaav_dynamic.js +e0c777377ca0ecc905b9c033a15c4f3324fc3fd29eabc76bff80e2480419bce1 task_004/tests/validate_browser_smoke.js +3fe35d7bfe40bc1896d5e1f70416aceb7d5652b31ab813f08d323d7bdee84b18 task_004/tests/validate_enhanced_cases.js +958d1145bb5c9172418a7d47028076d0df21fe8a44b4fd37af2e4e6c62c00db6 task_004/tests/validate_finish.js +c03ec90084b1d1c29fac580a98081ac1b24b409e43af031e14db41c9df9fb2ba task_004/tests/validate_semantics.js +0ad8ab0dfe0f495efab917686ed7886d0a1012337b081d947d9dec94dfef4ee5 task_005/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_005/environment/Dockerfile +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_005/environment/code/.gitkeep +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_005/environment/docker-compose.yaml +08ea68f7c71bf938f48ea61314458c02188d9819a122bc0c4c80e4690afb3aa4 task_005/instruction.md +9b205103fdfd1976115d27beb0b53841fd563f14560c2977cfbca97c6576cae8 task_005/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_005/solution/README.md +639f2615403f62d1167cc4dfe19cca0a5ca88fc82580dbf5d928b1430e29330c task_005/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_005/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_005/task.toml +cf4b3ac1920f699e64480ce402f47f0b9800ac836a8afc5d11a98bfee1876b2b task_005/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_005/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_005/tests/_shared/static_enhancer.sh +162d0867b0e0b6b4f5e4cd8e105cf061c57f0351b6b8d0f3820e28e9155db277 task_005/tests/enhancement_cases.json +611862cc887b0b0592ba26e896bc47ebd5e1b9f011fa783cf5d4a28441279997 task_005/tests/test.sh +e7277cd2059d782ecf0c464913c3b86ea2989fdb058fcdcc256f78cdd6088fac task_005/tests/validate_aaav_dynamic.js +e0c777377ca0ecc905b9c033a15c4f3324fc3fd29eabc76bff80e2480419bce1 task_005/tests/validate_browser_smoke.js +42eef5f7ceb8ee758b5b648e2b9a3adc38291f9d08a3ac52246c0d797e85ed53 task_005/tests/validate_enhanced_cases.js +c03ec90084b1d1c29fac580a98081ac1b24b409e43af031e14db41c9df9fb2ba task_005/tests/validate_semantics.js +f015f0021d6bd05f760df967c37c2bbaddf0ff151975f4558b20b2b31970be07 task_006/acceptance_checklist.json +eb8fe0e183c8472ca1eb8b817c2fe85956d6a27300aee4845a8cb19aa72313d4 task_006/environment/Dockerfile +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_006/environment/code/.gitkeep +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_006/environment/docker-compose.yaml +4dee0047ff08ef04b0f21234fa55379e6df7c6c9b943a9ad909f7c588dd7bbc0 task_006/instruction.md +f231b1f1d0e6aad99d336a2428619024d0376c817f2d99286511e8d87889053d task_006/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_006/solution/README.md +87e0d95bd1f7dd01d2f8921b98e0969284ddb9e6ba17ef4bf5c8127382f1b8ce task_006/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_006/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_006/task.toml +43729d24a83762fd728fbe570b06499a58fda46c51c02384a2e9b33f648038a6 task_006/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_006/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_006/tests/_shared/static_enhancer.sh +769f1edb3f049e0b5f95e0509481cdab2918dec26308d7c581a6d0983f7357e0 task_006/tests/enhancement_cases.json +036cdc75ccaabf4afe610fff6681a9b07cef959f9085ac7e2cd2eb03cbbcfbe2 task_006/tests/summary_values.js +611862cc887b0b0592ba26e896bc47ebd5e1b9f011fa783cf5d4a28441279997 task_006/tests/test.sh +25ea5f40a599a9f4a5029b43036d770d4b3ea5a856e1ec9a04ad839cfae2128e task_006/tests/validate_aaav_dynamic.js +e0c777377ca0ecc905b9c033a15c4f3324fc3fd29eabc76bff80e2480419bce1 task_006/tests/validate_browser_smoke.js +abe15ac2aa7af987818ae13b077824d6926ecd947ae27898e01ced5891600e30 task_006/tests/validate_enhanced_cases.js +c03ec90084b1d1c29fac580a98081ac1b24b409e43af031e14db41c9df9fb2ba task_006/tests/validate_semantics.js +e063be80e4a368c76dba531e6e87b40642cee02ef992a999ac82d9d51ca59cbf task_007/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_007/environment/Dockerfile +f92336650e5776b6127eec9dc928982c98bf658cf4dcb0cf7c595a8caa36a4b6 task_007/environment/code/index.html +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_007/environment/docker-compose.yaml +69d12ad100c81ae099f8ab22b949bf9c3a695a317252feaadfa7a3773573f215 task_007/instruction.md +958c767b6317f8e5d26a35616825081f8eeb13a751ae276817bb7f92b652beac task_007/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_007/solution/README.md +3325d71d2105977f5f409c0d8e997cb0e729e1b1ac2bb2a70c55225e0ea83c0c task_007/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_007/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_007/task.toml +571f5bce27b74f30ccacee35a6c6c548f1ebba1c7350386b05c71d9a6760ce7b task_007/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_007/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_007/tests/_shared/static_enhancer.sh +02a792237b33f70378356cc45948d2a3f4b2d81922d2ed96398106da581feaeb task_007/tests/edit_question.js +8da4d4540af93b5c086b6a1a7db0e248ec7303f91117515d7b2e1cc05bd728c4 task_007/tests/enhancement_cases.json +abc75cba72d320a2a5843065849b26c3aa5918e865ceca889e299ce549c21c61 task_007/tests/test.sh +6fdc2a27d08d248c4dd32db9b2139641802c080ff4af0a95c8cf36d07da2092b task_007/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_007/tests/validate_browser_smoke.js +6c0b4df2cad49abf50b1133ec1cff379cb58f34d7de0b9e40d789388fe301beb task_007/tests/validate_enhanced_cases.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_007/tests/validate_semantics.js +0a154236978b820021c76951998d237d27deaff85be5e77e3da6512c712af1d7 task_007/tests/validate_ui_behavior.js +bb40b67079f765459f374da925ecdf45f2f3421a2abb04f40e44fd787fa20c7a task_008/acceptance_checklist.json +6ea999c970aba5a796d4bce2f8222f49fcea0b8535f78dbba59002cd40ddcb40 task_008/environment/Dockerfile +404ab277b385b7d78b9d36303ab1222796cba38c4396badd3b1ac95799f4c93a task_008/environment/code/convert.js +0501caae551ab39f07667815209bd26d879dc2d83c079a98c3a9f6d0700f77bd task_008/environment/code/out/math.pdf +22ea8447dcc25e6e160b9b36954e72cbac3e8138d1aa9212c4760d023ff1343c task_008/environment/code/samples/math.md +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_008/environment/docker-compose.yaml +b807be92d5482336a6e35fdc5603abbe3df84926ade24bb6f5542ce7eecb9311 task_008/instruction.md +958c767b6317f8e5d26a35616825081f8eeb13a751ae276817bb7f92b652beac task_008/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_008/solution/README.md +20a23f9db23df90d1cababcdf6b1f074d07bb3a002b74f45a8d368597ca2a5ad task_008/solution/code/convert.js +098e52ee022117745c7672c4103e76ce5ba5fbb7d915556cb23662c62e94027a task_008/solution/code/index.html +527435549e29c77eacf04af90863b3cb3ee3b7d0bed435f490b0720eaf0371d1 task_008/solution/code/out/math.pdf +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_008/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_008/task.toml +addb0c75ef46a88f5fc82bd586c044560f9f57b59e0c229ea041aa4a09fd42c2 task_008/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_008/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_008/tests/_shared/static_enhancer.sh +e26de96c1c04cd7b28b244dd00c369848f48083706622815c414fc95407f3319 task_008/tests/enhancement_cases.json +0d6f054b7087a7eccb3d17c52f30f485bd6ac8e7a657e4cac84a87c48d2a426b task_008/tests/test.sh +3fbfd591d61abcf42e4abb521ea8a08ffb7048ff70da1e2476de15b8634016fb task_008/tests/validate_aaav_dynamic.js +1e8aef3abd1ef3149f88487f669df05e6b01e97164573b0c8cc1e6e16051fc05 task_008/tests/validate_browser_smoke.js +a79bfabff112a46703f77a326ed92408f6c3a221373fa8cc291d7d2a4628dbb8 task_008/tests/validate_enhanced_cases.js +b125ad98fd634d8eb5249e03ba13a88c050a62eb8f15ada0d40a03a3db790a9b task_008/tests/validate_readability.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_008/tests/validate_semantics.js +6d6e6cf77ea2957bd20bd7b33426bbb664eb18f110461aac8c98b09b5161b2bf task_008/tests/validate_ui_behavior.js +dc772fda2f50a6b71dea80c8275c7d276d1ae3e644be8129d623485f257f2ecc task_009/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_009/environment/Dockerfile +4f3ce195f53a4d9fecf6c3d1b8f759c90102a5604efae87d930d3264133aa0e7 task_009/environment/code/index.html +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_009/environment/docker-compose.yaml +07d2c0ffb09f757075c1781ab11fcd8dbcc62282f66902ba425a039d52c0d99d task_009/instruction.md +958c767b6317f8e5d26a35616825081f8eeb13a751ae276817bb7f92b652beac task_009/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_009/solution/README.md +96de4c000d9fb1114f28b0cdb05372047e37021408d8ca27f51ebaff50264dce task_009/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_009/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_009/task.toml +05e5a1764d07181c3dcc88b655d70dc688d821572c525d1ef229351f157c3db3 task_009/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_009/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_009/tests/_shared/static_enhancer.sh +a90912f13058f7754d4d265bbbf13d763a1d2a4aec020b0e9c28471f4de77e9b task_009/tests/enhancement_cases.json +abc75cba72d320a2a5843065849b26c3aa5918e865ceca889e299ce549c21c61 task_009/tests/test.sh +c4e04fef183c2962ae1ad8a285f756778022683a45bce0207402c9a125185f5c task_009/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_009/tests/validate_browser_smoke.js +f60d7f8a38e9d289f42e4dabc510d614260c34ce27f4e997e508ca221930a81d task_009/tests/validate_enhanced_cases.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_009/tests/validate_semantics.js +8c3948cf8816fb62908f9cb357254a6a3e9777b6fb567d4b05063b6bd6f21614 task_009/tests/validate_ui_behavior.js +e2fe5ef0a9abb2967f2fa24d9f733300efbc955f3b4ecfa4221ddddbfe59ef77 task_010/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_010/environment/Dockerfile +2784e4f4db84336c00e9c7e91ed0685d85353290a1d480c294f44d70ba5f48a7 task_010/environment/code/.env.example +85de6f27c436f2d7972a05f1347d810447cdd1471563e4ea3aa7fbc08b3bff67 task_010/environment/code/config.js +06bdbfc4060e1747cfc43ac0de89521a2f73acd62d7f1852a6de9e53eacda77a task_010/environment/code/index.html +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_010/environment/docker-compose.yaml +c2badbd5c3e879863922167f8899cc871cad0037ce97a9dcb53f554ca407ffa0 task_010/instruction.md +e4f07555335440da0277bfa17a487d4c73aa7bdb64ea449954fa42870d1f9c20 task_010/provenance/restoration_notes.md +e72d1761834423d1880cbd8b426117c21ef4bcd0fe9699b566d3d4b81acd9f50 task_010/provenance/user_turns.json +958c767b6317f8e5d26a35616825081f8eeb13a751ae276817bb7f92b652beac task_010/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_010/solution/README.md +2784e4f4db84336c00e9c7e91ed0685d85353290a1d480c294f44d70ba5f48a7 task_010/solution/code/.env.example +a6c2f7d50fe56c87b0319f42b2967ce46dfb5b78118ccdd8f5a2f093a3f283f2 task_010/solution/code/config.js +741e9cf26040e5c5cea3c4036e024fff091c157463e50008860d48716e21d791 task_010/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_010/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_010/task.toml +11984a36df68a21e2fc5f76dfca4e9121570a8d0fffd6506088835cc312b05e2 task_010/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_010/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_010/tests/_shared/static_enhancer.sh +c822fbacb1f9b2ad8e654eefce6f9322633d420a3e543c2ee14465d72e332b2b task_010/tests/enhancement_cases.json +abc75cba72d320a2a5843065849b26c3aa5918e865ceca889e299ce549c21c61 task_010/tests/test.sh +6c85f4ea3a60d9f3a582d3664dece49c3b269ce4f88929ce04603ec90a9d1c0b task_010/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_010/tests/validate_browser_smoke.js +9025c5f7a30a868a4b983a2fa75c6b0b00ff790129d23952e0780ad67161c118 task_010/tests/validate_enhanced_cases.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_010/tests/validate_semantics.js +fcbc43d8aee5693690207e0757c5f47b606ee9249d8a284dffe7a566bbcddfd4 task_010/tests/validate_ui_behavior.js +47c43106c47781b434e3b232ce4cd8d13bf617c72583982429e3c170c8bf895d task_011/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_011/environment/Dockerfile +2784e4f4db84336c00e9c7e91ed0685d85353290a1d480c294f44d70ba5f48a7 task_011/environment/code/.env.example +85de6f27c436f2d7972a05f1347d810447cdd1471563e4ea3aa7fbc08b3bff67 task_011/environment/code/config.js +06bdbfc4060e1747cfc43ac0de89521a2f73acd62d7f1852a6de9e53eacda77a task_011/environment/code/index.html +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_011/environment/docker-compose.yaml +1b5adeb3ff00cf57dcc7ab2f422086cc6b3659a1f4df4c9db7d8d5bd7b6318a2 task_011/instruction.md +aabd95e35b9955efb85114923b0b8dc0b5f9159950baed051794b56eebdfcaaf task_011/quality_notes.md +705a235279051a6b5468dacc7056f83f2c6200b75445ffa39aee4b001d63d3df task_011/solution/README.md +2784e4f4db84336c00e9c7e91ed0685d85353290a1d480c294f44d70ba5f48a7 task_011/solution/code/.env.example +8c65d4e10ecf6aae6c97116cde49afe8c340b26fef624a646f5678e387ffe381 task_011/solution/code/app.js +fae9d080660dde0a2b2e2d3b9fd4ba852a94de636dc2f23389ec3bbf1cb71d56 task_011/solution/code/config.js +9003f819c64ec239e472eb7bd357d6b60b697cd3b3fc7ff282c5f6b4e5d0745e task_011/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_011/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_011/task.toml +ef2141f1af1dbac7805985330a38f187e07f854be949c2e2b23d1ae4b15e4175 task_011/task_meta.json +0b28cf4a0777e0f3c2d4ca937b01441bbb44bddb51f951ff2d747916a8c863b7 task_011/tests/enhancement_cases.json +44efb1954e910fa85371cbdd2c082ae8dbfd315acfeb0f3ecfe7de46e48a6d29 task_011/tests/test.sh +9347403edbd7356c3d208eeb960aa9cd09c3e48fb214255f4d7c12d62f98aaac task_011/tests/validate_request_audit.js +e2afe9893e894541931bcee2163b39d8db5c96c16d40af3ca5f0565f33f037d0 task_012/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_012/environment/Dockerfile +dc8415d085dc55f86e4b52baa697808bb568e27b91e3eb5652d5fad2a7bfa82f task_012/environment/code/config.js +224ab5c281ebdbf5feec0a364c70a623322b75fdb73b25eca1a2cad0f73b2a9c task_012/environment/code/index.html +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_012/environment/docker-compose.yaml +061b9e98d1abf9e9b16bfe0a652e73e080e5381ec61fd3e7a89d428361a82705 task_012/instruction.md +5b74875d52028431aa963342712ed9e45acdaa8a1528fd208bda0bb27774dc60 task_012/provenance/restoration_notes.md +36044c26d1af83f30e5cca8721392b534bc6ff3dbb21010343e0894c4cf87a62 task_012/provenance/user_turns.json +958c767b6317f8e5d26a35616825081f8eeb13a751ae276817bb7f92b652beac task_012/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_012/solution/README.md +9fbf794f5729c953516b48dbd01d61c2ddc8b96c29b23ee5543a2de0a8cd38f1 task_012/solution/code/config.js +82ca4c7200b4db19bcf8a9bffcca3b3031ec79df4d37b80098a2c3d4f4c90073 task_012/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_012/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_012/task.toml +11362b38e1c50cc73e58e0445b24522407093338ff3094a7aa1201f30255ec8d task_012/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_012/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_012/tests/_shared/static_enhancer.sh +e7e84ccab53e188c85ad56900229b3b02ee9e5d8338b777912c022ba510fa59e task_012/tests/enhancement_cases.json +abc75cba72d320a2a5843065849b26c3aa5918e865ceca889e299ce549c21c61 task_012/tests/test.sh +5714a43e5059e39d41889d928cb93185d62b55e35f8674c62b0d50d732205219 task_012/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_012/tests/validate_browser_smoke.js +30fb6a5907b27153652e35411e22e2d8c6b5f48c3bf7402580d237af58392c16 task_012/tests/validate_enhanced_cases.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_012/tests/validate_semantics.js +d28304654def888dc94194b97da807a278795afa08dd7567814c79415e20dd31 task_012/tests/validate_ui_behavior.js +e10a2f64ebe15928ce7ff0e12e0aeb61121eedb7426a5d118120b785fa30dcef task_013/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_013/environment/Dockerfile +f68334707a210451995141ba2da59e89c8807e310a1fd327ea4384343b202385 task_013/environment/code/index.html +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_013/environment/docker-compose.yaml +b1f593e8c90a4b78a29ad2749744d4093cbfd87515870278c35321b2b3dd0dd2 task_013/instruction.md +4a2c6bbc863fb9b25124fd51d3bfd7490dfd1b59d47685643e2661d82530a36e task_013/provenance/restoration_notes.md +33c9958fe508d81199018728986db8b8240787693cae7305fbcbf2fdf09b2054 task_013/provenance/user_turns.json +958c767b6317f8e5d26a35616825081f8eeb13a751ae276817bb7f92b652beac task_013/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_013/solution/README.md +2368bbe60fda27a5ae19b08b8eceb867502623d9a7b2c0322c44d0ae466723c0 task_013/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_013/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_013/task.toml +7740ff6581d8c4e387fca2b2861f44f9ae53a3932f3ce554097a514dc00726dd task_013/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_013/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_013/tests/_shared/static_enhancer.sh +29f4ebb1f477df68cd70d382fd60764ac27f706e3b14b7b159d4c654bdab621b task_013/tests/enhancement_cases.json +9cfb51b23eeb6b9317aedcac3943893c1130f02e44cc026f0c89cc52ba51c90f task_013/tests/review_hard.js +abc75cba72d320a2a5843065849b26c3aa5918e865ceca889e299ce549c21c61 task_013/tests/review_legacy.sh +64b448947d3d1344a60ebde1dd50ac03b9cf3d9a06417b03a185b7cca2cc3d92 task_013/tests/test.sh +1920011ca825b9dba5979776b0d98675b325dd4d8b978db0bad4fdc0a7975d91 task_013/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_013/tests/validate_browser_smoke.js +aa3eac73f8ed6a37c387ca050b3209e24d0177662b571b3af23ae76822aea46e task_013/tests/validate_enhanced_cases.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_013/tests/validate_semantics.js +f2bcd5d724691eea579125c107aa02ec70247e9751539ab028fd1a1edba52209 task_013/tests/validate_ui_behavior.js +829547b35cb7487a0534b96f92f4f435cb7544b2cc5e00f0471d90769d919933 task_014/acceptance_checklist.json +3a724daf9e7145883ebdffb818a6dcca6d8f68dd10bd65d0301b9c1d7250b1ba task_014/environment/Dockerfile +eb0a81a7c84c73fc8ae4d6f9e32a3a1aa2ff65d471ad30204f6131220f289690 task_014/environment/code/go.mod +5143537ab2cae11576734b64814fb15eef7c03f54ba7905d916ebe6d27b85e86 task_014/environment/code/lru.go +f2fbc0236833ee32a6f9f3065c0f6e695acb2a2e144abd6c8ea65b7c15d6c5af task_014/environment/code/lru_ttl_test.go +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_014/environment/docker-compose.yaml +8579cfa6beec093b13193640a2ed63f26a63ac6c42002c4cd3adba1ae9bc6171 task_014/instruction.md +dff370ae62235c3b61ba5ec44cc409a8b0c607cbdb009a775283f8580f23ede1 task_014/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_014/solution/README.md +eb0a81a7c84c73fc8ae4d6f9e32a3a1aa2ff65d471ad30204f6131220f289690 task_014/solution/code/go.mod +8c102a86038f3bc4fa2352abb3d96116a61eeff3ecc47ef5072858ec56a4a50c task_014/solution/code/lru.go +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_014/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_014/task.toml +e67878e1bfc55da440d8199fbd2892097398325a1fbcf171a5a764b1f82a122d task_014/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_014/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_014/tests/_shared/static_enhancer.sh +c6e674b0e9d62dfd1e8f2d6245e4722d9d6de0ec899d9c4ca7d26b3f88ce3ecf task_014/tests/enhancement_cases.json +310300e57c1554f9bcb00051aca21a2dbe56245383568a0bc3d8240b604955fb task_014/tests/test.sh +f4bdcff3a596c122c7c4433cb2f1ac55cadf514c7cd1762b37ad82afaeb4088d task_014/tests/validate_enhanced_cases.sh +2378dd58bd4c3e5fa977c4b22be6397f5df82fb505ec08f8c5e698c522c8f999 task_014/tests/validate_enhanced_ttl_test.go +3e55f47f977bd2212ff13af17fbe7f3052c8c25c3cebd555c6bc976639183406 task_015/acceptance_checklist.json +cac869acb68f6cb27bf9f6e6f1985c0076c35a37ba6ba42db4ae595b32042e29 task_015/environment/Dockerfile +89d36504a14e357f1806813123c62a42047febb018f12b4fd65d44f37ca7737a task_015/environment/code/README.md +238e02b7ec50d45b1c26051990b1a5a4a94e5dbfc7cadbd53fe211da7d864fda task_015/environment/code/example/example.py +c9ec7361297267d0c7cc4532e7f6ca048333712d91f9cd624815129a2410fa8b task_015/environment/code/original_go/cron.go +e1f763625cdc5f18e456823e76495427f932e0fc1dab7ed688206f98a3f1a4b0 task_015/environment/code/pycron/__init__.py +347db83094693c964edfa0fc5126f3e2475dd99c6586d8de9808e0accc5c4aa3 task_015/environment/code/pycron/cron.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_015/environment/docker-compose.yaml +3359c5235afdc0d34577ab939723b2e0dbc5ce518501c636283475f47ce6a996 task_015/instruction.md +6e528b1fba0c2c012796df820b6c95e8d448e0b163e235195528f8d52b6f3f85 task_015/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_015/solution/README.md +3f6d3c33d861572839d5b7bd1fa446123fdc9b2c93fd60031cedc2c1f1307316 task_015/solution/code/README.md +21c1673d15f0a42899dc7253a8905ad9b8fb0d03ff93fec8f271c0219bf2487a task_015/solution/code/example/example.py +e1f763625cdc5f18e456823e76495427f932e0fc1dab7ed688206f98a3f1a4b0 task_015/solution/code/pycron/__init__.py +1c56c78cdbe9c31966a05e0728ca9d7ba923314d83ac0e774ecf5d1b18d032cf task_015/solution/code/pycron/cron.py +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_015/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_015/task.toml +76520256a59f8355068523f1cf3554b313687f60494edc4800a6e1171bb64587 task_015/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_015/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_015/tests/_shared/static_enhancer.sh +c3dd53d33670a707b766568e5816d0b9dc7f7770bf1727e3a87e719b91724d79 task_015/tests/enhancement_cases.json +e79ba6dc2eb4f66014348ac9064676051a47babc326d0d6f6c12f82c54ecdaa0 task_015/tests/test.sh +76725d996818b7eba21765d4842ed55f0c72898914540c83e94bd86f34a32f54 task_015/tests/validate_enhancements.py +2789d044701b591e9318ac2ae7ee4827a861ce1ec8a35763e795596df8e9fe28 task_015/tests/validate_outputs.py +b23d733d0adb6eaec7c5c102d6ee528535ce8b3c70520211ccefabc610bfb67d task_016/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_016/environment/Dockerfile +6c0cb4ba3d4d57ed84ce771d1118344d164408857853ccfd50ce72d8d7dc0e34 task_016/environment/code/index.html +4a4851a42914046c918be009a20d321d3a2ce1542b56d311d2353b82d35db075 task_016/environment/code/src/LoginScreen.tsx +906be24f2c9230c4f25838bef2dd2edab1229e5c8576af2730d5594a88a3a074 task_016/environment/code/src/lesson.tsx +1c3db774e3c44b6b186a040c7c6e2a91d976c3a96d27f231f008847aac277d85 task_016/environment/code/src/register.tsx +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_016/environment/docker-compose.yaml +42f624c4290dad6ab2341d33a352db89f4e0ae88a3f292dc01fac87a5898507e task_016/instruction.md +ea6a137673404bb98e7be4b6eabafeb5d44c0b6a61caa16952ead0d82e349dc0 task_016/provenance/restoration_notes.md +75422824e13639d60c4da5b8c5259b62ae44f9602c7b0c17ed8b1dc7b4f21011 task_016/provenance/user_turns.json +6e528b1fba0c2c012796df820b6c95e8d448e0b163e235195528f8d52b6f3f85 task_016/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_016/solution/README.md +7d12a522d209eba016af3b831037fc5ddeb361b3c73e34eee2a2593c2dad24a6 task_016/solution/code/index.html +5f942a86f58358340e67fbadf655400a870420229f4674edfbc24549f8115440 task_016/solution/code/src/LoginScreen.tsx +34b70c1a06ccc70bc883ad58531bdf180f924a3948a32ad93ec31953e61ab58c task_016/solution/code/src/lesson.tsx +8313b64f66b4d7f2435fab3ec2dc3e19dcbc9d0026d765e3e64cbe9d978d84ff task_016/solution/code/src/register.tsx +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_016/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_016/task.toml +b6d753316992848cd1df497c977624dab439a67e26cf9cf9dd64be8b6097b064 task_016/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_016/tests/_shared/contract_checker.js +cb15071c7de442fd508b17855e49e3b8806b579f994f7e8f246960e10f934897 task_016/tests/_shared/offline_browser.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_016/tests/_shared/static_enhancer.sh +ebae1664c5925f2511e7e60c637d7a9a5c437b12fe4d4d1e0c94c45745600e78 task_016/tests/enhancement_cases.json +be2542d431da5187c8d8ba7e1ab86a3b39e9d6001fa570621c9be6ac9bfe3a55 task_016/tests/language_options.js +23be497fb609dff328be98f7a4c435d97f8997e5e728abc4c4938b753a11929a task_016/tests/test.sh +b9490e1b6ed9461968f236f286bafb3785650da7977683b6e05155e950301b5c task_016/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_016/tests/validate_browser_smoke.js +8324be25bd295c53683526e78b41ec357a88c38e8a998ee507e74aa0f1422dd1 task_016/tests/validate_enhancements.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_016/tests/validate_semantics.js +759703226e2f963a66b165ca419019ec6ba1a92605967c8565125acaa5ac986d task_016/tests/validate_ui_behavior.js +ae09334be6400b369fccf2b3034e28b002ace0ca270ee3d6c599a531fdd56a4d task_017/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_017/environment/Dockerfile +713a89ccd9214158170b272bce58fda956cfdd0e3c7379db0fe6cd1c026940fa task_017/environment/code/app.js +e9ee100d640f2f81715e28e04fc5667fc3973867d2ab88dc76a8f6e75df36f75 task_017/environment/code/index.html +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_017/environment/docker-compose.yaml +150fdca184c98611ad93814cb9b17e937fd1e97102832298b104b79602da81d5 task_017/instruction.md +958c767b6317f8e5d26a35616825081f8eeb13a751ae276817bb7f92b652beac task_017/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_017/solution/README.md +c7dba0e718a7fa3028acc64ecf8303a6162c523e309033041d8dd9d27e1a3ae9 task_017/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_017/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_017/task.toml +20f7d760369a712c4030e58a19c35d7be945e5bb23aabb0bcc8be6f71152d685 task_017/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_017/tests/_shared/contract_checker.js +f6b3d4202f8759781a602c58efecb0821d4413beb45796f16b7cc773aca441ea task_017/tests/_shared/offline_browser.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_017/tests/_shared/static_enhancer.sh +ef7592584e416d7e8b20d08a66bd3fa7bb6d13ee73032ad8b5ce08f09163d129 task_017/tests/enhancement_cases.json +1868b112fa3302f7f9a764bf7310dccd42f70fbd83702b3f135366ce199055eb task_017/tests/review_hard.js +23be497fb609dff328be98f7a4c435d97f8997e5e728abc4c4938b753a11929a task_017/tests/review_legacy.sh +64b448947d3d1344a60ebde1dd50ac03b9cf3d9a06417b03a185b7cca2cc3d92 task_017/tests/test.sh +af5fd77a742693e25999d9fb148e67b5979a13f12b252592bf3ab12b082d6908 task_017/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_017/tests/validate_browser_smoke.js +d257b9f8f1b04f8f16ee130d8c1b0c94cce596855ccfa0e7490ec49bd20d10af task_017/tests/validate_enhancements.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_017/tests/validate_semantics.js +19f02987bce2c7c34cb1a6db20fa43ec08da2a20e8a306722a7c74443dccb2a2 task_017/tests/validate_ui_behavior.js +06b942a92c3344080b876eb34b4df174158d1cb0c33977885da1a6f89f1d0a2b task_018/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_018/environment/Dockerfile +a61a0c313d56ac20f97a838b6bdfc1bf60a145c61b914d43eec06d0048cc3808 task_018/environment/code/app.js +b4497290777ff757a1934d4878895495aa8b7b07cd2983e9e3e9a1ca04da2550 task_018/environment/code/index.html +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_018/environment/docker-compose.yaml +fad87a82c8b8c4a8e12a42dc680d827d60d6a046ab1c366d59ec8063046554cc task_018/instruction.md +958c767b6317f8e5d26a35616825081f8eeb13a751ae276817bb7f92b652beac task_018/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_018/solution/README.md +5961fd5f2123797eec72fbc9939be77064430cb484ead408f0e9334819459956 task_018/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_018/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_018/task.toml +dab0e29e08263f57046b3968dc2b735ea177b7e659d521119f9561de624be6fb task_018/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_018/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_018/tests/_shared/static_enhancer.sh +85a03bb8fbf100d5170409a5b1f38bb5437cdfa15d999d96b0fe5efdd0aa2e5f task_018/tests/enhancement_cases.json +abc75cba72d320a2a5843065849b26c3aa5918e865ceca889e299ce549c21c61 task_018/tests/test.sh +afe7edeb5880273e896f5eda03850337d1c44e31da5ba4cd8ff6bd21faa7f464 task_018/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_018/tests/validate_browser_smoke.js +478c912b10033cc34b3c12502a694c2a482e8d531e25ef0896bfddbb71ba6479 task_018/tests/validate_enhanced_cases.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_018/tests/validate_semantics.js +4e7adb938f4876f0115b0f606e145fbb0ab079ed468a3d0b7ab89d4b5ece346e task_018/tests/validate_ui_behavior.js +a6a49a3f4af03a6cc1b37c46a5d36e7b1fa46f4fbdda3f60a6abdc29e1486a85 task_019/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_019/environment/Dockerfile +b2be2f8f544201931daca119715afe52345df0d738e1888095da5b98ca703d99 task_019/environment/code/index.html +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_019/environment/docker-compose.yaml +24987a6bacca99079d9ac86fcce85146500fd4021e7488e6f9e001cedb4196ff task_019/instruction.md +d03089828b0f77c639f9c297a3211539259078f1f155d92bf69d25fa7b41d64f task_019/provenance/restoration_notes.md +2562f3ee1a1cbfe9a37f841721fbb296d94f0ca6af8d07a5a04adab099b79bf1 task_019/provenance/user_turns.json +958c767b6317f8e5d26a35616825081f8eeb13a751ae276817bb7f92b652beac task_019/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_019/solution/README.md +153fa747b23bc278efefbbd389c7bd70b86e400e9d98cda432578d5807da16fc task_019/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_019/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_019/task.toml +761c4d8a2923248c2c2bde508b20c233f62fc0268bdea7406569d5b76c2ed6c5 task_019/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_019/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_019/tests/_shared/static_enhancer.sh +9b4a590753002467fc2dfb4287cfae91dad0147488c04a34a03bfb739d0a3135 task_019/tests/enhancement_cases.json +abc75cba72d320a2a5843065849b26c3aa5918e865ceca889e299ce549c21c61 task_019/tests/test.sh +388119cda7c7c548647a056ed5f53345c0c0b20fc07814c17680b9a3b944637b task_019/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_019/tests/validate_browser_smoke.js +b8e92f1740b489b11db02313080e3a66dece12af79cc90edbe19a8a1543c2c2c task_019/tests/validate_enhanced_cases.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_019/tests/validate_semantics.js +31c1e644ca25a8b80c031bd64502d02a4e94dd7cffbaa7348edca94b0c868e2f task_019/tests/validate_ui_behavior.js +55fdf300f186e7bd612c26bc91d9ca90de4544e550254b6378ea9aef732d49ac task_020/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_020/environment/Dockerfile +d2be48f4b8d3a28875469c6f8486c055f4151256ad0600c3a14f6e07f46dd289 task_020/environment/code/index.html +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_020/environment/docker-compose.yaml +01510b6b455d55ca3794e4d0ae375f98054485a9cbc7b14409dc92eb8eea338f task_020/instruction.md +958c767b6317f8e5d26a35616825081f8eeb13a751ae276817bb7f92b652beac task_020/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_020/solution/README.md +2551d9f8ef7aa9b060cc263366f67d29197d26636d7e76baa524468f978d34cc task_020/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_020/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_020/task.toml +0f5bf9da8a54a133b1fc11629890cdf41fafd1572ce9dd285887e71983e93b5f task_020/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_020/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_020/tests/_shared/static_enhancer.sh +2075c3aaab1fed24db25b7463d7ba94d7a57f8f9c083cd18e8d7a36acdc59e01 task_020/tests/enhancement_cases.json +0c47e387f28e80c7f09c279f7390f830326317754c1142699b605378f8d4b693 task_020/tests/review_hard.js +abc75cba72d320a2a5843065849b26c3aa5918e865ceca889e299ce549c21c61 task_020/tests/review_legacy.sh +64b448947d3d1344a60ebde1dd50ac03b9cf3d9a06417b03a185b7cca2cc3d92 task_020/tests/test.sh +d5fe2198900301d12cf756decc760490be96f8bcac2318d00e57475a05c5dc37 task_020/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_020/tests/validate_browser_smoke.js +7abe50cd6635e34a0dbbcdd3f08ab540d1a799ff94009747d31a89169e4c0409 task_020/tests/validate_enhanced_cases.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_020/tests/validate_semantics.js +ea5676387ded12423495efa3665ce0131ed5f6803693afb8833fe8359d76c568 task_020/tests/validate_ui_behavior.js +8b0b8d284b07e62f0d165a9cda81d72f1a1efaca4c07b681d2141db5e2203add task_021/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_021/environment/Dockerfile +5aca2a0b43d1caa770b69e2e9d1e14b1b550fab0ffaedba5db0a316dbbe49bed task_021/environment/code/index.html +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_021/environment/docker-compose.yaml +ba2eed3c705c4558cd9a2e9237306585e4cf0bf88432f51064e18cf75daa40ae task_021/instruction.md +958c767b6317f8e5d26a35616825081f8eeb13a751ae276817bb7f92b652beac task_021/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_021/solution/README.md +bf4b0dd1f581381e439b7fcacae0fbc5f89435709904a8e5a64e059e81c9c8eb task_021/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_021/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_021/task.toml +af86682d1e1321494027ded0cef7b75d8021c8d3da84a9c3329e3ca91680dbc3 task_021/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_021/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_021/tests/_shared/static_enhancer.sh +498e03b3b24dc47cf904f6503dbfe3bcd09cfa216c858a5c973052a8306416c1 task_021/tests/enhancement_cases.json +4ef733feb2da8fd6cb8b190cadd4cb7dcdd31d140b8e14f956070e80b682e2d6 task_021/tests/review_hard.js +abc75cba72d320a2a5843065849b26c3aa5918e865ceca889e299ce549c21c61 task_021/tests/review_legacy.sh +64b448947d3d1344a60ebde1dd50ac03b9cf3d9a06417b03a185b7cca2cc3d92 task_021/tests/test.sh +a7dacb7dad70732b95fe7c3ef59aaf4459ac3c75337ee0617f840e5f42d32609 task_021/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_021/tests/validate_browser_smoke.js +263dfd3140b226e5fd52e5f978425f7ae2b4fd56d46ab79c647ed027ca2b2b4c task_021/tests/validate_enhanced_cases.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_021/tests/validate_semantics.js +f304b1cdf71ed947b677f31d1b92f9a9f44fb8970f79aa24124aeaed3f13d19b task_021/tests/validate_ui_behavior.js +b0cf7ef1d332fb5b7352864d71518c7bea6dc5dfe04a3f4a2da00df8bcc93009 task_022/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_022/environment/Dockerfile +62ed6bec738f858932b86fa39a95309598256af1dfc758274579b277ff5a2e3d task_022/environment/code/index.html +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_022/environment/docker-compose.yaml +9f72d0b199d5d82e3df0922f606ebeecd4123c93a9ce61e42b268b0c9fb204c0 task_022/instruction.md +958c767b6317f8e5d26a35616825081f8eeb13a751ae276817bb7f92b652beac task_022/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_022/solution/README.md +21f830b31bdc7151f9568df09d9336ececcd6f890185758304bf27b095a74268 task_022/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_022/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_022/task.toml +ef978ab0a49b8f02ce9e789e3963b28bca802824403674bce3cce9bda6fc3bfb task_022/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_022/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_022/tests/_shared/static_enhancer.sh +3de0e91495a66c09c517a2a234a55310439b1d2cfc97fa951fb5ab323b25cb61 task_022/tests/enhancement_cases.json +abc75cba72d320a2a5843065849b26c3aa5918e865ceca889e299ce549c21c61 task_022/tests/test.sh +f27293821de0215385521770f041bdc1da2bb670e6f9b735993dba66b2df8a0f task_022/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_022/tests/validate_browser_smoke.js +e23d197f5d7b09d44de848267df739f8c9903df80070e65bcf2ba890618afee3 task_022/tests/validate_enhanced_cases.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_022/tests/validate_semantics.js +8f5a33fd0338008343ba43e19c7515a5f13df5461c56627b4440519f9dbffcda task_022/tests/validate_ui_behavior.js +136108f8a3f180bca9fac087229991f3914822c1be7b3e8480704bbb31f18e80 task_023/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_023/environment/Dockerfile +8ffd519afb1b9977798caffc6b470e8a87bfea08355189a3b90f4cafa9f199bb task_023/environment/code/figma/page-1.json +99f6e6fbc7d1acb64f46abaf69c52ae5caef0e888f36dbf77c9afdc506b7919f task_023/environment/code/index.html +81c7353d98b36ad448f37d82ad7cb554d6a877efa2cb149bc513a8e3887cb76a task_023/environment/code/package.json +efd825c0643d35e5fb14fa1bad0fe5ffc18f306b4fca0ac06fa3f77549fa30b2 task_023/environment/code/src/app.js +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_023/environment/docker-compose.yaml +5c9a06f33dde62518e2a59b141edb600a4e63b98bd0d53e04ff11d49f99db73c task_023/instruction.md +1b8bfd7dab27af71a2656ef7ddd8cda5d7e8c44663b6bfaaea097f454be97b76 task_023/provenance/restoration_notes.md +f60041cb91640f9994f9def4fac3769f8ca6242588e2bb204edb42891a22a06a task_023/provenance/user_turns.json +958c767b6317f8e5d26a35616825081f8eeb13a751ae276817bb7f92b652beac task_023/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_023/solution/README.md +99f6e6fbc7d1acb64f46abaf69c52ae5caef0e888f36dbf77c9afdc506b7919f task_023/solution/code/index.html +81c7353d98b36ad448f37d82ad7cb554d6a877efa2cb149bc513a8e3887cb76a task_023/solution/code/package.json +efd825c0643d35e5fb14fa1bad0fe5ffc18f306b4fca0ac06fa3f77549fa30b2 task_023/solution/code/src/app.js +8351df4ebf58d2dca55e41986fc21d912210e9f978c53ac595ada29a1f38c05c task_023/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_023/task.toml +ac01ade73637d8d435fa6a6a8909107907f7cc869458a5ffe9f3b38918ff6259 task_023/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_023/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_023/tests/_shared/static_enhancer.sh +5e3e1f8f34f04ffc185681fb34666945f2fcf0bff759fd002672350a416a79a3 task_023/tests/enhancement_cases.json +abc75cba72d320a2a5843065849b26c3aa5918e865ceca889e299ce549c21c61 task_023/tests/review_legacy.sh +1cb8ba4c2566bbd9ede5247e222270c1ee55e81a44ee2cfcbf3aecb71852d4d3 task_023/tests/test.sh +c63ebb6584a373f7125090d8ede2a187cb2c8246fa4bf0d43bde99c0b0c97677 task_023/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_023/tests/validate_browser_smoke.js +d1d00072d12df8338b622003c0c0d5c0d1fa0b1f321465b77553bb8717e4f029 task_023/tests/validate_enhanced_cases.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_023/tests/validate_semantics.js +3bf016cf467a4647895b9eff7aa1b22ad70b3c3c2a8d187890c2b89d152f0e5f task_023/tests/validate_ui_behavior.js +d673b79e6b397c267dbbc92bd21f171ad15dd845640f15e3e6d54b34d0605419 task_024/acceptance_checklist.json +78dbb49c9520c95467d2eb8f421a96d928b01a02ec519ccf3080e94e1491f61a task_024/environment/Dockerfile +9349578430f76bb9a8319d49a75aa3edbe3506e2c453c6ffe859f828c3adf925 task_024/environment/code/titanic.csv +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_024/environment/docker-compose.yaml +ce410a7f878bd3b3cd4189a65e54ecb06d6511e049ad90e850e47c5b999a5c1f task_024/instruction.md +7fb6cd282aba63bac6b17d7eaad0172bd36eaee90d7eff2f37111b6c99891754 task_024/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_024/solution/README.md +b33481c3aff956213546560f0db7128e9dbf351d6c892a969ef2ed1aea5d34cc task_024/solution/code/solve.py +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_024/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_024/task.toml +21c7aeba013e475312a090c761d53b48f9d7d82bd2e4f5327758c0690e5da960 task_024/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_024/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_024/tests/_shared/static_enhancer.sh +e3ead0e4101d6ac250add117aa1555f3b1b6e8f1de1292f796c735b7582ef956 task_024/tests/enhancement_cases.json +ec919be8e0e37ed248d522cc7754c30d97000cc76fb9845a7c44ca7f313916ed task_024/tests/test.sh +453b56d5b9506665c5c1d64237808861e21891a53c0c40bb5c1216685c8d06dc task_024/tests/validate_aaav_dynamic.js +2a120c0bd7efec88b6fd5cedb0d145a27376055013aff07195a49a4f213a35c8 task_024/tests/validate_enhancement.py +8314e912dfeeda97cccda66337b021b40925e5d7030a872b405c5e2f2a059108 task_024/tests/validate_mutated_input.py +284f0fc40f22c079a2ce2481abdd5b68217de04c35ad1dc5e4cfce187b7fe1ff task_024/tests/validate_outputs.py +695909136c95458a838cd106c51e6c473f6e32da21a23cdce30ce27e3744687c task_025/acceptance_checklist.json +78dbb49c9520c95467d2eb8f421a96d928b01a02ec519ccf3080e94e1491f61a task_025/environment/Dockerfile +5235634caef6c46cdc8a8b924403092877293d0e0c923d4d4a598d9804972535 task_025/environment/code/gapminderDataFiveYear.csv +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_025/environment/docker-compose.yaml +fc766f57be3c5fbb7dd5e4c30d80c5851986e4aded187754641fd0ce6a2c5fe9 task_025/instruction.md +1fdc7beec940d1ed700593be5b5cc5799e8fcf9e4a7da6cb6146ca322221484b task_025/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_025/solution/README.md +a86cf0b5433e2564d5e503fb84aa1ba4d37b97fd698d67dba3275d3789ea98cd task_025/solution/code/solve.py +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_025/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_025/task.toml +f1dd75e878dc47a1e53bdf5894adcbdaf5d063a67ea333d9a341221db824769f task_025/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_025/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_025/tests/_shared/static_enhancer.sh +247c99a8cb9dfae0a058711a39d583b8d4801a01a63e9bd30872dd49345a9d06 task_025/tests/analysis_entry.py +ac94c05fefe2451d864d484713ff9adc2ac01096929af4ffe91e33994961d9e8 task_025/tests/enhancement_cases.json +a3e1e0c262c2b6b969782a04a26be08fbaf6a210fe26e283a3a7753d161ce793 task_025/tests/test.sh +04c4965af0b8241f8649a009f45cec1284c9c68ece0dece5edc899eb2eb2e5ee task_025/tests/validate_aaav_dynamic.js +eb3f2c9c654431968daed8ddf45b79b4fc3819c155fb6abd4e2e56c90fae666b task_025/tests/validate_enhancement.py +f47d508523f9e1ff1f2d45b1c38821c8420cedd110883deeca985e716a719646 task_025/tests/validate_fresh_run.py +d3a0ffb35da2a3e44d0c3fcca7e44a7c17740e86552c32a97aea30f1058d4b6b task_025/tests/validate_outputs.py +e12649e60c25a455a84973d86cfa54df53091d6e53e6417b57b47e92830691a6 task_026/acceptance_checklist.json +78dbb49c9520c95467d2eb8f421a96d928b01a02ec519ccf3080e94e1491f61a task_026/environment/Dockerfile +c195e4eb53d7818af7aa69057e2c0ea72aebf35db5330859b0c51f53d1bb9bb8 task_026/environment/code/BostonHousing.txt +61af7c187bcbec1741dba196263224f2051776b8bde5b3ffaaf51c7fe6ae579c task_026/environment/code/titanic.csv +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_026/environment/docker-compose.yaml +aa638961b0059c36e6be76d6ab612f2e1be4d5de4198073cf1dadaa89803d586 task_026/instruction.md +1fdc7beec940d1ed700593be5b5cc5799e8fcf9e4a7da6cb6146ca322221484b task_026/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_026/solution/README.md +e792c1222e54c70196da381c59607cf0e811ae485cc4f0619ff88c581ce608f8 task_026/solution/code/solve.py +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_026/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_026/task.toml +14be3cc16394ad164228abf93da1f7138e75ce1d40bf115903fd0b9840944d11 task_026/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_026/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_026/tests/_shared/static_enhancer.sh +5cd7f9b4ce09b86fc9d3a5beda7e8e67785a24f27aed1564ba0b7c966c423670 task_026/tests/enhancement_cases.json +f3bdbd0f967514b6a0d4e2a76065b46b1793e638715bdcc24fd467db3ba77f50 task_026/tests/report_contract.py +2f7b4c185ede0e65c987118c200f2fcbe39c82d4c8a7a699693f88b9581e4062 task_026/tests/review_report.js +4d20fef4b53a03d2c2b027159861cab61e38a418c1f5b7f17d827f2c68711bf1 task_026/tests/review_report.py +188e5f32af8e710698dfc76cc64db8af163ccf261b8969b04cc79d6644abb2b4 task_026/tests/review_suite.py +2d275632b0f955f60b70489cb58e80892beea130e3cc8042f02f4c7a57fe512a task_026/tests/test.sh +77956008fb2c58f2e17a602cbdddf6e2cf148770cb1560b1fe20fa932ee837f1 task_026/tests/validate_aaav_dynamic.js +d659de7a392215aaab72adab9059b4bad374d23af48bdadf2ba2eea9ac0ba6aa task_026/tests/validate_enhancement.py +a889606725d90355465f689483f71af64495d02e9fbe85a722defb7eb2294fcf task_026/tests/validate_outputs.py +7900464e506b0ab1d937758014496da375edbd8f5b4a94968267420eda60c314 task_027/acceptance_checklist.json +78dbb49c9520c95467d2eb8f421a96d928b01a02ec519ccf3080e94e1491f61a task_027/environment/Dockerfile +c0aeb4bed7e296b9bfec8c68f61b55b56c4f0140f921156794dbfce37b06da91 task_027/environment/code/diamonds.csv +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_027/environment/docker-compose.yaml +b65c44a66771a55ebd274c6648ee3d78b12bd0ee17eec12c07fa67ab5c4c9f86 task_027/instruction.md +5cdc4dfff335e6d6beb43a8a9c7799a230f39c58898f6e3396536fa39e326c44 task_027/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_027/solution/README.md +03f460d82821b33f4b79ba80434ae5f865394e989cab46f2aee7902d47f15380 task_027/solution/code/solve.py +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_027/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_027/task.toml +a64ad0df4f379b25a3660c1705973950e8648da6b99f5aa5b848c470605c3b05 task_027/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_027/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_027/tests/_shared/static_enhancer.sh +247c99a8cb9dfae0a058711a39d583b8d4801a01a63e9bd30872dd49345a9d06 task_027/tests/analysis_entry.py +3c04bf6107b8a11364b7443bbe1a4d5a4554eee924ffeb40348c7d3abf252cf0 task_027/tests/enhancement_cases.json +b88520aec74f7bbb12f760eff1268a41a6b7a54dcfe96e04a1f5b923eb6f874b task_027/tests/report_contract.py +a1912f162ad227636958e0407c04ddd78c9f1b144a28c1a224bf050456aa2ea0 task_027/tests/report_values.py +b2f740e8b1d2fc01cb65825a189630ea499061c162a3583cda1f13e885a8726a task_027/tests/review_report.js +def2f056e1712ab393abbe807f451b1e2143f4c3e81793d2486127756c6951e8 task_027/tests/review_report.py +5e0545b0cb9b26ec96280ea17a3956e795a68182052709e69a2a9022c8f09093 task_027/tests/test.sh +5bd99672515fb8a5c8340517a91ac3ccf20c75a734d910c88f3c9c5b3821a801 task_027/tests/validate_aaav_dynamic.js +a04ce471caee4882db00e7fba8a9f54bb2fecceaaaffadded06f6501fbc604ce task_027/tests/validate_enhanced.py +da03126c5f213cb9fec379ec529496702ee3a88c7decc74a9e23a4c953a8538d task_027/tests/validate_outputs.py +4b8afac58d49d1e889fde056c1617f54444082722c1af608be799c637f20662f task_028/acceptance_checklist.json +78dbb49c9520c95467d2eb8f421a96d928b01a02ec519ccf3080e94e1491f61a task_028/environment/Dockerfile +39967dc8b4ee21428317b95fbd733bac5339a186bf70a366ee376ef572e9e928 task_028/environment/code/spotify_songs.csv +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_028/environment/docker-compose.yaml +94791e82a0e051a6f819a9eb225512ab3cb4e19da6f726351317e967dbc52ab6 task_028/instruction.md +57c0a27df4681b34b925f3c97392215d7459c23aa7b84070aa0a244f56a5dfaf task_028/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_028/solution/README.md +50907d79ba3a9996d492f5241c90b6a8b166e00a6ef697f5e21e3c395e452546 task_028/solution/code/solve.py +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_028/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_028/task.toml +ed9029af5bc8c72a1ead0362549e76fc62d61a4194d88cf1d3d7c6abc3a537eb task_028/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_028/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_028/tests/_shared/static_enhancer.sh +498d0b19bd8bf259b095b2d7817d352b9a64e7575ed7a20349fa457625349a43 task_028/tests/enhancement_cases.json +faec4a80883229d1e3cb1703e28d028d6685d5316c715571e5b5a8e620bf1b04 task_028/tests/test.sh +4b30df0fe5862115a8980ba447dd9275980ef7f8e3843f1b6318ef02419f5180 task_028/tests/validate_aaav_dynamic.js +1bfcf17b60d152d1420858f96a93e6e20e6caa6894df9885cd47714b3f921c2f task_028/tests/validate_contract.py +be51c098d01d7c48bede9952e28d906c92618f7e43ed0da6918ccf42e28f234c task_028/tests/validate_enhanced.py +1bc8175365805eaa0d0add1dad7f013a60f45483fd80c28b08148a2083906cc9 task_028/tests/validate_outputs.py +cc2890d620d5a9e0af5366147920ea2cd12caf1b681f20860bab0fd5a1291b75 task_029/acceptance_checklist.json +78dbb49c9520c95467d2eb8f421a96d928b01a02ec519ccf3080e94e1491f61a task_029/environment/Dockerfile +3df7e1df09872ea82d7365cf4176f7c1ea18632e8f77772bde2493bd55acac31 task_029/environment/code/README.md +42b507b9f8f9928caabebc3eb698f21f2144c3152e3bbec6068de16fe5692dcd task_029/environment/code/train-images-idx3-ubyte +7fe5b10fe830ca4c05de6b47e399e78ad70b5116bf65bd8febbc683f29152502 task_029/environment/code/train-labels-idx1-ubyte +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_029/environment/docker-compose.yaml +98fd88f5a3fc11d6bba364ce9c4adc3f6277936688772b88b5bcdbb0a3f500de task_029/instruction.md +b6cba03c4b6955cf74cba99f613f4337f1705b464351d542fe52e0df389be6c9 task_029/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_029/solution/README.md +928b5b7b6272bf23f82e292aa4828b7f5fa228e2c339858f3ba7b78d03a10b29 task_029/solution/code/solve.py +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_029/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_029/task.toml +cd58d5f2a88f2719ee4c1b471c56e40bbd4b28e291e89abfa31c0d295493e602 task_029/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_029/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_029/tests/_shared/static_enhancer.sh +fa07a91ad8441dc3940be06d45d0d82f8f560d6bdce44420f17c2109c1a60e42 task_029/tests/enhancement_cases.json +3c7a93bd85b97161d3c3083bffebec1e918df5e1eb8e485317194f4c52e2cb5f task_029/tests/test.sh +8c64ebf296731c55f6e9403200ca56920e4015ca3e8b52887048e9ee5a146522 task_029/tests/validate_aaav_dynamic.js +c627ef730f6e1e797936dd704775e30f86f699d766b1bd8f6bbd36d425b23c12 task_029/tests/validate_contract.py +12e5f370657c67373c70d818f1378b061a032887cf9337cf0ee518c63a4d2fb1 task_029/tests/validate_enhanced.py +f088da5150b0fa78c77a71b05095d26f89be6e7f09083c581aaa5d21eaaa9b53 task_029/tests/validate_outputs.py +a9268e7fec285021a407dc9f28fcf494bd0038f00731e51771837951f3d22dac task_030/acceptance_checklist.json +78dbb49c9520c95467d2eb8f421a96d928b01a02ec519ccf3080e94e1491f61a task_030/environment/Dockerfile +da60f3c20ffafb90a77847b7d358765ee3285f08d42c94bf15423c53d2143b2a task_030/environment/code/README.md +7c35e11d8468bb1957cdff1bf58cff0069f68dada02be0931e0543c697061763 task_030/environment/code/cifar_tiny.csv +5a5b1710ec9f6c5b3210b9f4381841762e9ef9b6d637de650b019c0871be7b0c task_030/environment/code/images/img_00.ppm +a48a12be393ae07b832b2b718a60fa3eba482a78bc6b36465585fecfeb484aca task_030/environment/code/images/img_01.ppm +38e9530a8902da7b2f99df370c83fc9a369af45580eee66897311c87d33519a6 task_030/environment/code/images/img_02.ppm +efdcb17f5413982238566aaee094d12d6e2ca0b480157a1775bd2ca2c9eb6c35 task_030/environment/code/images/img_03.ppm +41b1b72067323f89f0ad83a428012d3ab5463bba4e647e449fb767679e1fd320 task_030/environment/code/images/img_04.ppm +ff0cd1e6c1f25b64685960e558a73725a976390c3e770e0f837827e715d366c0 task_030/environment/code/images/img_05.ppm +1fec7f351215d6153f40eef65220d6de4191e0b012c52ddf9d68353995ac8f31 task_030/environment/code/images/img_06.ppm +f613a03d800f193541958ce3acc2dc0db8439caf1a222c902b77c5db1a0384af task_030/environment/code/images/img_07.ppm +4ab46251a9c6b8c0e385b2ab61da376a7027fe23d46631847048a988b1e53553 task_030/environment/code/images/img_08.ppm +b9ff9a433591ebae15afefa08c5bc5694f03314f571d26820882caf3211511b5 task_030/environment/code/images/img_09.ppm +37d8d70c3cfca3ad86f9f7a067f0e7f9a99c3b3fe5910df9a895df29c11fe288 task_030/environment/code/images/img_10.ppm +b7d4f7d3c8c4c13bf2bfb5c17de05de7407fab99b767790dab87d019246d2de6 task_030/environment/code/images/img_11.ppm +90c1b001a0217dd1a0057c6e922b03eec1b270896320f4d4e1c3a15b9198456c task_030/environment/code/images/img_12.ppm +9ea6a5ff4a468dec80c99aaf624b2d10fd287fb887cec630db0ce30ead2c262d task_030/environment/code/images/img_13.ppm +49f87f7b0d755713d29b0dd4171c85b0bbb908ef0d3a8da86fb4ce3078806176 task_030/environment/code/images/img_14.ppm +6e3cd796c8c6357ece61c0188ecc3cc4bca4c962ae32983ff245f37eb47a5317 task_030/environment/code/images/img_15.ppm +6bba7de5fa9c7aea36436f4409af4813451143d7a73f267819f80d72fac36f52 task_030/environment/code/images/img_16.ppm +026474d7f3d80bbe2f042b9c3d12ec5964f954307a942af5ae76728d3d9fb430 task_030/environment/code/images/img_17.ppm +fecd53ee0827d7bef92047df969b2119074de9a5940a950b06b33539183231be task_030/environment/code/images/img_18.ppm +580cae62bd112b38a137585a6d39db55948b772e391dd568ada8ffdf0e14f682 task_030/environment/code/images/img_19.ppm +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_030/environment/docker-compose.yaml +5cac412633ea3851e58ef43871b99b2d863c6f21883d39881a6b0b5a0d6e1e0c task_030/instruction.md +6e528b1fba0c2c012796df820b6c95e8d448e0b163e235195528f8d52b6f3f85 task_030/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_030/solution/README.md +0a5f38b47d50ddc600c18a8710a8083313dd74b5d485c2c9af86aac8183cb548 task_030/solution/code/solve.py +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_030/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_030/task.toml +df88c36074280fccf2ffc5b12aa1e4ee808f0f5f8fecba42b21c945786b0ddfc task_030/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_030/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_030/tests/_shared/static_enhancer.sh +80e4a30c568f9e066ec05a8e547b6970d725432cb25d188b0699e927aabee659 task_030/tests/enhancement_cases.json +85bc08bbb21b7d0910d1eb1daae649ac3640c9ec65e7970a521b88109d5acd10 task_030/tests/test.sh +183f8826e25aad753b21030c595c97ba396766887ce317ef036e43c3b21ff21c task_030/tests/validate_aaav_dynamic.js +e4f51c0127bfa3aee4b770095a067cfea140735f7c52764b9a3f4d00c83c33a5 task_030/tests/validate_enhancements.py +5b0a9fe7c09203abc4a3f75343928201a5496ea6bc11f8b257dd699b6333c819 task_030/tests/validate_outputs.py +ae35118fae0668f724034b7f9ae3e963704eab042ad7012a7b19ffc7e285a08e task_031/acceptance_checklist.json +78dbb49c9520c95467d2eb8f421a96d928b01a02ec519ccf3080e94e1491f61a task_031/environment/Dockerfile +418a59ad300dc6384983fa95a97a3ffd131b1b1293828325dfb67c46f59ebdb6 task_031/environment/code/Audio_Speech_Actors_01-24/Actor_01/03-01-01-01-01-01-01.wav +812eb62c10afc8a5853b4654b3f7e6ff3b1f1cd19486e36f4f11f12102b311c7 task_031/environment/code/Audio_Speech_Actors_01-24/Actor_01/03-01-01-01-01-02-01.wav +027c0b1bc6ac35700e1045e37169d67545004560b8d4a007c24b766cd499744f task_031/environment/code/Audio_Speech_Actors_01-24/Actor_01/03-01-03-01-01-01-01.wav +5fd93b2f2a15c28d9f85fd9edf59288356feada2c7bd103d4b419a12560a51d5 task_031/environment/code/Audio_Speech_Actors_01-24/Actor_01/03-01-03-01-01-02-01.wav +19acdd9d72895e2a52e2e287ab1d8ec8310dabd3d461077ea562c0e6dee61d23 task_031/environment/code/README.md +6972c52677a2705b5410978b3c709515b313b6243e78dcb0181ebc0c5f1b62ae task_031/environment/code/analyze_ravdess.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_031/environment/docker-compose.yaml +e4ea2412e4d39202a3f2343c6695011dfbbf3b32dd056331cb7b278af1685b30 task_031/instruction.md +6e528b1fba0c2c012796df820b6c95e8d448e0b163e235195528f8d52b6f3f85 task_031/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_031/solution/README.md +e74042643d444d1c2fac6752a6a486217c5a90d815b9e9ceb235b7aa2f334083 task_031/solution/code/analyze_ravdess.py +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_031/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_031/task.toml +31c6c567c698d59bd61fe1b3cb19db883691d545219eb23679355464aadba9a7 task_031/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_031/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_031/tests/_shared/static_enhancer.sh +ee3adbcba1db683e3037f0a1364f4df89e3783cd5c91b97a972c9046311f1ad2 task_031/tests/enhancement_cases.json +145cbf39bb7c0bed68d31c61ce129ec1b908e643d4e8379204629e1dd606986e task_031/tests/test.sh +f6f718af09fc3c738f6343b9a5271ea8bc804c57a48a30f7dda5705fc3da7907 task_031/tests/validate_aaav_dynamic.js +67f0c08ce2f73b1d8c6375ac29d9e52add192361637ed74a84cc97c8d429b895 task_031/tests/validate_enhancements.py +680505bfe886250370a893617f835392b1080478332f771a2c53291e8cfb5869 task_031/tests/validate_outputs.py +65d89eaeac02b5d545ba7aefa1e855146a312edb17d68931ace0f41052645220 task_032/acceptance_checklist.json +78dbb49c9520c95467d2eb8f421a96d928b01a02ec519ccf3080e94e1491f61a task_032/environment/Dockerfile +225325fdf628cc4e6664c90be6643bf94098aa86fec47bb103ac593397954572 task_032/environment/code/README.md +eb7d60d8d48f04c139310b1de3d80c457ef6f0ce699a358d8701567ab351c1d4 task_032/environment/code/expected_ocr.json +d72af7a908f90d1325c5923d88bccf7ba1395ef1990c6ebe51c9d6c54928ed9d task_032/environment/code/general_ocr_002.ppm +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_032/environment/docker-compose.yaml +f52eaaa3a8f7dd11b813a7ee972fe62e8234b9a44c9051c4663d69e18ae809fc task_032/instruction.md +6e528b1fba0c2c012796df820b6c95e8d448e0b163e235195528f8d52b6f3f85 task_032/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_032/solution/README.md +a5c99164e4c4557b000ef2d50d92677abe5eb646123d1fef7d03238b6b4218e8 task_032/solution/code/solve.py +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_032/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_032/task.toml +42c8e17593f1df1c72d07f7698ad07aa6010ed2554a2d74d78104d5a18506f05 task_032/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_032/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_032/tests/_shared/static_enhancer.sh +88ff925785039361fb4399b80a59ac6e59ba6e8063dcf9250ec448a9700d85e5 task_032/tests/enhancement_cases.json +aca78ec1ff1de13268e16d517ed9b759fb343a23fade3e99ebefc7721ed44bde task_032/tests/test.sh +a421a308198ed25f1b8c1368782a2d590189017a8875c354e877de387a87aaa1 task_032/tests/validate_aaav_dynamic.js +0755ebb18a6a5862c1f6010d1b34e0ddd7adf13ba255ad7749564a6dbdca6982 task_032/tests/validate_enhancements.py +fef24a614effcdda550ac0cf3939456be5192fdd8d1226a97537e313e3f430d5 task_032/tests/validate_outputs.py +61f0fbb3085d88c45cebc0fe38082232a841093e3d0297e94951badf53886bbb task_033/acceptance_checklist.json +78dbb49c9520c95467d2eb8f421a96d928b01a02ec519ccf3080e94e1491f61a task_033/environment/Dockerfile +3df7e1df09872ea82d7365cf4176f7c1ea18632e8f77772bde2493bd55acac31 task_033/environment/code/README.md +42b507b9f8f9928caabebc3eb698f21f2144c3152e3bbec6068de16fe5692dcd task_033/environment/code/train-images-idx3-ubyte +7fe5b10fe830ca4c05de6b47e399e78ad70b5116bf65bd8febbc683f29152502 task_033/environment/code/train-labels-idx1-ubyte +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_033/environment/docker-compose.yaml +a125f90d2ebe272c3c7dc75a716831fc338bc311f60ee1be46c703b17d81fe98 task_033/instruction.md +d62d74f4e15d45e084d137a70a98a95315d1e8df9c88b704e6c841dbb5199eb3 task_033/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_033/solution/README.md +b08b7deea9d48eb5751ff69ba525ed4993794185fb0549034eece5496a3003f3 task_033/solution/code/solve.py +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_033/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_033/task.toml +0ae05c445e150b15cb625004c9d5dc446fb6c7a6c595dea15e49230bf8f5e0d5 task_033/task_meta.json +bb8e55ca76c26a553d1244dfcd2503a1d9fd31e063dd484ecd065fe36464bba4 task_033/tests/_offline/sitecustomize.py +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_033/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_033/tests/_shared/static_enhancer.sh +2053b1c6ee2361665ab0bb9d2eee8aa3eaec84444ac0d87d9960c36399db012a task_033/tests/enhancement_cases.json +2a64d87ffb085ea6534e6ccaceaf64e92fa2955e47af705eb43e4087ad1840dc task_033/tests/test.sh +52e99be776e1741fc57bc51765b19b0449525e6f1ea6cd153b9064d32dfc2bcb task_033/tests/validate_aaav_dynamic.js +4f80301ccb7e9065bd2d8a22bc5baaa764a1202a2ba2890d88e3079391636ed6 task_033/tests/validate_contract.py +680de5393b06af99c19fe9ec683a65d58578d892ff6ea80e2104ad6a21ace1f2 task_033/tests/validate_enhanced.py +044825231ad7418446dc7bac775567743aeb97d2b56ae743249d73545b0edf22 task_033/tests/validate_outputs.py +f4d1edf45bda662781ebab2e7d4d9aa0baa61073fe9712d4243be9a834078098 task_034/acceptance_checklist.json +78dbb49c9520c95467d2eb8f421a96d928b01a02ec519ccf3080e94e1491f61a task_034/environment/Dockerfile +ad0f094722d756e7165f23787eeb48e1ac402ab15b04b72c9e016d0a39f215ef task_034/environment/code/input.ppm +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_034/environment/docker-compose.yaml +bd6a1c1608f668368c309754aac833b31135d98c7518d67e1e99843e8388912d task_034/instruction.md +7fb6cd282aba63bac6b17d7eaad0172bd36eaee90d7eff2f37111b6c99891754 task_034/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_034/solution/README.md +0d2af740dd6c09bcb427944bcc6abe05a723305010230869b2fb4dd655a7ebf6 task_034/solution/code/solve.py +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_034/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_034/task.toml +3570985acf1709b7b01bec85a5ada1ffe85c06c67650cb35fc4aa1090f947d6c task_034/task_meta.json +bb8e55ca76c26a553d1244dfcd2503a1d9fd31e063dd484ecd065fe36464bba4 task_034/tests/_offline/sitecustomize.py +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_034/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_034/tests/_shared/static_enhancer.sh +1669727c077a69191327d62fa4433c129a037e89b49ed30576c9dc4b6d2e2d14 task_034/tests/enhancement_cases.json +b6b34aa7c8297647c9387fc96d2510a5ad0df71b10b432281cfd71547068825a task_034/tests/test.sh +c25df30dbf843b3279a6438d114de170bbe01475670a792a094e56a093fc671f task_034/tests/validate_aaav_dynamic.js +0e1440a7a7478ff738518e463a915ffe9b01e519c36f6f35d3be48b35aa9e6a3 task_034/tests/validate_enhanced.py +919bd3e30ec9392518554cbb9cd51ec70b49acff1db077550c722b305366712f task_034/tests/validate_outputs.py +7d62a4cb9e544b1f29ce2e03616d5206a4bc8e02f303e83683465552b71c1e19 task_035/acceptance_checklist.json +78dbb49c9520c95467d2eb8f421a96d928b01a02ec519ccf3080e94e1491f61a task_035/environment/Dockerfile +c9505ea118e8118906196915a7a4e11b923ad73613bea35be9aa97cf6a7ac47f task_035/environment/code/test.csv +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_035/environment/docker-compose.yaml +5d31b93f668e4f4f060c1042ccb2144aa5e060383254ff12528dd668d433537d task_035/instruction.md +7fb6cd282aba63bac6b17d7eaad0172bd36eaee90d7eff2f37111b6c99891754 task_035/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_035/solution/README.md +cf68b9e2e7d6083d6db8f2c17f042eb117d67b52a9c1ba8fe85e884e98ff58a9 task_035/solution/code/solve.py +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_035/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_035/task.toml +a0251630491918a4f0a3149a8adce0fb5e3b7ee67dde657ee2516c3e6b75a398 task_035/task_meta.json +bb8e55ca76c26a553d1244dfcd2503a1d9fd31e063dd484ecd065fe36464bba4 task_035/tests/_offline/sitecustomize.py +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_035/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_035/tests/_shared/static_enhancer.sh +d29cfb61f105ec7a4b395edae0a2215fb07d544dc42431ddb1e5def8bc753023 task_035/tests/enhancement_cases.json +f4e882112a99ebafbe6f67ae341c16d3c8106c1dd383fce32459912c52d080e7 task_035/tests/review_hard.py +df44ecbe4b23f1780426333507a152e0ecfad3c56a4562db64372d17220f8364 task_035/tests/review_legacy.sh +939c60cf5c1fc2d773b9669644ddf8e8a978aa5dceb194e64da33e6b5510c40b task_035/tests/test.sh +4bd23e35b036ff79f630108da7e539a93e170fb9e20d10edac5772d02fc64ad1 task_035/tests/validate_aaav_dynamic.js +f556f2c005a103d8d0992abfc73fd208b2b6609a22fa540e9e807ba2a5e1f0a7 task_035/tests/validate_enhanced.py +4659013a1ab65a845bdf2bb9d952f294145fde5359fb3f7d9cb8ebd7cd2e8b3d task_035/tests/validate_outputs.py +9cc40609b62124f9cd55b88c852ea7290db862eb7f3a51d9792afe86eb96e638 task_036/acceptance_checklist.json +78dbb49c9520c95467d2eb8f421a96d928b01a02ec519ccf3080e94e1491f61a task_036/environment/Dockerfile +677368831b98442b5da4c2306c6d8e8bc036f0ebf0335031ae1ef1964cea93b9 task_036/environment/code/data/dataset/000001.jpg +eefae1b8a126235b6559d88b8507fd07f3e2ac555c2ef1fe518999e03a267fa2 task_036/environment/code/data/dataset/000001.txt +cb161f124ecb971d5348949c849df651d0b18d8d2b6e5e844bb3440397cbd8a4 task_036/environment/code/data/dataset/000002.jpg +f81691b612c71b7b28b7ea9be6b56d812e822961dbab567f6b6772aaa84a5c0f task_036/environment/code/data/dataset/000002.txt +5a99aad7dcbde2c0b675506aaed3bdc713577c8dcffe535273d2b5fde045dfaf task_036/environment/code/data/dataset/000003.jpg +76d493825831a28d6a7d1ad5b9fae2ea72e334047bd78815a84b34d4f084897a task_036/environment/code/data/dataset/000003.txt +e959863baf72552dcdf6e9a8f9320f6ef722c11337b20f33cde6af94f7f21a10 task_036/environment/code/data/dataset/000004.jpg +dc580f434ab491793c1f0169d45b8e7d9e3924c01d3589eadb5032b2839dc688 task_036/environment/code/data/dataset/000004.txt +172bc5922de930781fb1d4536e9db51cba306e311317b493f127ce7a386df0d5 task_036/environment/code/data/dataset/000005.jpg +f1643590c6288f24c8eb9714224f185eed12c96e0ac685e0595405751156116f task_036/environment/code/data/dataset/000005.txt +b37d0eb98c04f92d59c66a0c4d2ef32847b783bf85d49f5cced3c28d32605d38 task_036/environment/code/data/dataset/000006.jpg +31eec85de0f1b3636facc73afd7816f0b4c81152f940525a16a2e93db89d2615 task_036/environment/code/data/dataset/000006.txt +af41c8e0c09dfaee685192e5588a7f5eea773941de5bcf1e1d82be2a95c17221 task_036/environment/code/data/dataset/000007.jpg +2252c73793a89daeb88511ac0db7277d24c8d27bd7eac40adddddcba1a3ded06 task_036/environment/code/data/dataset/000007.txt +b2c9e86e7eff48542d19deac6efca77ae707a2268160a38eeda173257c133624 task_036/environment/code/data/dataset/000008.jpg +c2b5d65ca2da53e716205d02ede2e431e4ddbe2b74fccd9a07b1b11967659301 task_036/environment/code/data/dataset/000008.txt +faf9c36eb50a8aeb121216f2b986c73da13c08be178cfc92efe299d5a0a93a26 task_036/environment/code/data/dataset/000009.jpg +724539bd3c583ff912a1d511c2521fd69fa072e0ba70a9caade6dbae0807d414 task_036/environment/code/data/dataset/000009.txt +b0b0cf31aedd9a744e16fef918e308e0c4d491f4819b79e9c1dd241edc66a8d5 task_036/environment/code/data/dataset/000010.jpg +d6e3537ebb89006401d66b653a6ad730463ab512e9274cf1c8d4a37645b3b8b6 task_036/environment/code/data/dataset/000010.txt +2ec87438c3f193e3106315b69cd3cb00590ed50aec56a31535ecd0eb71c990e7 task_036/environment/code/data/dataset/000011.jpg +921efc2c0433729eddbe2d0a88afd48da800afe2f31b427a20938fba2e7635de task_036/environment/code/data/dataset/000011.txt +0bd898a9df93938f80d8d94b12c5bdcd3f4208a83d11f46e1f8af55fef7f9fc8 task_036/environment/code/data/dataset/000012.jpg +62552e33a268dbd5a4abf83f54c968239e7d9bd293444a71cb7c6060afea2b13 task_036/environment/code/data/dataset/000012.txt +64b8c7138f07d1d7284cffeacb5b67f4f203febd803c05bb3ba39b3cf08a2d4d task_036/environment/code/data/dataset/000013.jpg +10baa6a19bc1bfc8d2dbe82ecea304e4cbf9e453e43ede845741d609cbd82d61 task_036/environment/code/data/dataset/000013.txt +6a29353274c9b568bb45ee968bda274c1cf5e1cf83e67a5bc6b23db2e91eb27d task_036/environment/code/data/dataset/000014.jpg +296d644e1018a093df748e0907ec94452a228ee18d54824756ff94ad01e1ef2a task_036/environment/code/data/dataset/000014.txt +c1c7c2bab8e169f7212ddc16d2a0305f8c612d979c8556e8ec07a5b7b0f70699 task_036/environment/code/data/dataset/000015.jpg +414a634645365cb429fc7a6d4d0f2e5e27ad8cbf412d1d84d22affc7961bd4d9 task_036/environment/code/data/dataset/000015.txt +fed13d3a998f72f3abf18718fe601e09cfeee308aab6183e3813b1a150469436 task_036/environment/code/data/dataset/000016.jpg +edd8bbbc81a8242f587b70d4f39d06650a47794eeb5d3bea074b19d18aff023c task_036/environment/code/data/dataset/000016.txt +2944705575a7af225ba890000e02e1442ac17e66d102bf4e61bcd802678236d6 task_036/environment/code/data/dataset/000017.jpg +524ec0df2757dcd59b3cf7f77bd80af7c135608a700e115b7513fe5c7909cf32 task_036/environment/code/data/dataset/000017.txt +a8605a3f37db1700fc73b100ad83af99df0115d01100062fdae597e264359197 task_036/environment/code/data/dataset/000018.jpg +cd89fe77887fbdf7bac851164955dd6e39e6b93fb036d61f606ec94d4dab1f1f task_036/environment/code/data/dataset/000018.txt +4d1b3c260bf87d56eb5f79ad8d48cc708966001fb241516d9099d61301405b0f task_036/environment/code/data/dataset/000019.jpg +7543fae28f09d5f0520be42d83e397e3d7f7151f84af2ac2daee8f1e4eb35683 task_036/environment/code/data/dataset/000020.txt +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_036/environment/docker-compose.yaml +8160fb76438c692b1cd09b4e696d535e9a8ef0568044cfcb7ad559f9e5dbff8c task_036/instruction.md +2a89df1ab9aa9be9dae238cb0362e472ff5c8d80d32c15db020f7799746883e2 task_036/quality_notes.md +d084dce1ff83d2940e8f257f8268987573c99a0c4977e9c09d18ed3aaef0d1bc task_036/solution/README.md +1c101fbdb7797dc41ad4d1b369fb53abbd314a24a2e2c2b79d8fa8e3ebb3ce89 task_036/solution/code/dataloader_demo.py +0fccc8fe107f7b81b2af6ef3d5ded6a47549caf1c9b573b826684a86098421c2 task_036/solution/code/distributed_demo.py +d82fa2017bcef5e631e68aa903a40b278ac5ff9f918077db83acb7e1d7a25b90 task_036/solution/code/solve.py +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_036/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_036/task.toml +08788768ba8832ff4193a0e36a1f4362a3596a5ce985ba5dfa21748259153de3 task_036/task_meta.json +bb8e55ca76c26a553d1244dfcd2503a1d9fd31e063dd484ecd065fe36464bba4 task_036/tests/_offline/sitecustomize.py +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_036/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_036/tests/_shared/static_enhancer.sh +a4cb87b368bd137673adc371c601543d7666a4e5602d38441fb0f8283b3af914 task_036/tests/enhancement_cases.json +4aa559611b99a3ad5fa085c0ba629458e966d5c1c636e304e14790e71ff46ca8 task_036/tests/review_ranks.py +98ed8b8628f11a32e50db1aa1095caf969e2dbe2d690425bc60c97f2006cf7fe task_036/tests/test.sh +f4dabd84331d2d7c3295184ddab702e5f6ab92e318b520bb1953a335e3f63740 task_036/tests/validate_aaav_dynamic.js +beb8a43d682ffe67baf561c02164f70ebccddaf0f5f61710dd4c50c8a168da81 task_036/tests/validate_enhanced.py +aa5f8a9fb02b4da4eff0dc28a8910a017aea1bc3014d3b426e7865ef6277eca5 task_036/tests/validate_outputs.py +b60be349180cc556995c7b68ff0391762155f1c4f1d52440fb5a86f50dd8ae11 task_037/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_037/environment/Dockerfile +29485365a512a155607f6dc0cd385f6d3209f8b1b230307779e99b8cb4800844 task_037/environment/code/index.html +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_037/environment/docker-compose.yaml +9d4f0d61882ca3f87af046b24d0163f7bc2cce4beb70783e3a9f90df19ff58b9 task_037/instruction.md +9fbb41661beb3cc2a2aba48334a969a7be45fdca49cf83470d6cbbf9a74dde8b task_037/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_037/solution/README.md +edd191a1d0f4d496e5ea9a4950580c876e011c18a84702c8e366ae7ba38ae288 task_037/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_037/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_037/task.toml +f0af5898c180edb76edfc7e73c3bf9b5ada0d509a294481e115890aaea9dc27c task_037/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_037/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_037/tests/_shared/static_enhancer.sh +95d88d3d6c2725acf8312172bfaca7e9d00e6553affb5c4e4243697186a783b9 task_037/tests/enhancement_cases.json +abc75cba72d320a2a5843065849b26c3aa5918e865ceca889e299ce549c21c61 task_037/tests/test.sh +66d953678b8e965418a88a2cade8386ff711dc600f4452cdd24e05c42797ed67 task_037/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_037/tests/validate_browser_smoke.js +799c3ee9402318e2677e0b31068cd3e6fc74adea625aecef8ab26f1fbe37d9a7 task_037/tests/validate_enhanced_cases.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_037/tests/validate_semantics.js +01d5cb1900471dcc93bfe1e6bfdb8b3486b51cc4317dc897ecc308a823d19ad7 task_037/tests/validate_ui_behavior.js +2ddf0b21623657e4bb8b143350071c0e21d1dccb04523771f81d0ac5a9659a26 task_038/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_038/environment/Dockerfile +4fb7e5299fd06db02a91e787f7be8e8fc9c0db7b402fa6fe4a71230029b631c3 task_038/environment/code/index.html +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_038/environment/docker-compose.yaml +67c5f8130e98f5d214408069aec68af16acfdefd2e29bb5959caa7954cf17f4c task_038/instruction.md +9fbb41661beb3cc2a2aba48334a969a7be45fdca49cf83470d6cbbf9a74dde8b task_038/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_038/solution/README.md +3b38afb0ec46f2e5e6f1074e822b589672cb8dbce9e1fcef7e72ce17ac6c010f task_038/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_038/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_038/task.toml +9b33ffd30b855e57462fdfc6f025dcbdf359ef40adee75791e811303ebc72fe5 task_038/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_038/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_038/tests/_shared/static_enhancer.sh +60bb061c6a17584855f7107e4c75d43c3e673f2d01c965783494e07bbb788a09 task_038/tests/enhancement_cases.json +abc75cba72d320a2a5843065849b26c3aa5918e865ceca889e299ce549c21c61 task_038/tests/test.sh +096d36e61bebed9f18065b76adfe50be36b8cdde7f7d2a8b8cdc70d4bd4dab71 task_038/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_038/tests/validate_browser_smoke.js +2823fd008d01e76800c38ac7963fc23c6834e416826666e3e7db50ee92caad65 task_038/tests/validate_enhanced_cases.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_038/tests/validate_semantics.js +e9ee4ea3c4e385c22034ee100f506fdf6b0ab98e2b06f40e4e0108ce0e11b771 task_038/tests/validate_ui_behavior.js +14d48895e56183ba6733f22460b6f27b9de6dae2a38bd3126b486bf910217764 task_039/acceptance_checklist.json +3a724daf9e7145883ebdffb818a6dcca6d8f68dd10bd65d0301b9c1d7250b1ba task_039/environment/Dockerfile +a67f904df4f11f74a65d548a40a93d45bde90fab99d6ca0034fd1d8393753d28 task_039/environment/code/content_safety.go +8d911f4c930c513523e5e53a684bd3c69f70bf35315cd6e38839b5ab4eee2c1f task_039/environment/code/content_safety_test.go +8de735ebfe1799b53af9b3629183836af60da3f7b8b0aa77e38bffd0f6913358 task_039/environment/code/go.mod +9bfa05781dcf8cc11df2547b51432b07fe9d4649bb495c629472caa7a8c6f4e4 task_039/environment/code/sensitive_words.txt +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_039/environment/docker-compose.yaml +a43c9069bc67db7a88524cd67dd2055f9e977e8980c311c323abe4326436c7b8 task_039/instruction.md +fde8780d5985ffda07948d4a5a3e1c0273e6ce0a7d26f454e36c79527c10935f task_039/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_039/solution/README.md +ce1cdad0785b59716ae3c3d402088b318de8274dd3ee1f5eea6be1489baa9a00 task_039/solution/code/content_safety.go +8de735ebfe1799b53af9b3629183836af60da3f7b8b0aa77e38bffd0f6913358 task_039/solution/code/go.mod +3d91aaa0be67c590a0ee717d78d61ae3cffa756eb567b2d1641cdaaa2938282c task_039/solution/code/index.html +3cfb5d3fabf13aea715ae02d095de4de227033f45a55b580a45916de14ee2728 task_039/solution/code/sensitive_words.txt +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_039/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_039/task.toml +665849556b73a4f76d29d8d6986e01a3df9bf6d556735780df07dc57cc499870 task_039/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_039/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_039/tests/_shared/static_enhancer.sh +1e7ee441c0b45f9dc0903aa71ab98ea9f2c26ae44e04d5a93a7e8c185722c188 task_039/tests/enhanced_cases_test.go.fixture +44fbfec51a22569ebb41b38de8f17c248d7a27aa6fb0a1022ac8d708dcf63dd4 task_039/tests/enhancement_cases.json +6776a44072e6d6959196b2d5138df2d765dbb79c95f46ca1aca71872f1c9678e task_039/tests/test.sh +ca5be5b57c8500b7478a381295a6300e59fbf85ec5fe88892e97e9a2530b8579 task_039/tests/validate_aaav_dynamic.js +10f116e0a155434cd3b1a2c330d7b0361d28a2ae79e2aa562ec9e92da6d28630 task_039/tests/validate_enhanced_cases.sh +b46c546d41d4155c769e0fb6dfc8a0de771c581028d618e4313bda19bd5b5f7d task_040/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_040/environment/Dockerfile +2c0cf7623edafdaafa0aebf9d6d6c1bef6e13a211bae9e9cd54e76e65d05e1c0 task_040/environment/code/index.html +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_040/environment/docker-compose.yaml +56a6e2192bee3400e6453788f70f99cafd4d4a416b35ef65839d6e69e6e05e92 task_040/instruction.md +9fbb41661beb3cc2a2aba48334a969a7be45fdca49cf83470d6cbbf9a74dde8b task_040/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_040/solution/README.md +27d1c3aade843b15a5a53dc62b98b0b4e50700cf738fd455ace9e8a9be5f6367 task_040/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_040/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_040/task.toml +a5edb6bccf56f233359fd2f60523cf043489c30826fed97f95dd525250879872 task_040/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_040/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_040/tests/_shared/static_enhancer.sh +ce9188ae8b850477466f2e76580951f9af150410abd91731e2a973e87644f9be task_040/tests/enhancement_cases.json +7ecb6080e4ce8f487f061247e076357579ffe026889c9ac3c8c862d2fba23861 task_040/tests/review_hard.js +abc75cba72d320a2a5843065849b26c3aa5918e865ceca889e299ce549c21c61 task_040/tests/review_legacy.sh +16c8242cc6664be6695e47d02d71bec0487466e72cf1d72331443104304da4be task_040/tests/test.sh +61340f52e8883c4fef44d651cae32f6c6ced7e54d3b134099ba171c5a1c9c2af task_040/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_040/tests/validate_browser_smoke.js +1520ea46f7e448ae4fc809c7a06bde233a02a8993ded5c7c047469b0868f2484 task_040/tests/validate_enhanced_cases.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_040/tests/validate_semantics.js +88d5b495ee84b9df615543c02af00a02bd8d0d91dcb8d262b57be76ba15f3274 task_040/tests/validate_ui_behavior.js +35cc73c2f589b7afbf96d8babc2782986b1a3fa83b09f67657905e7bea0f37c5 task_041/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_041/environment/Dockerfile +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_041/environment/code/.gitkeep +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_041/environment/docker-compose.yaml +4184a5e4676f083700f1f758e0f8d990c58223132dd0d526987ad9a377097fe6 task_041/instruction.md +f231b1f1d0e6aad99d336a2428619024d0376c817f2d99286511e8d87889053d task_041/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_041/solution/README.md +6ed79fdc752b328fd42c37e28bac3014c1963e88e0b865fb93c8ea76150c3c10 task_041/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_041/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_041/task.toml +e75b82655436ae38bca15ef32dfb0c99b5edc7df778272be9c7403efecdfbc33 task_041/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_041/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_041/tests/_shared/static_enhancer.sh +4a174f6fac1f3062ea7c64cbaa5d451639634d9e8948b825c0fdbdbbda3c8809 task_041/tests/enhancement_cases.json +611862cc887b0b0592ba26e896bc47ebd5e1b9f011fa783cf5d4a28441279997 task_041/tests/test.sh +7f91c4004cda394543afa41cf4964292a2ed6a3d05ce8cdf5b9c8d115d6bbc5f task_041/tests/validate_aaav_dynamic.js +e0c777377ca0ecc905b9c033a15c4f3324fc3fd29eabc76bff80e2480419bce1 task_041/tests/validate_browser_smoke.js +6bd03ab01dd5c0e9be415e2791644d0609b4cfba64cc7ba08fd6917f1a47649e task_041/tests/validate_enhanced_cases.js +c03ec90084b1d1c29fac580a98081ac1b24b409e43af031e14db41c9df9fb2ba task_041/tests/validate_semantics.js +9770c6e4d63a7332ecac63c00d3c622cdff5f7d0c1d5c0dd68764316754a2eab task_042/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_042/environment/Dockerfile +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_042/environment/code/.gitkeep +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_042/environment/docker-compose.yaml +3c0bb8109b11ca97d34bbce44a93bdbf618842d6077604ff804fa37eb7e588a2 task_042/instruction.md +9b205103fdfd1976115d27beb0b53841fd563f14560c2977cfbca97c6576cae8 task_042/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_042/solution/README.md +78a02c0bf20988a664753124add3e0f306758855a67c25398712420022d6deba task_042/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_042/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_042/task.toml +84601c0163451fc0aab1c5219eecec0d287811cb0de4d00dcd07be123bfc99aa task_042/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_042/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_042/tests/_shared/static_enhancer.sh +f7149594313459113fe319151cea497a7762d64066d1e73f56c5c4f80ba6661e task_042/tests/enhancement_cases.json +611862cc887b0b0592ba26e896bc47ebd5e1b9f011fa783cf5d4a28441279997 task_042/tests/test.sh +e8a6b2e998a07ec239a398cb3dd0cdc85e589c30544991cae80911dd9531450e task_042/tests/validate_aaav_dynamic.js +e0c777377ca0ecc905b9c033a15c4f3324fc3fd29eabc76bff80e2480419bce1 task_042/tests/validate_browser_smoke.js +9814c8b5e1f8dfefda7609fca38407aff5749e2b65504d0c26789ac02ffd8a12 task_042/tests/validate_enhanced_cases.js +c03ec90084b1d1c29fac580a98081ac1b24b409e43af031e14db41c9df9fb2ba task_042/tests/validate_semantics.js +92462c1c09907c916689d49eb455dad40cca2e450c77c398a008ec997e82ae32 task_043/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_043/environment/Dockerfile +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_043/environment/code/.gitkeep +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_043/environment/docker-compose.yaml +690d7b1cc80bbed6d92089e97c321044cc129cc7f18a55d1aeb62dbd81deca20 task_043/instruction.md +9b205103fdfd1976115d27beb0b53841fd563f14560c2977cfbca97c6576cae8 task_043/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_043/solution/README.md +59fe47974f3497337d72d8c38a4d69ba353ee55b3a80c8ae01ca1408b61d1f94 task_043/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_043/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_043/task.toml +d34b6c679b077584e44d887bf09ec75ff7823f36f49e1830bfbbf0f5094835bc task_043/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_043/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_043/tests/_shared/static_enhancer.sh +b2b47872b420d4aa21e41da6cd90783c80aeb8bab25d117a533fad3ac41e2f58 task_043/tests/enhancement_cases.json +611862cc887b0b0592ba26e896bc47ebd5e1b9f011fa783cf5d4a28441279997 task_043/tests/test.sh +8cff8c0165a4aaece1113785e505298f2cce3f4f7d616e9ba0b77b5136049558 task_043/tests/validate_aaav_dynamic.js +e0c777377ca0ecc905b9c033a15c4f3324fc3fd29eabc76bff80e2480419bce1 task_043/tests/validate_browser_smoke.js +0bf8538c841dacbb1925a28f44af5a37e2a12828db05473e2004500b44a11eec task_043/tests/validate_enhanced_cases.js +c03ec90084b1d1c29fac580a98081ac1b24b409e43af031e14db41c9df9fb2ba task_043/tests/validate_semantics.js +c06457fbfee170320e47a979cd0611b6fe681ec7d0104dd45ea667ad9b5f80ba task_044/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_044/environment/Dockerfile +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_044/environment/code/.gitkeep +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_044/environment/docker-compose.yaml +a8af4a347f4e19ac2a0d1bb554737df75f81c4502889d7f0bdb7205a47a7762c task_044/instruction.md +9b205103fdfd1976115d27beb0b53841fd563f14560c2977cfbca97c6576cae8 task_044/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_044/solution/README.md +8d9808dc952c056a5f2df8215e51d3b4512536191bd3fad67ad25dc6ec147bbd task_044/solution/code/aquarium.svg +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_044/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_044/task.toml +046e652cb900604c620e8986439f78f6fb726ccbaf1794d0f9600982a9179a22 task_044/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_044/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_044/tests/_shared/static_enhancer.sh +fe8156d6458df1fa99473716627d0ff4c72e1cef3485395c7d49df105ffd32cb task_044/tests/enhancement_cases.json +611862cc887b0b0592ba26e896bc47ebd5e1b9f011fa783cf5d4a28441279997 task_044/tests/test.sh +f024c9b32511614310de6b8fe746f8b5369566b30a237f41df198dee662cc9d3 task_044/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_044/tests/validate_browser_smoke.js +13747cdd08d56b5e06965aacae367d6434773ed2eedd9bf3b48ce885df8f5177 task_044/tests/validate_enhanced_cases.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_044/tests/validate_semantics.js +e6f1a0632c729057cbe6052b7672d98b2d9b0262b93989c0d2d3bd8449edf4e8 task_045/acceptance_checklist.json +0d1cdb9bbc77e72e4f8a7c6cec8640061d8c246c86e9e9c65ecbbefa861a8f17 task_045/environment/Dockerfile +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_045/environment/code/.gitkeep +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_045/environment/docker-compose.yaml +6f14ef62742367a8993e87221a34e450217d1d4dc9bf76b3e407b9b086fee557 task_045/instruction.md +9b205103fdfd1976115d27beb0b53841fd563f14560c2977cfbca97c6576cae8 task_045/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_045/solution/README.md +dbdc576f250d1afffb835479b422cb178bff3dc86ec1945cdb509d7e7e7ea12e task_045/solution/code/hospital_flow.svg +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_045/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_045/task.toml +51eb4017182c9c92844860270e7351376158929e04188724027569d7dea5f342 task_045/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_045/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_045/tests/_shared/static_enhancer.sh +5967b9f6ebf07ddbc274cea094c56761296315a78d52eef3c9a2831574ed20e3 task_045/tests/enhancement_cases.json +611862cc887b0b0592ba26e896bc47ebd5e1b9f011fa783cf5d4a28441279997 task_045/tests/test.sh +a830235ad64c022757ebea1cc73a06c6c68c322225ec8737b8bf6f6fd11f6a3f task_045/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_045/tests/validate_browser_smoke.js +8a3f6bd904d34b8e1e2dfe8772d732d8931cddb2565711b988f4c6b250e31703 task_045/tests/validate_enhanced_cases.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_045/tests/validate_semantics.js +c9f03d5bcc1a99633b18cf3e6d47c6a803c87561981443263601c8812dbda248 task_046/acceptance_checklist.json +3a724daf9e7145883ebdffb818a6dcca6d8f68dd10bd65d0301b9c1d7250b1ba task_046/environment/Dockerfile +099d4ef7d7ef3ce236e9f00f1c54e493e4cbdb3eb735b45dcb3fbf8cacad1ad9 task_046/environment/code/go.mod +17b5c996b9bca69f3ea9a29318930801c2a7e3d7dd5d96c6562140eca0a83c44 task_046/environment/code/promotion.go +05324a6b67e6f6ed4cde2f5cd3471f37f0a3759baa7a11bc1e1d705b524106eb task_046/environment/code/promotion_test.go +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_046/environment/docker-compose.yaml +cf27c6212cb7c277f92894438a1e7b712e819a4561fa416b4fbca264350d435c task_046/instruction.md +9fbb41661beb3cc2a2aba48334a969a7be45fdca49cf83470d6cbbf9a74dde8b task_046/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_046/solution/README.md +099d4ef7d7ef3ce236e9f00f1c54e493e4cbdb3eb735b45dcb3fbf8cacad1ad9 task_046/solution/code/go.mod +5bdbe1b7a81dbb255e5f5ac3327c1f855ce15a2ba6cca1a8a24020614eb19991 task_046/solution/code/promotion.go +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_046/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_046/task.toml +63e0fc3eaa4ca1c417719aa07c069e1e1183ca300e155deeb1453b00825bc09b task_046/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_046/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_046/tests/_shared/static_enhancer.sh +b5afa0fe16801d3b9103b5a83e5622d037c26fa320c3f54285981b6ad88468fb task_046/tests/enhancement_cases.json +310300e57c1554f9bcb00051aca21a2dbe56245383568a0bc3d8240b604955fb task_046/tests/test.sh +01ffbe253f047b5db03f4f7b4b90360457f10d9ba9abdb1f23a1815604e16138 task_046/tests/validate_aaav_dynamic.js +241a0ea40c80c42202957d550037e872e8c515254689b3ada86dbfb14517f049 task_046/tests/validate_enhanced_cases.sh +c27adf2c392f0516c5ad1571b8919841a4803286ecd189d4ec654ee85c82a929 task_047/acceptance_checklist.json +3a724daf9e7145883ebdffb818a6dcca6d8f68dd10bd65d0301b9c1d7250b1ba task_047/environment/Dockerfile +72b47c186ab17d94c63d261561e9ed14f4303e662bd138245779d8d7eea6a8ca task_047/environment/code/go.mod +061ef388497752c5d00e7187e7ce3ca9ca84b042b874ebe7de02d0a0994b0d09 task_047/environment/code/log_analyzer.go +a5bcb7c97991822089ca09bcbe8c2476c0f6d8c80f02198f872bdee6e3c96ddb task_047/environment/code/log_analyzer_test.go +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_047/environment/docker-compose.yaml +b2a8f7c5ff1669bbc29fe9d8d9aa9d9f09e63bf867ea68bc2681a0d15a024459 task_047/instruction.md +9fbb41661beb3cc2a2aba48334a969a7be45fdca49cf83470d6cbbf9a74dde8b task_047/quality_notes.md +107fffff586faaba6357be8a9fc6c730232201e78b8fa90f758f1b88cb241387 task_047/solution/README.md +f75ce3441f71d8188359dedfef09f0a488baad7cdc9e221f57b62cbcb1836d6b task_047/solution/code/cmd/server/main.go +72b47c186ab17d94c63d261561e9ed14f4303e662bd138245779d8d7eea6a8ca task_047/solution/code/go.mod +a88c7079f9997b3926e93d44418101539b673402f802613dd2bd10d1d308c53f task_047/solution/code/log_analyzer.go +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_047/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_047/task.toml +ba77e0348961dff1dd3d363482736dded09f2c35d9fde3e2b69f40a9e0169777 task_047/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_047/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_047/tests/_shared/static_enhancer.sh +8c92c7f1b73cc3515952fbe7fa1b35112bdb6028e8637d4fe4f75517dddd010e task_047/tests/enhancement_cases.json +bf875b3c22f308f3f2b2a08fcb0467a0838eebf12db5e05643802e4c763829d8 task_047/tests/review_server_test.go +8d29969cb2fa3ca7c9525ff64c60019dcff35c434abc24ae6e7c72c1eaf49c83 task_047/tests/test.sh +ca5d024bdb063c6d3cc9a30680ec286b14b4676054303a061ee1c89e56b3103f task_047/tests/validate_aaav_dynamic.js +4131c8185a9eaf9b4d473c1851ad7c99db16e93d9d4451c73241e79b3103e6fe task_047/tests/validate_enhanced_cases.sh +94df7ae8b65a5d4b07e390cb1f35794851fe355b25aea906898395b1da39f8a9 task_048/acceptance_checklist.json +fc9e4c7641973f8936f3c9dbd988bbb78be66621f55c8177a1e09a4d16b70021 task_048/environment/Dockerfile +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_048/environment/code/.gitkeep +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_048/environment/docker-compose.yaml +1407d6dcfe07cd2005b9355073678b39696e5ac06cca0d22446afcca20484976 task_048/instruction.md +7df3b4a7ab0a689d24a4eac3fc1822a0063ff4e63ef3948498de8eb4a942989a task_048/quality_notes.md +c717bec04b464adb106c70544d1a83d9cf93c8c752eac336accbd6f56b6c0c2f task_048/solution/README.md +0e6b5206dd5bd9a752b645fd58486902b912ee1854b8f22c23ce2db7309394a4 task_048/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_048/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_048/task.toml +8f963dbafbd24fc98f657b701d50d096a0dd09a9088227f5ba642163675afd17 task_048/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_048/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_048/tests/_shared/static_enhancer.sh +9c87964aed239b67ea515571f2da10405b11edffd58825d29cd8e84493dda001 task_048/tests/enhancement_cases.json +7ddb895ba6fd4c7aeb91ddc4b66a84edbdd38a585c92e1d1e3c444c90fdc5972 task_048/tests/test.sh +e69844abf879536238cf527746e5a81cd43b80250192bcfe6f967b06bc8ea24d task_048/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_048/tests/validate_browser_smoke.js +9f9dbc4a9d15124f1f9d9f871f317e15f21ff02a5ea64ba2dbc9a703ae94a3d3 task_048/tests/validate_enhanced_cases.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_048/tests/validate_semantics.js +e5350698e5ae9564140c4b48e9009104d0887ff26161a1a55650d9df709ee562 task_048/tests/validate_ui_behavior.js +6c4052fb5d88a120de01b7cb2f669abe6af4577afc2d7e0c4bb131dfc01414c8 task_049/acceptance_checklist.json +fc9e4c7641973f8936f3c9dbd988bbb78be66621f55c8177a1e09a4d16b70021 task_049/environment/Dockerfile +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_049/environment/code/.gitkeep +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_049/environment/docker-compose.yaml +47bcd32e2c91cd54dd6307640fa6fec3d012aabdafe2a18a432a1854df74021d task_049/instruction.md +aae641bd97de607a905e8309e349f9cbc162b096ca0fe276b78dbaeac9851ec5 task_049/quality_notes.md +f406a6581c3fb98a1d921b6961fe9fcc1d58f25e427bf3ac33c8208d167280fe task_049/solution/README.md +c3cff444155786fe122dd702adbae38ad1901cd8ef4f874eaa701aedb9a6736b task_049/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_049/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_049/task.toml +6edcc7313d23ed355c5c6421be5562fdd618f2df99e84ec0b75077fc807cf2d2 task_049/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_049/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_049/tests/_shared/static_enhancer.sh +4b10058e141a5d46f8bfb47b6e6663de0760800e3d6744b6d7af88d261c05215 task_049/tests/enhancement_cases.json +7ddb895ba6fd4c7aeb91ddc4b66a84edbdd38a585c92e1d1e3c444c90fdc5972 task_049/tests/test.sh +51d2530f322cdccc6b507c8c6e2620df88852be54b3abde3416af67174dfb5a8 task_049/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_049/tests/validate_browser_smoke.js +748487cf8754854ac13b2b901e117bc201477bb4f3f89ca7e37ef4842a28e788 task_049/tests/validate_enhanced_cases.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_049/tests/validate_semantics.js +71bd2260729ec3435222e7e408aa827a66365189099202511a8b06acf877d8cd task_049/tests/validate_ui_behavior.js +b3bef8e5fe37b8687016d371a6fdfbd2ced62fcb18ad0a7e970c851e64a20571 task_050/acceptance_checklist.json +fc9e4c7641973f8936f3c9dbd988bbb78be66621f55c8177a1e09a4d16b70021 task_050/environment/Dockerfile +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_050/environment/code/.gitkeep +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_050/environment/docker-compose.yaml +c78b79efcdfcb08ad4cedd5f522cd65f16b7fba274d7bd95c819ec1313730ee4 task_050/instruction.md +8d10888764c2fe73ea4728c0ed7891bd765845b67930aa6c61ab8d4df2499026 task_050/quality_notes.md +a83b294b0a5a75d338352693e487020cced03d98cc7595be4c2cfc4d2903a605 task_050/solution/README.md +294fd20748d15843cb25859283e597f0e54aa4773d869dda38091f3184f6bbd4 task_050/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_050/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_050/task.toml +edcc9db5ddcc72ae075c867a90c62504a51fae307a464a282c59e740a27531df task_050/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_050/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_050/tests/_shared/static_enhancer.sh +4e8ce0df81bc8d6749ded63fa3f6aee3c3bd6427dde596385c6ac57a045d0cd1 task_050/tests/enhancement_cases.json +b95f49511bc50e65f007ec1ea8280aad64e71364b9a7e48a4a99d6156d319dc3 task_050/tests/test.sh +ee39ce9a8883f3329dd17cbd5783c45c3e4e262eda9619684f825fdf614f10b3 task_050/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_050/tests/validate_browser_smoke.js +2ec65768068e936c884f9b672cc7898d4c438744b4bbc64ba39b06e303546bd0 task_050/tests/validate_enhanced_cases.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_050/tests/validate_semantics.js +f3f24299060402acb56d5d834ccb35e6ff88288ff2a5e8e124ada2579643c4f5 task_050/tests/validate_ui_behavior.js +96fc6e6c1a9a76b5c7ff45670d7b6e8aca4171229cad9b34d74a224fe2931b9d task_051/acceptance_checklist.json +bd47a18f7cf045ee0c8bebc38ac7034dbe67b03a7b35958817d7f628d143c2f0 task_051/environment/Dockerfile +416e12a8aa14253331a2770f3aef8cfc41bd4486a7943a1c79b5d817a4f6b3ba task_051/environment/code/.env.example +e9318d86b624c0e5cf4a15bb610f402a1498c1595dab20fc1c3fd64170d411c1 task_051/environment/code/README.md +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_051/environment/docker-compose.yaml +403f12f18284ace3c1313de9bef458b025e54221db73db91d6ee89707c4f52be task_051/instruction.md +014e6118836186208fc7d77aa5dda269c23e5f498ce5b5a0c3585ca0bc602108 task_051/quality_notes.md +c4ab11664a7694ea6fbd131a8315d00e67a3621dadcd0fffa1568661c6921980 task_051/solution/README.md +416e12a8aa14253331a2770f3aef8cfc41bd4486a7943a1c79b5d817a4f6b3ba task_051/solution/code/.env.example +c6aff57a744d12b5f96eb720f76853021d43033e2eb11bb296426632685ae664 task_051/solution/code/validate_env.py +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_051/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_051/task.toml +2b521262133373cb91038d1d240381606a5f5f026483212127aeec10171ea2c4 task_051/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_051/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_051/tests/_shared/static_enhancer.sh +a6ae6218d6e6a5d3fe5800d74dd3bd5c7d5c4ce7fb043b5f46c471e931a6df74 task_051/tests/enhancement_cases.json +d7d8bc5c3ed5d8501c030f982637528824c4f1429e540dd0aa2b01a9bc0929a8 task_051/tests/review_hard.py +ecee225062c06c3b6ac7d45d9f35989e0285c37250dfeefc95e9a7c65695b43d task_051/tests/review_legacy.sh +939c60cf5c1fc2d773b9669644ddf8e8a978aa5dceb194e64da33e6b5510c40b task_051/tests/test.sh +d1a12c9b569741277a314f46eb7e9d8c7110160c49d124dab5b54d7485cafdba task_051/tests/validate_aaav_dynamic.js +ae5bd93176670d80012f63a3d32bc65a2a648c2d48c6d70382354ae27fd4ad20 task_051/tests/validate_enhanced.py +51a13f4e624e25961414ddbe1be097d397be68a9d82c23b101cf2c7353f9379c task_051/tests/validate_outputs.py +8d93ce542bdf14f8902e622153051c102373b391d15555cf37140b43d7df887d task_052/acceptance_checklist.json +bd47a18f7cf045ee0c8bebc38ac7034dbe67b03a7b35958817d7f628d143c2f0 task_052/environment/Dockerfile +9cd85af9d0500ecc9ee1cc32b4ee8a43713e2ddf12f7800de3770abe89c5ff16 task_052/environment/code/README.md +6803388f943eb077522725f9256aca98954cf84a271f084fde9a28eb0b6fe8d3 task_052/environment/code/logs/app.log.1 +d0a6fa1314c1a3fa93a26617a6c109b638cf8d66db364975e72e99364132c75a task_052/environment/code/logs/app.log.2 +deae431233402e9d48cf668e2acc2bfd3827a31781bbe2783507724012339bc9 task_052/environment/code/logs/app.log.3 +199b8026396602cedecf376c3f4bdb5ae58f4aa8543f39b6a23c7aee85d93c5d task_052/environment/code/logs/app.log.4 +35cff1a9f4d39a5a5286219615a6381704414d5f15668f071df53cc32a995f6f task_052/environment/code/logs/app.log.5 +00b5f7dd15e07b08659bd48ae55e7e6bd8c5ac475bc7cf56ae796e1ef994af87 task_052/environment/code/logs/app.log.6 +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_052/environment/docker-compose.yaml +95e8a5a64c3979ea9131150de496f142a07b774526735a1f99b0fa91a0a643e5 task_052/instruction.md +63ce51e89bf7ed9a5f5feac18eae30956008ab121b574a5c38d49d1006343784 task_052/quality_notes.md +8e7a64e2b85080cd0890bc7cf8640c4c15a6e57451d3b356ee21109eed042860 task_052/solution/README.md +2639d66a82d430f41d5793954405d13fd84fafcaafd89f6d1f03d5dd817346c7 task_052/solution/code/rotate.py +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_052/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_052/task.toml +e38fd93b2d02e45e74f80b7de93bd51121a00d3ca291d30355592232c2dbe90b task_052/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_052/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_052/tests/_shared/static_enhancer.sh +f480b1ae5e0410d368d3c1483fbb0cb9fbd528d38861b238b5db80e23fc4ec3a task_052/tests/enhancement_cases.json +cff915d02d21bdf47f93c22ee4996e186d57f6f4cb0056cd1f032f0f3d7558bb task_052/tests/review_hard.py +c5f9e866816aeeb1a9755eea75a9a5433e7fed77540bb1ef8c6532bd49b5bd7e task_052/tests/review_legacy.sh +939c60cf5c1fc2d773b9669644ddf8e8a978aa5dceb194e64da33e6b5510c40b task_052/tests/test.sh +7b94862a50c16a9dea78d37526b624d6e17e343799e2116a859407e61aba3d5b task_052/tests/validate_aaav_dynamic.js +879189645b798e70e44f2106ec624f1c05448d7dc7a2b33e028a54f0d72a6b67 task_052/tests/validate_enhanced.py +81d0f788a11d090b4db6f90c61c9e0496bd38b1b0079b25a78d19d1a13f2d993 task_052/tests/validate_outputs.py +3049b2de17a781406fe65e8c019154216ee33f95dee09414e97f978bd6390f34 task_053/acceptance_checklist.json +bd47a18f7cf045ee0c8bebc38ac7034dbe67b03a7b35958817d7f628d143c2f0 task_053/environment/Dockerfile +88322a0fbab0ff58ed5243bac5eb8423e0e7fa132e9c514b4970b0ce3f6651b6 task_053/environment/code/README.md +c28fcca53637bc88e124af1725df13cb98c69dedefd62fb3cdbe1cdb6b760624 task_053/environment/code/current.txt +593f576e7e5bb8e1b1d64f67f6d7fe99c6615a39c12e1751e6a3b0211f2866b4 task_053/environment/code/releases.json +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_053/environment/docker-compose.yaml +4de50ab5c3b9f6b5075358b9f07a83a9880d32d93a429f24e7693d7ada0ffd4e task_053/instruction.md +d546da56fe375f887738dc123c491d956bc565fac6bed7060bf16675821c1a64 task_053/quality_notes.md +be3e13981b61cf076f6323a42d5b94f70231c10d7080020168924281c8a5894c task_053/solution/README.md +c28fcca53637bc88e124af1725df13cb98c69dedefd62fb3cdbe1cdb6b760624 task_053/solution/code/current.txt +593f576e7e5bb8e1b1d64f67f6d7fe99c6615a39c12e1751e6a3b0211f2866b4 task_053/solution/code/releases.json +b7e3021bbf94fa5121fa69f33a63464c665ce220e45b3609202086945141e9fb task_053/solution/code/rollback.py +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_053/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_053/task.toml +0031dc29d7d923fffb138ff88b4c04c5f39597350ffadd637cd759df21e4b95b task_053/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_053/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_053/tests/_shared/static_enhancer.sh +9b9b03b514702551230b63d1c15eeffdaa271e6e3c11ffb8db0dbeb03fd4d448 task_053/tests/enhancement_cases.json +f55f92dc9ca74edd05c2562a8679e8f007e5b8034451e91d00a77b64cedb35cf task_053/tests/review_hard.py +520db7e7cc6c515e2d2cc0f466e8d22fcd4ccdd9f8011850c897c8af4717a66c task_053/tests/review_legacy.sh +939c60cf5c1fc2d773b9669644ddf8e8a978aa5dceb194e64da33e6b5510c40b task_053/tests/test.sh +bb6541084d34c3d2f9bf8c9d8ed72fbbe03b58d4bfbde3927458ee57aee1f8f1 task_053/tests/validate_aaav_dynamic.js +2233645b2f7ea4f0b2ebc8bd4b16877be564f57a63551028a7f8117db786370a task_053/tests/validate_enhanced.py +b4cf53ed9bf10bd9788f076fe9c644868bddb20fd8791758b3e051eb5a0fd2bd task_053/tests/validate_outputs.py +7f71ee24924c4848d323f9f6f4bf9944289d5c7f2f508d596eed63d2a7b908fc task_054/acceptance_checklist.json +bd47a18f7cf045ee0c8bebc38ac7034dbe67b03a7b35958817d7f628d143c2f0 task_054/environment/Dockerfile +642844e756317b7cbfa7983efdff8a0514894199664bea5d83f63861d0bbf13f task_054/environment/code/README.md +41909153fdd1643f4a97f80a9867a00e56ca0800493a728d3a147de6012d3ef8 task_054/environment/code/mathkit/__init__.py +fcc6d07e600488f6f39627271cc245ceeea62dee190946ddd26c527f12b09e33 task_054/environment/code/mathkit/ops.py +c1d05961e1fb1f98767369649a699df86d86a84b47feec3aeaa33bb71a1db7ef task_054/environment/code/pyproject.toml +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_054/environment/docker-compose.yaml +c77f4debd7ee778b0ccfad8a6443dad2085c3c84dd4365534d3704cfb9b20324 task_054/instruction.md +39b53cb546a20095f57863e2b8ce3ac75e3a25c02ad1bacb742c80147779e5d5 task_054/quality_notes.md +71ff17df622416143eb948fcc00252d1cff7e78b2078553a17308c78fe10b7a7 task_054/solution/README.md +69e82429c47f9f82a2da6273d7e02f19916388c44fa0dfd86e7ff19311322408 task_054/solution/code/build_wheel.py +41909153fdd1643f4a97f80a9867a00e56ca0800493a728d3a147de6012d3ef8 task_054/solution/code/mathkit/__init__.py +fcc6d07e600488f6f39627271cc245ceeea62dee190946ddd26c527f12b09e33 task_054/solution/code/mathkit/ops.py +c1d05961e1fb1f98767369649a699df86d86a84b47feec3aeaa33bb71a1db7ef task_054/solution/code/pyproject.toml +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_054/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_054/task.toml +563b789bffe42debd5d2e37ee5ee8dd56a83b74803ff775af442246563f9aa0a task_054/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_054/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_054/tests/_shared/static_enhancer.sh +008ea3d9e649bdd2e8b624328ede0b3c29a30bd23545da0a7b93176d6ee3a628 task_054/tests/enhancement_cases.json +e9a907303a3007a2a69d5f45aec03997bde778a4a20fa91dd0e0b3b60aee46e0 task_054/tests/test.sh +22c02f844dbb50bc249ba7cbc22fd5145b5e06b19a5f762d4af66b9c83e2bbb6 task_054/tests/validate_aaav_dynamic.js +833f0d4c08151a3528c06c5b7c36b9b6c362d898a2ac58008953a19ff5d436e6 task_054/tests/validate_enhanced.py +3a0f61cea66f7f75a6cd3194db6b5cfaa8616786f2b9af09c61429093da3d8c5 task_054/tests/validate_outputs.py +3f2afa4b27ad4ee77bb731985252418063a87aa970462915e4a2e615a91976d7 task_055/acceptance_checklist.json +bd47a18f7cf045ee0c8bebc38ac7034dbe67b03a7b35958817d7f628d143c2f0 task_055/environment/Dockerfile +a2ff07988a1f918519600d9fb27162318ecfe8d3043a008df479f3814aa28d8c task_055/environment/code/README.md +c1c20d3d663ef3896a74a346e3033781393de267c3695170722f1219816e2e56 task_055/environment/code/data/orders.csv +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_055/environment/docker-compose.yaml +b73b712eb7d171eac6c7b0cd2980410c2ec64e40810bab5be1cd8722d0d5c5c8 task_055/instruction.md +c298f04a95e47ae59ed71c2736ee2cc5baf70fb162210e7221ce5bb941789f6d task_055/quality_notes.md +6f6870823e7e3d1d260f370bc71cbebec3beccd86b39ef527727571a9175235e task_055/solution/README.md +dea8931f63811490ecf104c93f076f94de1bf08fa8090b10154d36c45876bffa task_055/solution/code/cohort.py +c1c20d3d663ef3896a74a346e3033781393de267c3695170722f1219816e2e56 task_055/solution/code/data/orders.csv +199f7e89c130aa7ac7d611ed3aaf3e138163e310abc5b96e5bc10cabd3ba225b task_055/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_055/task.toml +83113278de5eef1283f1e282105b89d81efa20e327b04a65957cce21bc1ceadb task_055/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_055/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_055/tests/_shared/static_enhancer.sh +b7e9208c70ad8d74d8a58e271558c038498f24821b0a401b5cf96c649c25254e task_055/tests/enhancement_cases.json +2affbcdbed3edbcead0d5bb3d24fef3f88b11d5e339bbbd86c929852e1713fa3 task_055/tests/test.sh +be04680cdc73c822994abbc800ef93e2183ea8f3d7e61751cc6865396881349c task_055/tests/validate_aaav_dynamic.js +3fbeab73cff981b388a7be8541c456b31bc73ce1c4f5e30a944602e396063c45 task_055/tests/validate_enhanced.py +15eec2ab1889bc88909f67b9121e05ef388c8a8db6bad10a751934e7e12393be task_055/tests/validate_outputs.py +0e572a758983df92c16d302ecc574e279dc719242d1ed04e5e97be4c7392b3f4 task_056/acceptance_checklist.json +bd47a18f7cf045ee0c8bebc38ac7034dbe67b03a7b35958817d7f628d143c2f0 task_056/environment/Dockerfile +d3141d057eecd90a2cae2f253887b790f12b1d14880da3dcbceb92aa34bce0a2 task_056/environment/code/README.md +8efdfe7bb162a92baa14a57853d0e7c025738d0324a412aad0434417078fba64 task_056/environment/code/data/loans.csv +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_056/environment/docker-compose.yaml +3a5f77a850bb64383901f0b086bd90b397bc13734681dced42014c5da8e42b2c task_056/instruction.md +dfdb51bf763bf24db481b8c001aeb7d5219ed818be66093d015deddadfb17a0f task_056/quality_notes.md +bbc8f1b739d77b2cdad76af2cfcfddb3a5d5653e39adb85086eb55ddebcb3959 task_056/solution/README.md +8efdfe7bb162a92baa14a57853d0e7c025738d0324a412aad0434417078fba64 task_056/solution/code/data/loans.csv +9303f11744ddd3f6e38840380cc3bbb059c974a1a5a2592b4e8284908a8ffd18 task_056/solution/code/vintage.py +c42e1d8ba8f602d868593266f6fd9ec7d5e1be015326f66d8433ca785b6cf13f task_056/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_056/task.toml +6c4f1973eff917f8814c5709c8f9cf08f109bb431ec00a2aea2c3ea3ac0f2bfc task_056/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_056/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_056/tests/_shared/static_enhancer.sh +5aa54160722a63352612aef06ed3cf31e2f0c88db461c86eb146e3a3ff7ea742 task_056/tests/enhancement_cases.json +a53f657b9cd794ead1f824c958da07512ee8401540df8f9b9a4dace3b851381f task_056/tests/test.sh +5230544b5665592fd398441aaf511b85b3daa4db6bcab024f020669acebc807b task_056/tests/validate_aaav_dynamic.js +c3bfd0deb993769debd34cac95a9870cebde5110065d0453c5aaf20b58ef0618 task_056/tests/validate_enhanced.py +97974e93e2007d3b607f20f5e71f772ae8b1de1665d5f52894334fefed6d00ec task_056/tests/validate_outputs.py +6faad27fd2069a262516ad3b9b3908c3c7d7d66f8c080dafa0971b22be971e07 task_057/acceptance_checklist.json +d4a8b51b5a3b88d47f2e3f5ed96f0853851bc4efda0425f186f9ebd963328d89 task_057/environment/Dockerfile +5f4d2ff876a1e852c387fde8529676c6534bb1b475761d8871cf6c61f482fdf2 task_057/environment/code/README.md +f667d407fe949bb9ef08b1032db82ba85c9b2fb6e82eb591d2574f3d76e80694 task_057/environment/code/data/housing_test.csv +431db849d8c862244386b347c82423390d9a0b82f9be7da85fc1283c41cb5db6 task_057/environment/code/data/housing_train.csv +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_057/environment/docker-compose.yaml +ad992eb92bfd123b1ebaaea7dedb58aa032220848905d3e7ea5fbf8eadef44ac task_057/instruction.md +3c5d890fc64d463c89c377c2a50e844155c672e0271ed8b5ce0767ef9d2b5647 task_057/quality_notes.md +55f3395279ab9ba7df174c0ec95b3798ea1a9386e4a21c43e008608bafbe4aa9 task_057/solution/README.md +f667d407fe949bb9ef08b1032db82ba85c9b2fb6e82eb591d2574f3d76e80694 task_057/solution/code/data/housing_test.csv +431db849d8c862244386b347c82423390d9a0b82f9be7da85fc1283c41cb5db6 task_057/solution/code/data/housing_train.csv +87aab66261700b01dcb0d13c5cc38412d09632c72cbdd63f7b45a5d0a8d4fe02 task_057/solution/code/ridge.py +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_057/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_057/task.toml +c89377c09edb7877e320466ba99537eacbd850248bd0c7a0adc9f5cfb64bf02a task_057/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_057/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_057/tests/_shared/static_enhancer.sh +2a44616c3318d5c800e727d13d8f4c7763213a8577b5bc2d60a08a59163699b4 task_057/tests/_shared/variant_runner.py +cc95ea599c4f9ea4d84a69f3ab36910a3ebcfea5d66178928994a8fb64810af2 task_057/tests/enhancement_cases.json +9ef465806936067246a8410ade621e019d1be3c0f25efc1a7b475270bd0d114c task_057/tests/housing_test_labels.csv +48a44c35cb1bc719b6f16fb66338dcfca3946d68f054de189cfc28d24465ef91 task_057/tests/test.sh +13ca2f16fa7f921effcff1d0870169a776e0902aa735e566ac159f1a5ef11a9c task_057/tests/validate_aaav_dynamic.js +ce25dad5a7f9178cd10d0adb590decfd2e9730dee59bb7263b86b56d2fddca00 task_057/tests/validate_enhanced.py +672e735d918da579462b1ec4fc284ea77d66c7a063796762c5da94fdede5b3e5 task_057/tests/validate_outputs.py +a85d042f0c0e2b5a088189225f3a791a983b46507895f69ed935276c42019daa task_058/acceptance_checklist.json +bd47a18f7cf045ee0c8bebc38ac7034dbe67b03a7b35958817d7f628d143c2f0 task_058/environment/Dockerfile +7e36c67a0395cf10fd95a4506261c5ff021bbb4387b1db732af67606ede3e894 task_058/environment/code/README.md +04e2efaf2999a374117797e952898a8916b5e7d0c966af84258076d73f3a0917 task_058/environment/code/data/test/img_000.ppm +9c9de33bf407904a6decd12d5d6b57082ebfd03ee4a7eabe26397440b9648753 task_058/environment/code/data/test/img_001.ppm +343e9a87449da0b3a9e4e279cb932102029de7b4466185399c9f939dc63a6e54 task_058/environment/code/data/test/img_002.ppm +050de1e2a5a949f4ef4e3d01207fa9e3fcd2ae6261fc181dc6f36e0c69a13241 task_058/environment/code/data/test/img_003.ppm +e497495863fbc445b10851e9e686cd8e29eb80e19b3a302096eef8ce80722cd6 task_058/environment/code/data/test/img_004.ppm +eee4609701c22af031ce769e28195747bf53b773d35d7e414e7666a3761ed3f3 task_058/environment/code/data/test/img_005.ppm +2f244ff9f764327a8413f9a00e686c4dea01b82610cce5a8250df1c7c0762a68 task_058/environment/code/data/test/img_006.ppm +feee8a8632db653466f756c231008c51b1a39ba92b938bf64b0f978a944565d3 task_058/environment/code/data/test/img_007.ppm +9b23d7c988edd23647165143107e52698fe1dd8e2cd665ac5fa3033ea0be6425 task_058/environment/code/data/test/img_008.ppm +171984fec0a5852f21843b0e18bf6d338537c4b7a3957b5ebff3b00bf1d97fd6 task_058/environment/code/data/test/img_009.ppm +82b1806f4172cbf3d71b113b7561ebcb24f29bd8ab2b5797181df7fcb18e43db task_058/environment/code/data/test/img_010.ppm +a3814b988e8e52b3b21a167f553487fe5d7e5e589a0e16446e00aa514aa59f29 task_058/environment/code/data/test/img_011.ppm +9ed0a0c1c31e50152b09e2233eaef432017a38b89ffa42be8b98c706c01c2549 task_058/environment/code/data/train/blue_00.ppm +0e54e8d222cb00d2982dfb50a0ae0529c7edcb9413b799ead948a149253df1bf task_058/environment/code/data/train/blue_01.ppm +5fda65267b69c530851d40deb0755fcc8b23909f6cb1566470ed483825fefdf4 task_058/environment/code/data/train/blue_02.ppm +fd559d62ac34f42265574cd1c01a16781c8b5c3afe14e641b3b2fdaa237e1020 task_058/environment/code/data/train/blue_03.ppm +b947c330edefaf336eaec2f73afa319ec7de6ff17d9d81433825bbb4fe380549 task_058/environment/code/data/train/blue_04.ppm +b140f4d49df1f8857a8991241b877b8ab5d1d5b68dfab97dc04e10c82f4f4148 task_058/environment/code/data/train/green_00.ppm +9b59db53aacbf41681071f2f8521a359d8bec34ed1c9424ea04759ab6f4a9833 task_058/environment/code/data/train/green_01.ppm +0e4ea0dc3057af6df979f1c4bc2586f0060dcd7655b9e4e3b6c54e99c59ef10b task_058/environment/code/data/train/green_02.ppm +fedbc243d7ea14f7f25793136cce3297689a2288da58491fba480326408b6ac0 task_058/environment/code/data/train/green_03.ppm +c3d3abc1b6b91f2aea1fb73749ef8b86552cdb5b7bb47595381d5799e6f03b8a task_058/environment/code/data/train/green_04.ppm +cf5e632c00f6afbaf95fcc953fd09790c59b576226c10f5c8ce1eb7bd709a1e1 task_058/environment/code/data/train/red_00.ppm +67ffea61af84d17fcfd1ff5af9643d88b0fd0fa1a84884c6141c81bd7de72083 task_058/environment/code/data/train/red_01.ppm +42cb8d99f73ff9fc9ac0ba55a500a6d81221d3b53051f3b96cf6add7bd6fbb1d task_058/environment/code/data/train/red_02.ppm +d5f5107862488fa874e24b782244e85843cddc583b668432c8fb9842bd08d475 task_058/environment/code/data/train/red_03.ppm +f3ea9ce82e96edd0dc30e8b92b183e73db6bf57b1e08b3b5df85f01a648225bf task_058/environment/code/data/train/red_04.ppm +681352b4a1787a69013b294cdcfb351bbc95e93f3009a3aa1fb6eecfd0a619c2 task_058/environment/code/data/train_labels.csv +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_058/environment/docker-compose.yaml +7f6956e07cd0a8af2d60bd69e3eee934fe572ac2d6c30e6315a0c3c85ba12c84 task_058/instruction.md +07bd299e608eccbbc74be004e650ee8d395fb99a97d07afcd11aebabca985209 task_058/quality_notes.md +1e9934a2e23914cd8d858cd1122caf1000886ba59250310cae02d0821da64bac task_058/solution/README.md +e8ebee2ce74611371c0cf9dad55db462252436c90486605bb882449cdfce1f20 task_058/solution/code/classify.py +04e2efaf2999a374117797e952898a8916b5e7d0c966af84258076d73f3a0917 task_058/solution/code/data/test/img_000.ppm +9c9de33bf407904a6decd12d5d6b57082ebfd03ee4a7eabe26397440b9648753 task_058/solution/code/data/test/img_001.ppm +343e9a87449da0b3a9e4e279cb932102029de7b4466185399c9f939dc63a6e54 task_058/solution/code/data/test/img_002.ppm +050de1e2a5a949f4ef4e3d01207fa9e3fcd2ae6261fc181dc6f36e0c69a13241 task_058/solution/code/data/test/img_003.ppm +e497495863fbc445b10851e9e686cd8e29eb80e19b3a302096eef8ce80722cd6 task_058/solution/code/data/test/img_004.ppm +eee4609701c22af031ce769e28195747bf53b773d35d7e414e7666a3761ed3f3 task_058/solution/code/data/test/img_005.ppm +2f244ff9f764327a8413f9a00e686c4dea01b82610cce5a8250df1c7c0762a68 task_058/solution/code/data/test/img_006.ppm +feee8a8632db653466f756c231008c51b1a39ba92b938bf64b0f978a944565d3 task_058/solution/code/data/test/img_007.ppm +9b23d7c988edd23647165143107e52698fe1dd8e2cd665ac5fa3033ea0be6425 task_058/solution/code/data/test/img_008.ppm +171984fec0a5852f21843b0e18bf6d338537c4b7a3957b5ebff3b00bf1d97fd6 task_058/solution/code/data/test/img_009.ppm +82b1806f4172cbf3d71b113b7561ebcb24f29bd8ab2b5797181df7fcb18e43db task_058/solution/code/data/test/img_010.ppm +a3814b988e8e52b3b21a167f553487fe5d7e5e589a0e16446e00aa514aa59f29 task_058/solution/code/data/test/img_011.ppm +9ed0a0c1c31e50152b09e2233eaef432017a38b89ffa42be8b98c706c01c2549 task_058/solution/code/data/train/blue_00.ppm +0e54e8d222cb00d2982dfb50a0ae0529c7edcb9413b799ead948a149253df1bf task_058/solution/code/data/train/blue_01.ppm +5fda65267b69c530851d40deb0755fcc8b23909f6cb1566470ed483825fefdf4 task_058/solution/code/data/train/blue_02.ppm +fd559d62ac34f42265574cd1c01a16781c8b5c3afe14e641b3b2fdaa237e1020 task_058/solution/code/data/train/blue_03.ppm +b947c330edefaf336eaec2f73afa319ec7de6ff17d9d81433825bbb4fe380549 task_058/solution/code/data/train/blue_04.ppm +b140f4d49df1f8857a8991241b877b8ab5d1d5b68dfab97dc04e10c82f4f4148 task_058/solution/code/data/train/green_00.ppm +9b59db53aacbf41681071f2f8521a359d8bec34ed1c9424ea04759ab6f4a9833 task_058/solution/code/data/train/green_01.ppm +0e4ea0dc3057af6df979f1c4bc2586f0060dcd7655b9e4e3b6c54e99c59ef10b task_058/solution/code/data/train/green_02.ppm +fedbc243d7ea14f7f25793136cce3297689a2288da58491fba480326408b6ac0 task_058/solution/code/data/train/green_03.ppm +c3d3abc1b6b91f2aea1fb73749ef8b86552cdb5b7bb47595381d5799e6f03b8a task_058/solution/code/data/train/green_04.ppm +cf5e632c00f6afbaf95fcc953fd09790c59b576226c10f5c8ce1eb7bd709a1e1 task_058/solution/code/data/train/red_00.ppm +67ffea61af84d17fcfd1ff5af9643d88b0fd0fa1a84884c6141c81bd7de72083 task_058/solution/code/data/train/red_01.ppm +42cb8d99f73ff9fc9ac0ba55a500a6d81221d3b53051f3b96cf6add7bd6fbb1d task_058/solution/code/data/train/red_02.ppm +d5f5107862488fa874e24b782244e85843cddc583b668432c8fb9842bd08d475 task_058/solution/code/data/train/red_03.ppm +f3ea9ce82e96edd0dc30e8b92b183e73db6bf57b1e08b3b5df85f01a648225bf task_058/solution/code/data/train/red_04.ppm +681352b4a1787a69013b294cdcfb351bbc95e93f3009a3aa1fb6eecfd0a619c2 task_058/solution/code/data/train_labels.csv +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_058/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_058/task.toml +24b589917eb00667b1042f65362a58150cce88ecee57f6339d9e71fffa5cacc4 task_058/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_058/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_058/tests/_shared/static_enhancer.sh +2a44616c3318d5c800e727d13d8f4c7763213a8577b5bc2d60a08a59163699b4 task_058/tests/_shared/variant_runner.py +ac57b47454ef24f368871abd9bfd73db808da77e6dbd46255d4b81f4592b99c9 task_058/tests/enhancement_cases.json +75702fceca55c0ca740f18f8362c69d45f9e001cc3fcfc6f6e8bb9399181f2b2 task_058/tests/review_hard.py +7d8c32238ef8fc8671e09475cf490d345c2afd84e24920e321d600bd0ee3be33 task_058/tests/review_legacy.sh +939c60cf5c1fc2d773b9669644ddf8e8a978aa5dceb194e64da33e6b5510c40b task_058/tests/test.sh +bd0cb30a9df33c69af5b12a3c120108cdcbd81dc1bf3a9931d67e057335b5f44 task_058/tests/test_labels.csv +7532efdc9dcd380af5cb5ed57ede590d9534a2212d5d54187cb62e5a9fe3cfab task_058/tests/validate_aaav_dynamic.js +c8614a5bc37a7f58fe277a7b2520ee41bb33724f7dc2aeeac409db5a3ae819a4 task_058/tests/validate_enhanced.py +ae64a6f1f540ef90b6202e90c494818746bbeb11f4a4db6195707e6dd85cb62c task_058/tests/validate_outputs.py +602e753c5e39a2a667afa2d1fcef7e6b024be4d76cfd1c057a57f6ba2528f1ca task_059/acceptance_checklist.json +fc9e4c7641973f8936f3c9dbd988bbb78be66621f55c8177a1e09a4d16b70021 task_059/environment/Dockerfile +54e6f5e180d49ea94e31b435fb965656149b4f45bec93ab44f879e99585798e6 task_059/environment/code/README.md +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_059/environment/docker-compose.yaml +4cb6c8a024ea55ada343b94ec2a3351e34717e32321be9159987deb4c9273775 task_059/instruction.md +0390841b9a0d098aec02322ace54abde4f2c53b69a6cafbb0d2949c494eded6a task_059/quality_notes.md +b2066b406ad89df0bc9b349b03ebcbe6df63555118bbb48130db81dab68a97af task_059/solution/README.md +9c461766526eb742bc648c41560b456a577d24e0556a742f2f774b57bae01028 task_059/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_059/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_059/task.toml +3ddb28a0caee42ddd5fb7633f03776098e05c3693acb0bbd2f26d14453e71c6d task_059/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_059/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_059/tests/_shared/static_enhancer.sh +e47afbb961544e18baf7703dd6b4720e1bbafb5b211203df5f3291c1922ffacc task_059/tests/enhancement_cases.json +7ce3998d01d5a889522139054d450a86389d1e2c003035710e8ef2401f7426e7 task_059/tests/state_equal.js +b95f49511bc50e65f007ec1ea8280aad64e71364b9a7e48a4a99d6156d319dc3 task_059/tests/test.sh +489a5eb652a2bc0b1e746e1853d498df09056b44222517d4cd684a81d6822930 task_059/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_059/tests/validate_browser_smoke.js +19bc41f90706042a06ffa324e30dbc270ef70a3175cee5e2846739f8d921ca68 task_059/tests/validate_enhanced_cases.js +1ad98f1ebca4544d51253a9e20b66d86af363469577ab8c8ecb5bf59ef7a4082 task_059/tests/validate_render_mirror.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_059/tests/validate_semantics.js +58ecaa5eb21b92d179fd6033729b08995b59d68f87b57adef8303006843b4e36 task_059/tests/validate_ui_behavior.js +4078826c680f85808f213a3a53ee9191ced8c4c4d0cb75254d24cd3856acbae7 task_060/acceptance_checklist.json +fc9e4c7641973f8936f3c9dbd988bbb78be66621f55c8177a1e09a4d16b70021 task_060/environment/Dockerfile +7c92ff8c5fdbc1510812eee1f7d514c3aee1489c1634ad19fe4c0c5beb350b82 task_060/environment/code/README.md +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_060/environment/docker-compose.yaml +70fb1e9f58f22624267e3ce27c65a359dfc8572cc8e0e227848627a619f5f29f task_060/instruction.md +8e2d3d1a6b9ff4a1ac49c80905b213ee481141feedce11591482929af8ffc157 task_060/quality_notes.md +cee7fb6aa88de6a3757c6e50db440777de1d83ec87d44ff6dcd2fcfc334e320e task_060/solution/README.md +bdbafbbd59a7d153380252afd356640f2d88fcb96e61f5128f7d0cc02c4f239a task_060/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_060/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_060/task.toml +586801be9dcae51cb82ce025a7ea4b39391db251bf57e4fede4a842886f36b55 task_060/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_060/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_060/tests/_shared/static_enhancer.sh +1bd3271bcab216421eb706cdb8eef6b4ff2d3109daf28e420282376b661fb718 task_060/tests/enhancement_cases.json +4293c67fd22581cf0b82c8e3916508fdd70a25b92b2b75dccf8d1b9871671ec0 task_060/tests/review_hard.js +b2aa26d9190400647938d2fa914e1a2f132d5ac750b65944a890ed8fef625850 task_060/tests/review_history.js +ee51f5e3751d9be1d72d0b127ef7366c1a40b7e004ac7223cb86919cb0602839 task_060/tests/review_legacy.sh +30467cf9e1b9d7df0a47d6cf9d615251f614f196f92d0428859a61ae1a258a90 task_060/tests/test.sh +e8d03020357c362fdb5e3181a3866304f5319d4b495a3fe01d7ea93bd75f819d task_060/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_060/tests/validate_browser_smoke.js +fffbe9f3b76f9c047615670dd7b91d2eb6dc83c8222b473e2f7fcf00c50d8e61 task_060/tests/validate_enhanced_cases.js +1ad98f1ebca4544d51253a9e20b66d86af363469577ab8c8ecb5bf59ef7a4082 task_060/tests/validate_render_mirror.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_060/tests/validate_semantics.js +c1b97b896339f34967d55afdb80942c910845462cf104f15413b32825e414a20 task_060/tests/validate_ui_behavior.js +952c2bc7cec59635d9f3d26d8495e1ba323a3e5b4310cdfdfd3e14ea63abb190 task_061/acceptance_checklist.json +fc9e4c7641973f8936f3c9dbd988bbb78be66621f55c8177a1e09a4d16b70021 task_061/environment/Dockerfile +8ed61e7470d5f235cd903f968927aa2a4d9dba08fb0e17b1e5718d9851aec1ca task_061/environment/code/README.md +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_061/environment/docker-compose.yaml +7f91c8c5e18c9ff9706f1cbde02618d1dfa9aa1d446c37d227986c2f7700b251 task_061/instruction.md +ccb9615a22ebdb8ed1886df222771c2a4e93197599b644aeb41d0eee4780b79c task_061/quality_notes.md +d1e01da277056e7650ecfab7d8d1ef0da1e49f6d2797fe22ef63721bbb6855a0 task_061/solution/README.md +42e2489974d6f9f9a86405ed047fefde689754ac2355f8b5a54dd9d2dab48b36 task_061/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_061/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_061/task.toml +98e21f9fa6c290b7b9446d00da2daa57921d438f0db37a06b2bb830635f923ac task_061/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_061/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_061/tests/_shared/static_enhancer.sh +3fed1908b8b5642fd3230926c90231ad66dd43ebf417773247635fdd9e7cc5e8 task_061/tests/enhancement_cases.json +55955ba4971baffacf2caf8b0faee7615096b278fdfad5834cb893a06e55c12c task_061/tests/review_hard.js +16e46d4248cdcea8c7e5f7ef3d022d85a6e0080513b24f1cbf1dd58526f3cc54 task_061/tests/review_history.js +ee51f5e3751d9be1d72d0b127ef7366c1a40b7e004ac7223cb86919cb0602839 task_061/tests/review_legacy.sh +30467cf9e1b9d7df0a47d6cf9d615251f614f196f92d0428859a61ae1a258a90 task_061/tests/test.sh +194d4bde9d3529c59406e7a71dcf8f3541f3c840529548cc66f72553916177db task_061/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_061/tests/validate_browser_smoke.js +039c030f42bb7b69b08c05ecab17b95b4c153701162dcf62a121be619fc36fa6 task_061/tests/validate_enhanced_cases.js +1ad98f1ebca4544d51253a9e20b66d86af363469577ab8c8ecb5bf59ef7a4082 task_061/tests/validate_render_mirror.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_061/tests/validate_semantics.js +3a6b1d2d30cc5b782c3d133c063928ac5a3e07dae2e631641f26d5a7904aff04 task_061/tests/validate_ui_behavior.js +92ddc8d14da260cbed8735712e75c4a3e31621720f2a1b6623d53d387332e724 task_062/acceptance_checklist.json +fc9e4c7641973f8936f3c9dbd988bbb78be66621f55c8177a1e09a4d16b70021 task_062/environment/Dockerfile +81f5f5720921149a45d3d982beef4637cdbea73996dd4981b13d70c10a786589 task_062/environment/code/README.md +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_062/environment/docker-compose.yaml +308b83fb97021e492ed123cd691f40bf3a10c693dd9364c623e6cb0e572a81d4 task_062/instruction.md +0643a42f3052ba57ae0d28c658725c35945655696896ec88b83d970e7f93b40e task_062/quality_notes.md +ac734d8c3a9e0d8477ed77035e10b32f94f2965eed62c74f9423d3b3838eb477 task_062/solution/README.md +76db4e9a3a7cba2163a3d41eb3541626ed3295f46f520d12feb8395b4d20d847 task_062/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_062/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_062/task.toml +1d67bead8373229c0505c18b0d79af494c0d2bffa37e80a86acca13f71bf0732 task_062/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_062/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_062/tests/_shared/static_enhancer.sh +5bc1e532c5d1c5f3583b17711ab3ee26f7974dab3fad9cb4cdf7a95922612c28 task_062/tests/assert_visible.js +0d1a80dfdd1292ccdcbaedb127591b57e3d0febdf39ccbcfa4c52ab88c0d0942 task_062/tests/enhancement_cases.json +ee51f5e3751d9be1d72d0b127ef7366c1a40b7e004ac7223cb86919cb0602839 task_062/tests/test.sh +79246e48c1e150a6955f78ce43ce161ab4b0c41f883eb34d3c37b1c38102d890 task_062/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_062/tests/validate_browser_smoke.js +b57019c9a2679d483fdea82ac3bd149a5ad6f130753080b12c73ad671a175279 task_062/tests/validate_enhanced_cases.js +ae4837f56261d30c074d62011d67d778391df40989eacd56c6bcfeab71533f77 task_062/tests/validate_render_mirror.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_062/tests/validate_semantics.js +abe8e4fe2cbfdb1e16d941f49ff85f2202fdfcef096d572db380a685001cbf2f task_062/tests/validate_ui_behavior.js +ecb1aedae74c4c9db54d953d6fe0ca55f98ed0a38233347e9b008194f91e4725 task_063/acceptance_checklist.json +fc9e4c7641973f8936f3c9dbd988bbb78be66621f55c8177a1e09a4d16b70021 task_063/environment/Dockerfile +8156d8933e59bb4d994943f99c0108b2677cd72ae84dedc518f98f6cad40340f task_063/environment/code/README.md +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_063/environment/docker-compose.yaml +4d39fa1edffaba01dc3a96ac5fb53df44a1d2979e73638f62d5ca31967128fc2 task_063/instruction.md +78530738e1906fd584c86014f2fa2522f7347f88c4ff9e6ec2e3d883db735257 task_063/quality_notes.md +10c167adc42d6952f33b6fab717f670a5b803a36ea3ab4387aee5c9a9d2a440c task_063/solution/README.md +a4705c6a07048ce99c04860fec2ac51de5e72994011996f0387413705a087d7f task_063/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_063/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_063/task.toml +682378f1316c70aa78e23a68c43b2fcda771cf9b128d81d67fad0ffd28d04daa task_063/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_063/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_063/tests/_shared/static_enhancer.sh +5bc1e532c5d1c5f3583b17711ab3ee26f7974dab3fad9cb4cdf7a95922612c28 task_063/tests/assert_visible.js +56ab48ee61c442e9e462f5c3912d6504559dd2183a27ab410655e5dac1012065 task_063/tests/enhancement_cases.json +ee51f5e3751d9be1d72d0b127ef7366c1a40b7e004ac7223cb86919cb0602839 task_063/tests/test.sh +44075e4098b58b480f60b67cf6392efcb462c8c4fc4229498f44943704e06062 task_063/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_063/tests/validate_browser_smoke.js +581eca87795395b2e56a9af45f6d67e7e9fcdf015ea3efc0197065d32b1e6c9b task_063/tests/validate_enhanced_cases.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_063/tests/validate_semantics.js +ba2de6e990e594b839445088101e3d61dfe3b13141c048a2edb2d971479704e8 task_063/tests/validate_ui_behavior.js +295b3a7af87e2f5ce4f317dc49c7ac733a0e2248581ea1bf21f3dd2a892fb754 task_064/acceptance_checklist.json +fc9e4c7641973f8936f3c9dbd988bbb78be66621f55c8177a1e09a4d16b70021 task_064/environment/Dockerfile +c538687d12db25757511e7f55a7cee84aa25d4eb657cf67e53106e9d6f247cd5 task_064/environment/code/README.md +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_064/environment/docker-compose.yaml +46ef9bbc0f066fad2dd710a31157cffcb76a19f94a86657119238f00837aea7a task_064/instruction.md +c4bed2a112ad3c507fccf9c5ac740fd64741bf316301bd1d38547717dd1e6e19 task_064/quality_notes.md +d74e7230752a504899434dfed3f1ba75fad79f6ee8978b27ac99e7fddcdc2377 task_064/solution/README.md +ae22bad3219ea563dd9fd606afb10bf59d39ae03e334ed6238d92991643781d7 task_064/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_064/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_064/task.toml +cebccfa507b097955645686ec75a0d2e39a2c321b06cf5419bf6a076acffd38e task_064/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_064/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_064/tests/_shared/static_enhancer.sh +5bc1e532c5d1c5f3583b17711ab3ee26f7974dab3fad9cb4cdf7a95922612c28 task_064/tests/assert_visible.js +35edc1adec39c00ffbfc428ed7e731eeefb839f8a4063bbad8f3e90d9bf4a1aa task_064/tests/enhancement_cases.json +ee51f5e3751d9be1d72d0b127ef7366c1a40b7e004ac7223cb86919cb0602839 task_064/tests/test.sh +e8be7bfff279e4984606c8c74c2c892132c03d93d41835951df3702cadd47233 task_064/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_064/tests/validate_browser_smoke.js +ee77bc714d9bd089b1e8f0d37f4864a6522f7d6420560032b845d7112c35e5e7 task_064/tests/validate_enhanced_cases.js +522f9bd57ea1c76230bfbeabc0fbea3e774cd32b60478b76c8bce7e5d35fb213 task_064/tests/validate_render_mirror.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_064/tests/validate_semantics.js +1edc571b1b99b0a53e80a2c4d01a14b1c6a2ddb7a4d56194146409f293943a2c task_064/tests/validate_ui_behavior.js +43caa5b98c085443fa6e944654e4bb1ebcb6fd65b53aad7711a636a06269477c task_065/acceptance_checklist.json +fc9e4c7641973f8936f3c9dbd988bbb78be66621f55c8177a1e09a4d16b70021 task_065/environment/Dockerfile +31bfe96355f2f5c0ee6e6456325fac6d1eb56ed3aa4c4b9d7e9a174ec1bc06bf task_065/environment/code/README.md +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_065/environment/docker-compose.yaml +0b210d96c447e923cc50899ecbb9b8b722a65f4e677c036b439cbca81cfb6f39 task_065/instruction.md +c691a3a2277f7857efd8bce967dec4e38c9467f53bdf5452c230b2084cd85004 task_065/quality_notes.md +aec508bba0770bf6f0c481bdf0c1bef7f4e40b394af501669c53edc3e3c8c395 task_065/solution/README.md +df3f6c7b5e83cc1d2158461fdcc7a2ae3a4ad5e02dcd88f580396fdba14ab6f2 task_065/solution/code/index.html +824d81700641b1fa5a13da9fa9bb37568dcaeda79cc8040a65f516fa2786d942 task_065/solution/solve.sh +19366b5bf92a0ba810b9f1d3ccb1f5968f77af820401b57d42d6c5f4fe4be37a task_065/task.toml +6c94e342fcfa532a8400fb48cf8d4a92dab0cc95a34dbfc5deefbc8b3296cdbd task_065/task_meta.json +c99f7fe1820b127fca0c919a580ea14c3dfd10f5ff4f9ff5bc97c5cefec3c019 task_065/tests/_shared/contract_checker.js +70353e591e19704128781337cf504bb3a685a495e330bc540f3a3848e314758f task_065/tests/_shared/static_enhancer.sh +5bc1e532c5d1c5f3583b17711ab3ee26f7974dab3fad9cb4cdf7a95922612c28 task_065/tests/assert_visible.js +faa10385479fda178cc1a6a1df7b9585229aed250f292941994d7e09f9f578c0 task_065/tests/enhancement_cases.json +ee51f5e3751d9be1d72d0b127ef7366c1a40b7e004ac7223cb86919cb0602839 task_065/tests/test.sh +ad7024be7793a130ad66d0fa9fa8fe60acc402dc581df8af1cab08755d7d4693 task_065/tests/validate_aaav_dynamic.js +a4f3d2ad9c69bfc1150e25062e41a04c0ddf783193f9a39a9af3567831669221 task_065/tests/validate_browser_smoke.js +c4eddc8ddf6c67ff08be3090696497efd80d94f3d37d65215ae83eadf7e0bd84 task_065/tests/validate_enhanced_cases.js +522f9bd57ea1c76230bfbeabc0fbea3e774cd32b60478b76c8bce7e5d35fb213 task_065/tests/validate_render_mirror.js +209408fe75e57386f8e914d5c71d337095b81dc9f7390664ce12bb0d54566570 task_065/tests/validate_semantics.js +95c0239423c0912cb56546f8e994e5b76feecfcb25173180d9c4c30db1b35fed task_065/tests/validate_ui_behavior.js +1d2870f534323c474c8af5d86d2ac95b1b4ecc0fbac16cd71f1e8397a0e3e1d5 task_066/admission.json +4a187c415a4019debbc3951c87ad280be880e9337ab1dc987fcfb0330b04fd3f task_066/audit.json +26a3545853623005d1d5b3b4e539c326e15ac4e8ceee32e6d5448ef54a67b88c task_066/environment/Dockerfile +7e28451e278c99e795b0916688f1aef52d90d0ae30ccef3b17e7ca6825abf251 task_066/environment/code/terragrunt_sim.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_066/environment/docker-compose.yaml +b1dd51abdcbe42150892faec3e741406b9ae51f2ac7645888c4079fac248f6cc task_066/instruction.md +1d3c94b0f17ca9c008e80aefdc41d8b9079688076037ebb7f1cfddb80564409c task_066/provenance.json +7d23ef7ce8a7f6b5ca22601c9c051116c6ca423442aadde6558002872396efce task_066/solution/code/terragrunt_sim.py +a88b222d872299977b5149fa2ad90cc48d6f01ec8561b85e536ab1dd22b8b9dc task_066/solution/solve.sh +9c2c9064b6d6ae670f7434c223c0755d52d6137d52c455baf03986428626a9bb task_066/task.toml +add3450f5d85f990d07d1c67f97cef25fb10464dd8c97a276562e5de15cd64c4 task_066/task_meta.json +49fc12890fd8c46e9705485ce9642a71e79bdf40c5215d4a63a7067a028d5e53 task_066/tests/test.sh +aea87048400f52130dee6f87cbf8589b32a2ffc7bcd2bbe3e75b6399fca05bf9 task_066/tests/test_behavior.py +4fb1030f5f5da40aaed072679d6dc22edbce82f3aed43e470e6f2017789d8abd task_067/admission.json +f10e8bcf9ddb007b8c620572c780fc6f2acdaccd1b1b66d36e34c312596abbbe task_067/audit.json +26a3545853623005d1d5b3b4e539c326e15ac4e8ceee32e6d5448ef54a67b88c task_067/environment/Dockerfile +b5c907cc80cf1300bdcdb4682462666e907f2a08ed6309469e4331ed0d01234b task_067/environment/code/paddleformers/__init__.py +06e5be51423b3bf870b6e9c54bba3101cd07f868f01e9deb1c0edc605d970f83 task_067/environment/code/paddleformers/transformers/__init__.py +9dd4daf8917eebbb491a7cc637f141ac7e8f062d2f7de7fc694a5ef585e2f8b8 task_067/environment/code/paddleformers/transformers/conversion_utils.py +d53ced12fb73b7822a5268fefb33b948cb023fada465a258810a5fd772035cd3 task_067/environment/code/paddleformers/transformers/olmo2/__init__.py +c3ab9e20661787d3ee7e1165effc03901b6499c07130d0600d9118115d6bfaac task_067/environment/code/paddleformers/transformers/olmo2/modeling.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_067/environment/docker-compose.yaml +dd37630aa97e1a43dc278c8f4857de0ce9676691186e1456049440a234b926ce task_067/instruction.md +aa51df4cb3baf827218eca6f236e265cb8b51bb0a0302976f8c932e26b7cb2de task_067/provenance.json +b5c907cc80cf1300bdcdb4682462666e907f2a08ed6309469e4331ed0d01234b task_067/solution/code/paddleformers/__init__.py +06e5be51423b3bf870b6e9c54bba3101cd07f868f01e9deb1c0edc605d970f83 task_067/solution/code/paddleformers/transformers/__init__.py +79f997e8fa396bf827fb22fc68890e3d0e80f1c39aae19c5aa18a2d08218b5bc task_067/solution/code/paddleformers/transformers/conversion_utils.py +d53ced12fb73b7822a5268fefb33b948cb023fada465a258810a5fd772035cd3 task_067/solution/code/paddleformers/transformers/olmo2/__init__.py +c4ee0d948ea29582ff7f2c4ea2d9075e7bb623a6da31ce22f92aea2d84dfb847 task_067/solution/code/paddleformers/transformers/olmo2/modeling.py +145428490b1376fa6dbf0a2aaa1a7f084dc0425fe5de5cfce3bb21d8eb419932 task_067/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_067/task.toml +3865a341d96289b28619e30ece0199d8fe8758e8f7cda90e4b08c237330da617 task_067/task_meta.json +bf52b62e6ba810a5c8e81852d5044dc648978d086bca3b63c0642cbdb2a4f6b6 task_067/tests/review_hard.py +187b0474c960c1ad4742a26930079582ec3c67b973aef4a7fdbed9ae85eeddaa task_067/tests/review_legacy.sh +939c60cf5c1fc2d773b9669644ddf8e8a978aa5dceb194e64da33e6b5510c40b task_067/tests/test.sh +75e8fe99736b1c27ba2a693ed09fcfa80bb4f7141e132e477a7b1f45abe9f42f task_067/tests/test_behavior.py +8a4acc0f6b35ea6c290a4d0748d497f14ba98398e01960dc58a68bc4305f7c55 task_068/environment/Dockerfile +81a63fbf5e988cd0d9abf5d05933bd684b5bc0bbccd8f9a3b632f2ad8b5035b1 task_068/environment/code/cmd/secure-bridge/main.go +c2234267eddd607f2851209ed212a6d71c15196a6d37bbb86d61673e204f8c76 task_068/environment/code/config/policy.json +887b27e54994bdbc6d5598db36d920f633972eb1b40d9a8ff94f6cb25f12bda2 task_068/environment/code/config/processing_contract.json +365a3b1e992ee56874ea1fe5ecd670c3dab14356f0b7872ac7d5480ad10ad280 task_068/environment/code/go.mod +7731a6915e2689a9ee97656ff5209a63379ddd3475a450bc1081c8f3c871d72b task_068/environment/code/internal/contracts/types.go +487c863a2d1e9f3818e6bfcdf257eb76d880ac75c35cc88bbeb5a74522646c33 task_068/environment/code/internal/pipeline/process.go +a8cb58119d4bd29fec0b6e3010a45231b11064866670b853941ab48861da00c2 task_068/environment/code/internal/pipeline/security.go +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_068/environment/docker-compose.yaml +b1889af722f102718a4c6685fdd13e986265d0f5efef4ca33d32c5fd7805bc3a task_068/instruction.md +6a97cd52d7531ae6bbed8b9405bb0f337d1425ab158e19e45c89c1c2d876efcd task_068/solution/code/cmd/secure-bridge/main.go +4778451447d6915d4523d7cc7141c030920e3538e01a7f7820d285f68dc50ee5 task_068/solution/code/config/policy.json +7e781fe3b18c0bcc0087644d5bbcd220f068573437beff998649dd61e3fa7468 task_068/solution/code/config/processing_contract.json +365a3b1e992ee56874ea1fe5ecd670c3dab14356f0b7872ac7d5480ad10ad280 task_068/solution/code/go.mod +7731a6915e2689a9ee97656ff5209a63379ddd3475a450bc1081c8f3c871d72b task_068/solution/code/internal/contracts/types.go +e099500ca368ae07b4aab3793da67dfab3dcb03db319d0614b5f997b45404417 task_068/solution/code/internal/pipeline/contract_document.go +b2a67a39e568604313c0bb701ff2d45ac22fcd3b156f44fb3b63dffaba71982d task_068/solution/code/internal/pipeline/process.go +de58af3dfcf0c3654ddb333adb7c4d77b678109b9be0b1fa01af9bea6e438ac8 task_068/solution/code/internal/pipeline/security.go +449da9cf9d1cd74dfa128d9bef9dd4e068639b6f62b4f8442265adbe2ecc586b task_068/solution/solve.sh +39de7d6157976c5e1e78aca9267caab43e09437f8309364f5eb2d14818f2f413 task_068/task.toml +729d4cccc447537c5b5b69263a2a28f5cb94c600bab5b3a61b632485ca71a501 task_068/tests/review_contract.py +507a35639bc553deb3b700fc2aef5ed8bb13bb6a626c8f35b040d407fe1a5896 task_068/tests/test.sh +1b8c8b038a29fd7631f94c1a917f068a464e43f166b0be0202c9e8b5fd7f2421 task_068/tests/verifier.py +7473e3b94ce9dbecff707de9611cc7ef29a1b793f1e3428265c47c5fd1683eca task_069/admission.json +83405fdd3a425b52158ac64776ffee13545b3cd7a2a4dc1b13d7b58e146c8922 task_069/audit.json +26a3545853623005d1d5b3b4e539c326e15ac4e8ceee32e6d5448ef54a67b88c task_069/environment/Dockerfile +547fd8de51b8717212d7362bef53b2a26b132742c048a9eb9ecb55b5646c46c0 task_069/environment/code/benchmark_data.json +a36de27189c3fbaecf545189f09b3f0dfbebd155270daeb8671b0390b850fbab task_069/environment/code/databridge/__init__.py +0c3d1aed44645c87be563be8fa2fc0c8791f1928a15a090f7b0d819046e82b97 task_069/environment/code/databridge/benchmark/__init__.py +0cbe9a932176475bc3c17d5613cccd28f717476de91091ce4867522481c3b34b task_069/environment/code/databridge/binary_codec/__init__.py +76e1a94b3ee82b0c06c480f4a4424747dd8ae2175689d0d1a2c5b3f3ee80534c task_069/environment/code/databridge/cache/__init__.py +6aece07d3323fe0a74bb62863aa8a22aa935da73453a42e710a4e524fba9e976 task_069/environment/code/databridge/converter/__init__.py +3c2af440adefd8d95d6540659569ba4666c0eb4cc3a343e42f4f9bc470bbc8c7 task_069/environment/code/databridge/csv_codec/__init__.py +1efe8dc6ab095434a8d02ff01d120385b64590cb6b3bb137e28304278ed45ffa task_069/environment/code/databridge/json_codec/__init__.py +53c10de2a02462d9b7be31afc742d172b9019f1e491bade544eb15f6023042a4 task_069/environment/code/databridge/schema/__init__.py +074969c2a7b517a803b3f6a3135b1a628a0bfe8a5552d3f000e0be5dda83ac84 task_069/environment/code/generate_benchmark.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_069/environment/docker-compose.yaml +3dd44bce01f0dfd7f7913234069e2ae7d18a1facd784b1f07e5c94ee926bd672 task_069/instruction.md +2b9fc283da5e9d4daeb2c2120e591ccdd20af59b3c2aa7be26f6c678bb7b253b task_069/provenance.json +a36de27189c3fbaecf545189f09b3f0dfbebd155270daeb8671b0390b850fbab task_069/solution/code/databridge/__init__.py +0c3d1aed44645c87be563be8fa2fc0c8791f1928a15a090f7b0d819046e82b97 task_069/solution/code/databridge/benchmark/__init__.py +84cf1953da5bd6c38636718fef53b573622a7c97ec3c5ac23ac067d8582ab01d task_069/solution/code/databridge/binary_codec/__init__.py +6412f690ccb894dbb5139070361f8351caa9ea02b35991f687bf2ee7c0366c05 task_069/solution/code/databridge/cache/__init__.py +0cf688702e030b999729bae94ff37b06e54c22e2dc518d11d34046a2513424b8 task_069/solution/code/databridge/converter/__init__.py +7a57b6491aa7815674f104478db0c2a3ad8cc49eefe8881f01d870f3c85f07b5 task_069/solution/code/databridge/csv_codec/__init__.py +299d0cd5429253126e6236ec29fcd819ab4002d880ea4750f19a03698b788d53 task_069/solution/code/databridge/json_codec/__init__.py +8ee7579786f1212a07aea6bdc11f2217b2753670ae8222eb7418fe5ae9f77ff4 task_069/solution/code/databridge/schema/__init__.py +074969c2a7b517a803b3f6a3135b1a628a0bfe8a5552d3f000e0be5dda83ac84 task_069/solution/code/generate_benchmark.py +49c4ee0fbdee0c467e5cb383035fd53b3901fa70c5909198905dfcc0748b8de4 task_069/solution/code/reports/benchmark_results.json +478293f46d0b067633250e8993c6a1a5960b1e030f1a71062b9c9f9ddc7ec3c2 task_069/solution/code/reports/optimization_report.json +eae66313accb40c0ba4bd44f91b276daac063f80df9e9c50526c1f149c5fdcb5 task_069/solution/code/reports/profiling_report.json +e9a73efa6f215ad7753c971aec84330a7bb94386afe632c236629e71c6e99e41 task_069/solution/profile_reports.py +ae25a411e2b0aef2ac58ffd788c8d9d0807ba32632dfd1fa173921d3a4479a17 task_069/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_069/task.toml +3b9b6d10554be905e8803d2ee90353e53482558b5e8b9fa9649d24adb27bff22 task_069/task_meta.json +6c2b0bb06a663bb3e7b8b6ddaeed50c4e46d488019b1f2be35508391775d60fe task_069/tests/test.sh +5afa23f15d517194ac2ab7ccffec42c25d9e2ea76a3f4501e32928ed999d23e4 task_069/tests/test_behavior.py +98077d82e799953ef02b78608dc6c7feb677b024c77c2e74942e2552e53d96b1 task_070/admission.json +de22bcf8283081fb1dc0c14fbf1f4973b9dc3b87b71c8002dcec38b284885f37 task_070/audit.json +26a3545853623005d1d5b3b4e539c326e15ac4e8ceee32e6d5448ef54a67b88c task_070/environment/Dockerfile +01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b task_070/environment/code/paddleformers/__init__.py +01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b task_070/environment/code/paddleformers/transformers/__init__.py +01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b task_070/environment/code/paddleformers/transformers/intern_lm2/__init__.py +fbc94ababd96ae231239ac61468ce7fb60c7e1dec77938508136edd74a3c0229 task_070/environment/code/paddleformers/transformers/intern_lm2/modeling.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_070/environment/docker-compose.yaml +27d252c09201398db265a00aa2b96133bf280ed79ed8c4ad69432fefa55d83b0 task_070/instruction.md +c11fd6ef10c232e7b00214734517955bfdf6eb43709e828137c4f495ccd9ce29 task_070/provenance.json +01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b task_070/solution/code/paddleformers/__init__.py +01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b task_070/solution/code/paddleformers/transformers/__init__.py +01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b task_070/solution/code/paddleformers/transformers/intern_lm2/__init__.py +cc4bf44a1f377c87d9c29706ce329893bafb49da6bc6096bb283b76b6c6d2e73 task_070/solution/code/paddleformers/transformers/intern_lm2/modeling.py +f8db12dc4db2e4e69099a024ea62e94448cfb16c25b7668903ea4eb55d3b32e0 task_070/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_070/task.toml +c82da868d2a6f911b9bd6678fce4eef9cf3defff31ab3514db87798f52871cf5 task_070/task_meta.json +8932fe6148b4bdec88afda8a7dbfc48745da93b11ae0d3b57eb103d7c348d443 task_070/tests/test.sh +d1836368e5e4185d4e9a25731c2144c2c3c36f9716c388fbf195d85641e0fb84 task_070/tests/test_behavior.py +000bf84d63cf45c2c39bc1048d881196f54ab840284297cefad299cd7c464796 task_071/environment/Dockerfile +93aa64a86567796db3eaac474e1862c1513a29a03680c879371924de47e4357a task_071/environment/code/cli.py +7c0bbac3a278e7c73c695dcbdccb6ad37f1801d63366126a3903ed5f9c189c3d task_071/environment/code/config.yaml +753b7dd49c202476c6324b46a1809031c64f1b5e8b5038d50e5cff98fa535204 task_071/environment/code/config_manager.py +65b2354f57ac2c4d7088523d7707b3dcda671884c4cafadc752c818d2859e05f task_071/environment/code/coverage_core.py +761d01dac28f5a28a32999725c0de2649a9b0c9a6aef9f0dfe88637567f064d0 task_071/environment/code/coverage_diff.py +e5492db5dbb167dae64263df52a742c82e1066268c9884a23fb3791d268b001d task_071/environment/code/report_generator.py +5ef8afb8d04e7f4c5e4b54874898dcfad1afddad21366daf8bcce510a9156479 task_071/environment/code/source_analyzer.py +989fb745f0016c5649416413394b5863f3afc588e778667a86738008c389a209 task_071/environment/code/trace_collector.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_071/environment/docker-compose.yaml +ae9c31874562d70bed2eac78b01a89d51ec24d51ea5de1fbbc6f8da6dc7747c0 task_071/instruction.md +93aa64a86567796db3eaac474e1862c1513a29a03680c879371924de47e4357a task_071/solution/code/cli.py +7c0bbac3a278e7c73c695dcbdccb6ad37f1801d63366126a3903ed5f9c189c3d task_071/solution/code/config.yaml +753b7dd49c202476c6324b46a1809031c64f1b5e8b5038d50e5cff98fa535204 task_071/solution/code/config_manager.py +65b2354f57ac2c4d7088523d7707b3dcda671884c4cafadc752c818d2859e05f task_071/solution/code/coverage_core.py +761d01dac28f5a28a32999725c0de2649a9b0c9a6aef9f0dfe88637567f064d0 task_071/solution/code/coverage_diff.py +99542889197ea37f8bab53c9bd78e8cf41597f6449215e007a11f0790e99896e task_071/solution/code/report_generator.py +6716963b597eac432a555816dc382ab3d1b84b1bbec4313f4a23de5d999f2bd2 task_071/solution/code/sitecustomize.py +ab5f7cf73855aaec16d53c60391f75b4f006efa167388fcea5dadec8bfa90ca2 task_071/solution/code/source_analyzer.py +612ebfc4593445aadcc5094d3d52e3a2040622e92c4e593cbe3d8dee1c619f6c task_071/solution/code/trace_collector.py +d3582ba227c163d6b62ad81c43f26c9e3e61fd81dc3c955f41acb0c23ad26daa task_071/solution/solve.sh +8b4041e8062d77696fa14b8ef489d2dfd2ee3e02cc1cfb4fc165ec0bb65f84b4 task_071/task.toml +9af6af985a836d123472837f151547a1c66d5561f6ca540978850e752e367070 task_071/tests/test.sh +77b66f93d3fb901aeb7309215936255eb8da58b3cdefa62d2126753e95123b64 task_071/tests/verifier.py +8fff81f70405fd210c9dd52e052361766cd8475a181cd5d821c68019210cd2ab task_072/environment/Dockerfile +9bb2257e7f8f4441b490f6258715427a2f4182a591739b0eee8471d660046d31 task_072/environment/code/pipeline_optimizer.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_072/environment/docker-compose.yaml +1c5307e6e02147093fc4f42815c04a3d1a768d7dc8f911d3203536930e25c26b task_072/instruction.md +3caf0b493e82aa41c846f0bc6d57b4659a239443a3eeb76fac8b60c0e2744f92 task_072/solution/code/pipeline_optimizer.py +2c16e9053754f29c31c2cef19d13bfb0a00b748ddb39b2f1398fd50b9c550d61 task_072/solution/solve.sh +d110a4a2ac3cd97a30e11ce37bf770bbee95d92b188a3ec1f07f1ff8f912922f task_072/task.toml +666b86dd74952238e9aaf312f0413122b1a1d2d2a5d0240b86002401af563cd1 task_072/tests/test.sh +f8b2b291515ecd34d614970db8e1492e7fdca1978b1ba6366481764631ab8859 task_072/tests/verifier.py +acf1ca26dcc4b0eac323b0494c382829f350f9663852d06bce955b9a846e9d59 task_073/environment/Dockerfile +11d817cf6662385a0d4cb825db8214ac37db60de1cf00f31f724d2d2701689c7 task_073/environment/code/P04_CURRENT_AUTHORITY.md +ab6243b4cc0513bffb30383cf77a9fa33905c2f6b73e3b0c41fdffd334508d95 task_073/environment/code/data/frozen/cell_level_fixture.csv +ce03ebc546efa5c92088523a328d072b71b5ca1c9a3a668f212f59e764ffb845 task_073/environment/code/data/frozen/communication_edges.csv +be1069140ccaccd69306c41698da3d90d7af9235e925f1c8078fe9eed621df46 task_073/environment/code/data/frozen/communication_pairs.csv +86748c1f0213d37dbe2761b1f003ef3ef09a38b1191bd248e6ef3afcc6aa719d task_073/environment/code/data/frozen/mde_inputs.csv +9e1eaca42de1bc0f3cfd6934ae3e7cdde29041a4edd04579cae7606c1b34392e task_073/environment/code/data/frozen/module_effects.csv +f3f5be5add93d6451b18dcbc7f5f16ece6069691c7cac42d72c25e77aa7eb00d task_073/environment/code/data/frozen/module_equal_cell_summary.csv +5bf64661a548ad975f43afa43061978c1a5ff3ae401e66ac577f59db51f4fdb9 task_073/environment/code/manuscript/MANUSCRIPT_OPTIMIZED_vNEXT.md +dfeb48f30d1b14fb6fec65e987f2a1faade765181fcdfee658e0e5d0ffb458b8 task_073/environment/code/scripts/build_supp_figures.py +d53bf26f1d0e1fb629fc7ca98aa59672accfbb0df48a1cbe045126b4fad93f8b task_073/environment/code/scripts/cell_vs_donor_contrast.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_073/environment/docker-compose.yaml +59b71124a04d314ca741c9a4f7fc6237e2c57b03d581369d2f59a61f44894663 task_073/instruction.md +a514916af9e4b7317ef8613f904f15f5dd286d8b88ff13cb4a26f8d9f165857f task_073/solution/code/P04_CURRENT_AUTHORITY.md +aba133daa79697488045f7779ad8c5f0b191ae78085a6dbb5185d6e05ff18671 task_073/solution/code/manuscript/MANUSCRIPT_OPTIMIZED_vNEXT.md +567abd9fc4696f2dc3fa0cce575ca509e72100258746acdac6b15196343bf4cd task_073/solution/code/scripts/build_supp_figures.py +3e24f3500a572f94a1992ff287dcd64d931e252cc9b16f3bea33e7c8e609255e task_073/solution/code/scripts/cell_vs_donor_contrast.py +6df6aa912c85af6292c2e59232156ff16ce4f69d5165aa07b6c182a775ec6909 task_073/solution/solve.sh +eb6ca0c77f62a7b4b2094d006442fccc8a19cf22c23e78972040c92da9a00ff2 task_073/task.toml +329310cd37d91add349a7d52f6d16b42136cd990bfd67c77d8090887151030a6 task_073/tests/fixture_guard.py +db39b8748dbc6ce43c8446a80b15841b13d09dd7fbb9760873f24fc6274a9f59 task_073/tests/sitecustomize.py +595dffaf55673be3dd50295ba4f8109ea6311bb9afbb525e79ee01999d3ec38c task_073/tests/test.sh +d10659d28539d1abb524d0a1bb770ae2950f67c082e4eac8d42e1e85b2dad12c task_073/tests/verifier.py +7b992c57c8071e0c85f86944f4eb8df6c60a238eb3fd9f4adcc94a46df67a5b0 task_074/environment/Dockerfile +18d20dedcbcf2d83cb406da7828b429f40c845fa5920601e528fbd192af0f072 task_074/environment/code/mlp.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_074/environment/docker-compose.yaml +7af71bce4637215c4ccf8133279ecee0f27a6a54e64f7729d8e09e4fa85e3203 task_074/instruction.md +801f659e1280261fab6d70b94f306333c13e11d25ee76e249bc6bb269a972631 task_074/solution/code/mlp.py +3ee6dc75b6c3bb9d65e9ba412274b9f8409491a29e926fad2a15d7e2f7857f87 task_074/solution/solve.sh +829431de0754257f794283976e4e0c4106142a70164d60c9e5e44a8546d47c00 task_074/task.toml +3f96f9842347a9a69e035905999451a25e9a92ff2dad1f03d8ebac9e1a9143f3 task_074/tests/test.sh +94544d1f5a58019386f4f307fff78b2de03cb0761125cebcb2e6215c8c0d5692 task_074/tests/training_probe.py +6e5b1fa83620672e577c2f1004cab575f316e24810a22a846746dbf41d22a640 task_074/tests/verifier.py +67907280cb6992326a43678a358309b3650c9cb3586717819b1297db73ea47a5 task_075/environment/Dockerfile +a29eed9f34cf1dced20072ab1f8f819d23ade85eb6fd20f75d3fc924e4823c0b task_075/environment/code/data/README.txt +83655ae5aed54469da34a5ed5bd74c1fc62a77805b8f44fd21884bd38d9a0fbb task_075/environment/code/eval_config.yaml +32721cc4ae65e321ee7f1a1d599fd35c18602d344f9f9d082e7b87cd8c5a5151 task_075/environment/code/eval_metrics.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_075/environment/docker-compose.yaml +7a7a49f8d3495257b550ebf8e9f467270d167a2122bc34847d74ccbba13b8ccd task_075/instruction.md +0f8200dae6f72f2b5e30bd655f64707f15345b791af8894b50d9e22d255798f3 task_075/solution/code/README.txt +285dd1946ed796844c2136069b696ae63cbdfe2f65282fea8f68dca4ce454743 task_075/solution/code/eval_metrics.py +aad34f320b465d1c218751ba6447bbfa5a9c494af12148d6e562eab1d0b41599 task_075/solution/solve.sh +d110a4a2ac3cd97a30e11ce37bf770bbee95d92b188a3ec1f07f1ff8f912922f task_075/task.toml +898fc7e864d4f9123b81b5180c9bc15de810799f73c93b1f2574f34cf5ad250f task_075/tests/test.sh +74f0c77e088c3e9303ec67f0aca52fe4e346847c606623e6a8e45baacad4d8cd task_075/tests/verifier.py +ddd3b8d69a9b70d7001d8e6634593dc5cf2de93a5f4595568c5e1f2ac5f21c50 task_076/environment/Dockerfile +9cdf1e4dcae9bab3282db390ab50f225814ae056adb181c6c5804905ed69e47e task_076/environment/code/evaluator.go +bc388d007c93afac24d2ed2bd615e04778f9e04a1c5801b1e607e74f767c4695 task_076/environment/code/go.mod +8959844db5c269d13499ee4a1a376cee8854fc593f9319a68ee7f91910b15cf9 task_076/environment/code/loader.go +c85ceda35f64b837cdfcaa29047028c886ed29adff134b57d8c27159c569792d task_076/environment/code/main.go +fff74b33a4f456ad892de1b550dd98ada3a2e2c8224d765538714273395d3250 task_076/environment/code/types.go +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_076/environment/docker-compose.yaml +ae59f4769d9c53c16f075846498e246a6eb4be780ecce585d19fe4b7583a55ec task_076/instruction.md +3e3a3c7fe8378a0ca6b0e112dbb592d5680fe6be4667a115863708bdeace9b17 task_076/solution/code/evaluator.go +bc388d007c93afac24d2ed2bd615e04778f9e04a1c5801b1e607e74f767c4695 task_076/solution/code/go.mod +6e8b7017014d86cd0973b1f3ca1878f27767c394014f9e2286a5b3b82d74d0f1 task_076/solution/code/loader.go +7322eb2593bf752b6f30e4b2af922bca2bedfae0d672d88f9fd64fcf8ece00f4 task_076/solution/code/main.go +e2c0ff09ed5ccff7f9481a3611c2b75e76e1d3606bf37869e2690f247e8ebe75 task_076/solution/code/types.go +3bb3fab4945aa960fddfa70c6069d09a2d251e0c83f36ac545b764da30e694c1 task_076/solution/solve.sh +d110a4a2ac3cd97a30e11ce37bf770bbee95d92b188a3ec1f07f1ff8f912922f task_076/task.toml +9ecf454aee80ec8fbb320c297dce4cb13c1ce121625e3b04ddebe6e3d0e5f80e task_076/tests/test.sh +ffb0ab05637fe3277571d06b6ada7d2548f9d10802f6f377482cc23bd5ff7d87 task_076/tests/verifier.py +c521cdaffacd0a86231fa02f9a23d02121d659f6ff07f0d6629cf4a336392deb task_077/admission.json +090dff987e737ca503fcb6524ed1baf86027c136a58f78ec44e4e74fd1637fcf task_077/audit.json +26a3545853623005d1d5b3b4e539c326e15ac4e8ceee32e6d5448ef54a67b88c task_077/environment/Dockerfile +ad18e23d4e10b62940a3e9084b682eeb551c36a5e1971912c2c4c7d91a6b5a02 task_077/environment/code/app.py +1dbce8c61cafbf60c9812197305093b4e72bd5be20f23049a506dc3edf6a4ae2 task_077/environment/code/build.gradle.kts +192cc1a9049b6c44a567d1a707c3ead20a5decff12eb821d9e4f0aa8b9617f2d task_077/environment/code/gradle.lockfile +9e9a4287ae6604f0e7a458bb940298405d057a1bc4ae94d4125df801b80fbf4f task_077/environment/code/local-repo/org/springframework/boot/spring-boot-starter-json/3.2.4/artifact.json +3b5f27ee99e0edc3884a132a509e0980108ac6354ee5babe2034ea5d36c84b70 task_077/environment/code/local-repo/org/springframework/boot/spring-boot-starter-json/3.2.5/artifact.json +ce5b1785b681497db3d0ccaae8acb5b411f8cd439ed621aefe81cb944325ed6a task_077/environment/code/local-repo/org/springframework/boot/spring-boot-starter-json/3.2.6/artifact.json +7762dcd54eca231ee5328079bd9c34d40d7608605a14119e7484d1a5b264efe7 task_077/environment/code/scripts/build.py +5b1e52a4271929cbb5b4b5dfd65430a368a105cb5e07e874c9eaad1ee6bd0630 task_077/environment/code/settings.gradle.kts +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_077/environment/docker-compose.yaml +e3cc95413f36ae7b72de4ac8da893eca3d9478639c0e923182eb28121abd7490 task_077/instruction.md +0486ed6282eede20491f27ba668d1ed1a27c835969e3931316693e6a98ebbefa task_077/provenance.json +ad18e23d4e10b62940a3e9084b682eeb551c36a5e1971912c2c4c7d91a6b5a02 task_077/solution/code/app.py +c0fde495569c1ea601cd1fde724840fcc45255a3da4a15fd42a5940ecc5f2e48 task_077/solution/code/build.gradle.kts +f893008fad8ee4664ae90476ec635b3f9899808adb2dff28011d66d5bfa2c34b task_077/solution/code/gradle.lockfile +9e9a4287ae6604f0e7a458bb940298405d057a1bc4ae94d4125df801b80fbf4f task_077/solution/code/local-repo/org/springframework/boot/spring-boot-starter-json/3.2.4/artifact.json +3b5f27ee99e0edc3884a132a509e0980108ac6354ee5babe2034ea5d36c84b70 task_077/solution/code/local-repo/org/springframework/boot/spring-boot-starter-json/3.2.5/artifact.json +ce5b1785b681497db3d0ccaae8acb5b411f8cd439ed621aefe81cb944325ed6a task_077/solution/code/local-repo/org/springframework/boot/spring-boot-starter-json/3.2.6/artifact.json +7762dcd54eca231ee5328079bd9c34d40d7608605a14119e7484d1a5b264efe7 task_077/solution/code/scripts/build.py +5b1e52a4271929cbb5b4b5dfd65430a368a105cb5e07e874c9eaad1ee6bd0630 task_077/solution/code/settings.gradle.kts +fc7957e3bf19a0eb67b77ad22376b7cef8b6745984a268a407ffe11bc0afc113 task_077/solution/code/tools/bump_version.py +e274deca473674bffc7324e89e02d6b38e8a0b4b27abe4056151fd89c7770b1b task_077/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_077/task.toml +5ccbc49c9921d143f4fb455a8950f2cc81394cca7b6f2d99a297b34a761c295c task_077/task_meta.json +64f2dba4cd8670ebb4091960d3814d6812f4cae9d47dd0afc7b370d4a58728ea task_077/tests/review_hard.py +de6ae6b83821fbb27037d5e4d2bcaef509940c1c8009f51bc623833a9e9f8bf5 task_077/tests/review_legacy.sh +939c60cf5c1fc2d773b9669644ddf8e8a978aa5dceb194e64da33e6b5510c40b task_077/tests/test.sh +6facfee2051583342595ff66f72f6d214f1e6f633fb45cab0e27d5c7623f9ec1 task_077/tests/test_behavior.py +180e2a97808171bf377cf43e57e466565d6065b5c4fc310c0fef026e8af99878 task_078/environment/Dockerfile +25ce7e095fbb5d917d09f4d987606b610edd052c80f2d0eea09a92de910175e9 task_078/environment/code/go.mod +74ac741cc5f4b396669aeac9de5415654ab2176658b047455235757dd154fc1c task_078/environment/code/main.go +eced65a432bd0a32c58e1ad6cba83cb642010b5ebffd3c6aa1d6f521eb639c3b task_078/environment/code/package.json +6f1564f9f4a4ea86e76ae34eeb4db8c6a7ccbf36a213db0618434fefba2238ca task_078/environment/code/web/index.html +a96a66bd34ce1b63ef06e2755e339063bdd2e107ecc54ac4fa43b43ee52ad4ef task_078/environment/code/web/src/main.jsx +f3ca29f4f22836167010ad80ffd804a582ebbac9b872a68786defa66db5e03dd task_078/environment/code/web/src/style.css +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_078/environment/docker-compose.yaml +4313e0fbfe7be5e791dcb75884572f70168534fe766198ae94c3b921cadacfb9 task_078/instruction.md +25ce7e095fbb5d917d09f4d987606b610edd052c80f2d0eea09a92de910175e9 task_078/solution/code/go.mod +95f68602892a4916caeac4ff63ca1e017ae1d9bb7c9f6e7fb4b03406d91f7f66 task_078/solution/code/main.go +6d1a269b9d241b2e0fad1f4d4b55e84eec86af3d8704da7281d51378c05dd509 task_078/solution/code/package.json +80d80827b66ead5b906870b47b1f0ef653772551acaa9f92f44b719f953948db task_078/solution/code/web/index.html +bc9d5a77d356ff548cc13825ed12caf5e01fc5a49687722ea56ddd5c85995ad8 task_078/solution/code/web/src/main.jsx +0622a2eaf22f4b363fd1efc0c24b809ff349adda5e742fb308ecb9e4a9dd34ac task_078/solution/code/web/src/style.css +d52f79a9c000b78cf2962244e2e6fd4638bfa58b76f8a32da7bd2cead7fd776e task_078/solution/index.html +338f8fa909cfcd6c379f2398e9a9551febabeff2dbd24c4b81868dbe795093a9 task_078/solution/preview.png +0376550e5f1aa7daa832ff26d62aec530b7c153525407a509b67ceacf114b393 task_078/solution/solve.sh +df7eeba0cb47a2d505fc0f6a8e8e832e05bccd15c270e762d140883ab9832245 task_078/task.toml +ad2068d3251855126eb10d608a49a7fa2dbd09128135333ae6e241ad36492e96 task_078/tests/test.sh +a924b0f2020b75ad87378776b0b0642c34d779ad4c14d47994b41d9cde6432d9 task_078/tests/verifier.py +b419a98942d692d1dff345f81af6306db5a853716428b4391174cdfa45deb5f6 task_079/environment/Dockerfile +83b4cf25bcd9d9ee9d1c6fb8e43d301d6a8f78584d2aeef8e5896c5b45989dba task_079/environment/code/pre-tool-gate.js +660ba47d1bc1f2486abd948f4f84a38f89e599f985e2a185a8c91d5f02ad2364 task_079/environment/code/vflow.js +82b131aaa8d9eb568f07eaa09058daf6011979354f2f6152e8c5b4f9776866ee task_079/environment/code/workflow.md +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_079/environment/docker-compose.yaml +ad9b2be84d5aec94c1aaadfc42f0905d398bb646714bddcddc187aa6dc73b9a8 task_079/instruction.md +83b4cf25bcd9d9ee9d1c6fb8e43d301d6a8f78584d2aeef8e5896c5b45989dba task_079/solution/code/pre-tool-gate.js +714f68b7f17a49bf09d6c58ea3e08067b342d1aa7bed8d6ef6b137c274cf0f1a task_079/solution/code/vflow.js +e9a3118b5fc5c8b190cf741a3c3159877b49214e6cda4cbccbbff25d5c65948c task_079/solution/solve.sh +df7eeba0cb47a2d505fc0f6a8e8e832e05bccd15c270e762d140883ab9832245 task_079/task.toml +119ff915f4c7d54eb37b26a45bf613f75febddee58c2e7e28ca6353157d17037 task_079/tests/test.sh +b4bb758ca98d6401df6933372176465d853071ad92cde0414d499cc3315be465 task_079/tests/verifier.py +9fd23032c75e25db327cb1336d8b43c500b6ba284173c632e680672288b8cbf5 task_080/environment/Dockerfile +1ad92b347f7be622ea927e5c1ae51bbf0f7b85e040740cf7b31840d5403c50ae task_080/environment/code/evidence/scenarios.json +3d3b866ceec08375de6ce725a3e1e3c201e9b5ad73843f3d7882e8fac07c206a task_080/environment/code/evidence/source_excerpt.json +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_080/environment/docker-compose.yaml +dad21df58132808897f09ec964c3ab5d27f9c96f84180024058b779a96aa93a5 task_080/instruction.md +920f36bc0f69bd3544142dd3fb5e8c10bdd44e1808e8d9fcc8279a4bfd7d8533 task_080/solution/code/plan.md +dbeff841b765c64212436ee30724e9d3c73cc6f69a26e6b885e0bab67748d74e task_080/solution/solve.sh +1bf075891c0c837b5d3d72ae09ee1f4283ce6fd9a657c0ba721fee5e72945dbb task_080/task.toml +2ef2a555117b1301fd850c0fbb3c7413f95e04a40e43865d67fd9b0d61ed367a task_080/tests/test.sh +ffe496b7344fd999e890d7c94976e90eb526fc7766e0e6efe84e43b04a94c702 task_080/tests/verifier.py +bb1940444950ffab1ee203e2880ef3f9948fb1bf2b86ece6f863385671fa5be7 task_081/environment/Dockerfile +5826745c937c2ae8f6465aa5ce9ab9b7d768e79f5404a1bac7de47e0d04687e2 task_081/environment/code/fixtures/README.txt +7edd0718c15c80c246eff9df2935bd321e5faad2834894d5235a9d52a036231b task_081/environment/code/forensic.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_081/environment/docker-compose.yaml +d9c5d9266a4f8279bc395d7a20e3c8de74d9b762f1c4e141da7c863eae2a7634 task_081/instruction.md +ef561e9991b3c8d2188e6db235ea005b5329a208b1c230749caac3cf09223309 task_081/solution/code/forensic.py +11e8b720ae938a1f326935f290ebef8533cffcd78d76ddab3d245a4676be0d20 task_081/solution/solve.sh +418b9bc02c1ba4604732a6ab7eaf4c39c0db293fd49f30819411a40b56d15668 task_081/task.toml +666b86dd74952238e9aaf312f0413122b1a1d2d2a5d0240b86002401af563cd1 task_081/tests/test.sh +6ba1d73141b06e2218438b74c5687745c4120cd7df14aca2d4c177b6568438db task_081/tests/verifier.py +b8f01182d7df9900f85f3a30a62338a7787dd0b9eaf0d01c7084d3c9c3379704 task_082/environment/Dockerfile +d364ff4fca600b7b2aab2938906eec51147104e33a73e4d67058f296237e9994 task_082/environment/code/data/schemas/products.schema.json +69d31c97f5321f4968e051c70f1e20f9bae3ebec150561a0ecaa1066d8d8056f task_082/environment/code/data/wal/products.wal +943a4ce5f22c5c6dbced651fcaf625585553539e4af884e7d549bea270405495 task_082/environment/code/data/warehouse/products.csv +f4805fad9507d7bd06ab51b45610c55515f745b6f7bc44d064507c1a55ded6e4 task_082/environment/code/rollback_tool.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_082/environment/docker-compose.yaml +6a54326c4871e531592622be8d693e3ba87b63f3a75463cdafb707903ed71063 task_082/instruction.md +8e6818698a80100d6b7f0ea5a6db647f5af042b56545f73fc22ffeb20a3ef74b task_082/solution/code/rollback_tool.py +2182a1d3f293ce139b16d80d380318fd958e01a01450428e72851a1a227ac8f5 task_082/solution/solve.sh +cb8850a765fba30185914829976e974e0e66cb7c13da12850cfe9e515c38a221 task_082/task.toml +0eb774fa8550d69ce05cac4f6d4744d0738aff7a2080a77c6608d46d54f608c4 task_082/tests/test.sh +e4d1d598ab58261d82602c01dd54fb2fc9f5d00a092826d1a9a402049173ae56 task_082/tests/verifier.py +a65d1dcebabcb1e282badd9e9593122d40e545f2fcfadacf97087a74a3bb1971 task_083/admission.json +c5e07b2c481bcaffede4a63274a94f5eb2eb316fa5ae7606b01217417ddd2cf4 task_083/audit.json +26a3545853623005d1d5b3b4e539c326e15ac4e8ceee32e6d5448ef54a67b88c task_083/environment/Dockerfile +dc78728679d74d68fc59787aff9f2dd9fae7e856cb2b06b8211d24554af51e4e task_083/environment/code/solve.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_083/environment/docker-compose.yaml +ed55300a1c4e9c2074c3c8be46e004bfae4f0928be076ad97f526dd0989f9763 task_083/instruction.md +d8422027a02f03f24bf4564c1b620d6b6f44d748d9058666e9a0fc6f661c711b task_083/provenance.json +686f4b677f545624bc33029fc5a2cd07d0e57ed60e2ae7179633af5902e314c7 task_083/solution/code/solve.py +dafa11bd92380053a22e0aea06c37f6c35c525d37fc36d34a6e0abe5bf9dd932 task_083/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_083/task.toml +7e99442289ade06dc00d499054479d7d3352d56ad49cd204c15222f3ab592edc task_083/task_meta.json +c25baa37cc7de2ca5fdca517fbcd89e142f7bb479ecb3991ef01bcc93cd5cfdd task_083/tests/test.sh +a0ecb2d893bde27e5852d2073be94b0381d7e7da2af46162d7ec9dbb478e6c59 task_083/tests/test_behavior.py +787759cf0cccda2164c80dfc6ab6ec5d1663e82acc9a48e636b3308147540567 task_084/environment/Dockerfile +0860ed307a00b11ff2c6fb0ee406a18a219517ff9e11930b6f4343b58dcb5aba task_084/environment/code/backend/go.mod +6dee2be6383ae2daf0c83620056d5a45c1f9daa3a79e0fdca27adf860fc6e4ff task_084/environment/code/backend/server.go +185159d8df1fa6f2fdc58542443abf0aa612c4ff0b28ebb4e54282be8e1be571 task_084/environment/code/frontend/package.json +f6499770781763a34bb5ca44843e35a31b434bc94623eb67d2430c100425e0a0 task_084/environment/code/frontend/src/auth.ts +4641726db23fb03155a87da070cfcb2559b44e167331856a160bc059ccf54051 task_084/environment/code/frontend/src/callback.ts +7175d57b3306b725dcc79ba7d18eb83452f2b4b8487c952a13e423571a2e819a task_084/environment/code/frontend/src/store.ts +d7b214d83425f9ff509f714967863aaece922ba84a66c9e517d4aa82c9914c80 task_084/environment/code/frontend/tsconfig.json +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_084/environment/docker-compose.yaml +cc812b86948a2761698df24188103619820bb3369f32381422e7517f3b57fce2 task_084/instruction.md +0860ed307a00b11ff2c6fb0ee406a18a219517ff9e11930b6f4343b58dcb5aba task_084/solution/code/backend/go.mod +ee224f81ef2235e1fcee09d5240f4bf210e02fdebcc5efc86e55096314200b8a task_084/solution/code/backend/server.go +185159d8df1fa6f2fdc58542443abf0aa612c4ff0b28ebb4e54282be8e1be571 task_084/solution/code/frontend/package.json +eb9bc927d2bc891f191e365eb07d3a8c2e3772ead1706ad5ae123acc95be31ec task_084/solution/code/frontend/src/auth.ts +d3e91ad96d2cca68f3f672991576e5dd9db8514779ae8a1efd3a712bf383e0f0 task_084/solution/code/frontend/src/callback.ts +8765e5e99fbdb09ed94b0701e227fdefcd33a6e334fe1e804b51d59c41c42a9c task_084/solution/code/frontend/src/store.ts +d7b214d83425f9ff509f714967863aaece922ba84a66c9e517d4aa82c9914c80 task_084/solution/code/frontend/tsconfig.json +d826b02169c47aeb4fa69296919cc5a91d3e1c6854953dde5a7a8b587121ba22 task_084/solution/solve.sh +829431de0754257f794283976e4e0c4106142a70164d60c9e5e44a8546d47c00 task_084/task.toml +3685b163bf509b0c51c1f57045cad7ecb1e048e903b2a760bdd576d5bc8d5907 task_084/tests/backend_verifier_test.go +ef2f050e1921cd67a56db5041d44a5bfa8bb07235a4741a358bea61f3a56c906 task_084/tests/frontend_verifier.js +b305fd617152539fff7241a04fbf120a09b7788955ef0123d1981e01b227acbc task_084/tests/test.sh +164bed19ac726dff75a6b0d95e2849557d451f68b3973dc041e36c06aa801b18 task_085/admission.json +1819aacc778142d248171e082f56e20f57c5a730972e6f78ba263b5e1a208958 task_085/audit.json +da42e2f9dab4ade0270d0e7b815a56bd0bdb1c66ca288d22e28af55cab7e50c5 task_085/environment/Dockerfile +187d0c61b513d061b7a99c46fc412a2d7067c3dbc34148a72683a8cefec81f29 task_085/environment/code/build_paper.py +df22c9ac65491ab3477252665c2210ccde15e0c13b02f0e93fdc623dcd6c1a7c task_085/environment/code/iclr2027_conference.tex +34ad99942d311403406c40460406eb29dc66259e6006b42b9a024756bf24c540 task_085/environment/code/sec/experiments.tex +f4acaa90f4b76287987cb75e8b8266f0deddde596a51fe85879b73155b1d3307 task_085/environment/code/sec/fig/pipeline.pdf +d8a259097a6288aa874b954dbef42598a0b0065635232a2491857a7c1c8e0739 task_085/environment/code/sec/methods.tex +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_085/environment/docker-compose.yaml +b6cd658e5a6da18ca75702c71a6a995bfd3403dd3bf23d2744da312e16dbbfce task_085/instruction.md +e8de268a051771d9f26e12fe3bade964a33f79166ddf19e20382f6954373a1b1 task_085/provenance.json +ade9f6000717158e43ae5d4fe1c47d45b37f5af50accd38de3d9f95713e75bb6 task_085/solution/code/build_paper.py +c323003dddc8bb8c15dbfbfbff665345e83cca365ec896de046b4fa5623b5bc5 task_085/solution/code/iclr2027_conference.tex +5cfd7caab0b4efef0114c2b12c93fef4b2ed345e49380891942d181d7dbfe3f6 task_085/solution/code/sec/experiments.tex +6e2139a6c00963c7900d2b5c7702a17bf0991961524adc9001b8e75f16d877ad task_085/solution/code/sec/fig/pipeline.pdf +0426d14db607e478c7d2d3519bf1a2e34b0784d3592a5d78a418a6146799da93 task_085/solution/code/sec/methods.tex +a16da5eb23f6ddd523a24356402388531f4a278ae37fa161c63678a622f1d037 task_085/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_085/task.toml +a94048469d311422a2fe58ac75cab1bff2e86bf7c07323118bfe87ca04491f46 task_085/task_meta.json +4d8a7ee7732065b354411c47660df3cca24e4fc5a04dd73b8d9d5e0b8cd89c11 task_085/tests/test.sh +4313362d7d22881c2bf3e875c06c4597ecd89d843fbc93c64dfc4269cc511fe7 task_085/tests/test_behavior.py +fbe31303f02a3b11674dc9e1c6f2d88df347ce0a859fbe5ff02762923794c008 task_086/environment/Dockerfile +d304aeb8875572cf9266f98d4dc2012cda9998f69540790563f826dd42c7b060 task_086/environment/code/config/pipeline.yaml +e7e95f52af2359ea4e9ca1bf9e5970a1af325ccf75343f3ff1aaddd44451a099 task_086/environment/code/config/schemas/input_schema.json +760c6240571ce7b499a290ff520337a1391012eedd9b82904ea07ded3c4bd1a1 task_086/environment/code/config/services.yaml +239882ca7e0a91e5fdbbe47f05684a3ddc08b3fe23d616b8d0365db5f6776827 task_086/environment/code/data/input/inventory.json +57e162f79d4996eb3c408d9dae6e01e12f5092a535f5b8fad3e9f346d7f07765 task_086/environment/code/data/input/sales_2024.csv +bce9588f0de15cd763e2f9eed9f13efee62022d30d970fb3ab972b793e701783 task_086/environment/code/data/input/suppliers.xml +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_086/environment/code/integration/__init__.py +9d03d1f6fe74f7373a85461c00e0ce8a1e1b29cb9b9a1b2fff8e0fcc20930e62 task_086/environment/code/integration/adapters.py +f98f5c68a3704f2b60260b5efc0721bee3ac2f248755fe4bc2a73aa01932d33b task_086/environment/code/integration/bus.py +3083ba1f8eef8503b51f67825b49f3cdeac3429cd9784803ef903e1c029db6e1 task_086/environment/code/integration/config_loader.py +682aef81a46ee88762ab47c84219b34ae52b3840521b692d70d07fcfaa3732cb task_086/environment/code/integration/error_handler.py +c150faa5fbc6088ad837256c763b04bb385f44cb344b1069afa3de5a00456c08 task_086/environment/code/integration/pipeline.py +911748648b9cb511910784f4af3f2dbd8c7bee8aa4e0e81f916dcc061fbb4fdb task_086/environment/code/main.py +5968b3cc9e80a8579f52e2af1f363fee57596e348219cda2cc3def07046d5aa5 task_086/environment/code/run_pipeline.sh +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_086/environment/code/services/__init__.py +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_086/environment/code/services/ingestion/__init__.py +4478d8184c0fdc3c3474e8afe413b4f7aafb4bdd82269d9a595cd51f039897bc task_086/environment/code/services/ingestion/emitter.py +00f754fd0a5cee7ed55a1d19373790979a805e5c1603c9a6518b9f04afdabcde task_086/environment/code/services/ingestion/reader.py +eecd49605ad8db94668e0db6b0be60eff25fb067033e9c220ac38389e1d44445 task_086/environment/code/services/ingestion/validator.py +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_086/environment/code/services/monitoring/__init__.py +3cc4ccac512af0f09bf90c2632ee13f25c827814edd3189c05e75ea72005513c task_086/environment/code/services/monitoring/dashboard.py +950b487a01d5eabfb7af834750825e45ba7c034b8cc90bf73a55a6701df4d29d task_086/environment/code/services/monitoring/health.py +b4dde2e780dcef077daac9c2c5b58c8c674a812febf089b7c69ce3b864108b87 task_086/environment/code/services/monitoring/metrics.py +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_086/environment/code/services/notification/__init__.py +288e7668c3b120a2160fdc5a2bd15a9677953edb5ab3b6b9b3553cd3236664a2 task_086/environment/code/services/notification/channels.py +90e56485fce3c016d9dac92cac78f157a270d40c2724ac48c153d45f49e86bfc task_086/environment/code/services/notification/dispatcher.py +fbafec20ffe6685ae738e1ecd95d7f0bdc4de7f6b9d537857e835570c178d0f2 task_086/environment/code/services/notification/formatters.py +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_086/environment/code/services/storage/__init__.py +41c7466bf8e0d1bc01bd16bfd8d4ba376f5dfa68d616c937cd71429324e9a14a task_086/environment/code/services/storage/file_backend.py +63db7e42c6a1871ab7c47c25dc9e89a722d05b5bf589db7ac0156769dd95090f task_086/environment/code/services/storage/sqlite_backend.py +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_086/environment/code/services/transform/__init__.py +c60cf155926a2da94345c68e2d8583946fa4d1689ba7b08ba438cba70d19a48a task_086/environment/code/services/transform/enricher.py +db7577aced7bfad4409eaeb356b7bd814466fc17d662eddf7405e7eb63de1a03 task_086/environment/code/services/transform/filter.py +0ca55681602779446c51d03555ee9c67fde26c4164c1cca2c2686599c1b32164 task_086/environment/code/services/transform/normalizer.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_086/environment/docker-compose.yaml +2f6477d394ff7521d238c5a9b897004028d3a4677652510ec5f169cd327ad063 task_086/instruction.md +7d0c4d495512ef17068577795b327e057b45ae45b6250efc7dbb81b3d92a7ed9 task_086/solution/code/integration/adapters.py +3446846caaae837a9d3e39f792ebd8dec9c18cce5ec79ecf254a70c432164d52 task_086/solution/code/integration/bus.py +07597620a4bf963c37d4d71c1a59b4c5a20bf2a98921079c0a89b73cc51a4891 task_086/solution/code/integration/config_loader.py +40b1201b526a8749631b3a4ba342c79b1b9c23a5b065d6e081ff42df2697d729 task_086/solution/code/integration/error_handler.py +dc4a975f30cedf11d8e66612f053bb623b8b30c112a59d77e5e102742d8ada88 task_086/solution/code/integration/pipeline.py +e158507eeacb4b79178c95fa90dbcb90ebef14f758e393ca94635db2d318c2bf task_086/solution/code/main.py +f8f72f5f2d7be57bc6907eb591ac76c6d44f98d8c6d172976b3a64694999aab1 task_086/solution/code/run_pipeline.sh +d3582ba227c163d6b62ad81c43f26c9e3e61fd81dc3c955f41acb0c23ad26daa task_086/solution/solve.sh +cb8850a765fba30185914829976e974e0e66cb7c13da12850cfe9e515c38a221 task_086/task.toml +5e5a0596d0dbd2724e962e29d5211b188556577aeaafea14ff26c57a15219e62 task_086/tests/fixture_guard.py +a1437912b560298e2b192c037fe94a5e530ee2cfce4af2bef4beaaab6bbbe32c task_086/tests/test.sh +76cd108bd99ba84ada6643a11cf0200baca14b172d13dd17e4a538814ffab5a7 task_086/tests/verifier.py +0bf515d41aab5a369063aa020b2ba995df923006fdac40aa529de1d9ed94ec12 task_087/environment/Dockerfile +30d6c4d3bf9e7b9f63924d5ac417a2b7be251fb7f9ee21cef8771459541fed9b task_087/environment/code/chartrenderer/__init__.py +4c3a3b9334e16733c732520558ce9524fcc93d8dfd6c23ee8c5172104b5120bb task_087/environment/code/chartrenderer/chart.py +e385af96db7ae5678fdfd7bf329f95865b2eacd0f21eb4644d62fb5fd7cd79f9 task_087/environment/code/chartrenderer/engine.py +5628834ca85f6c47e7d0a66826c6cc2043900e26b217b45a3937999528e5d70e task_087/environment/code/chartrenderer/values.py +17e55c4ebcf798bc26549dc38b8f86e0fda31cdcba3739776692017975eeb107 task_087/environment/code/charts/webapp/Chart.yaml +97fbeabe60304da778c02856e5b79ff67ecba0bc4a3fec48d48bb61a3030b321 task_087/environment/code/charts/webapp/templates/configmap.yaml +682fa9eb7575c92daef39cdebffd3218f90e01cf03a499791d462dfc91728e22 task_087/environment/code/charts/webapp/values.yaml +c91dcb77b2ca49ef26f5997c41a223428beaa89ab3ac81af4543295114f408df task_087/environment/code/cli.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_087/environment/docker-compose.yaml +397e6d941bbc983b78bc70e3906143feaa7d29012ae4019b3d48efda920d580d task_087/instruction.md +91a4f3ad4d95f77af548e7073b0735d4b7982d8fa6111f1cf2dfaab1c4acdcdf task_087/solution/code/chartrenderer/__init__.py +750f1325cf72c025f42b9aa8d0e187c6045ff50f304ba4dd9167509d5cf6ed08 task_087/solution/code/chartrenderer/chart.py +cd6c2a4c909b760a1f60215de4ec4e9801e0fca281d1e618d80855e88a611e5e task_087/solution/code/chartrenderer/engine.py +134de0636187a696fb0f02a4c62cef5f424db10065336cdf68907c958e841ea9 task_087/solution/code/chartrenderer/values.py +17e55c4ebcf798bc26549dc38b8f86e0fda31cdcba3739776692017975eeb107 task_087/solution/code/charts/webapp/Chart.yaml +bd525b131b7a3f406bf638266c0058db5891adf6ded833ffd03430d641000d33 task_087/solution/code/charts/webapp/templates/configmap.yaml +682fa9eb7575c92daef39cdebffd3218f90e01cf03a499791d462dfc91728e22 task_087/solution/code/charts/webapp/values.yaml +f74eaaf56f30f87ff8d18e9a6ea6abf51633bf3fdbf61023f94f5b8f565b2d3e task_087/solution/code/cli.py +063f28d4e9472872be3b11f7be2116d122ca9491792381badde09bc43d94d11a task_087/solution/solve.sh +cb8850a765fba30185914829976e974e0e66cb7c13da12850cfe9e515c38a221 task_087/task.toml +c438ac333af3e5b0648ac0ac7fd03dea72489f40e306e0245a3c3f14dc99b0cb task_087/tests/test.sh +e1e40358b4eb0542aa2646bcda1a8037053189868fe6f8c0f35d793cd5328012 task_087/tests/verifier.py +cd5190b930f041ea03489c8a978da09c80b99808da602c4262c230090add0408 task_088/environment/Dockerfile +4f1b97ea0c9b24f700463d334259058f9f3dc6ad3ac5073dc231881a2f373c6e task_088/environment/code/checkpoint/__init__.py +27fe07f6acd9b50aa64b9923725e966b07191558df3384750ea8b54461d8be09 task_088/environment/code/checkpoint/manager.py +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_088/environment/code/cli/__init__.py +130acafaef8483625c857235eb995dace14121a5ba10eec2c7464c9f045153a7 task_088/environment/code/cli/__main__.py +ed3e4d6e83ccaa36ef0779b8f9c45e9a3f8803bf674c53dc867e16ba88d21c51 task_088/environment/code/cli/main.py +0e2113119ab60d2652c036950585893e976bd35df3627acbbc34e9478c95022c task_088/environment/code/data/configs/analytics-service.json +03f70da428a5212bdcb25ff7c1ab348979470f656027e4ba84745344e927aa41 task_088/environment/code/data/configs/api-gateway.json +5e764bd0774cfa998587039781f0794085e611d99fd69776106393677a68fa89 task_088/environment/code/data/configs/auth-service.json +80bf6c6cbab7f584f0240d88bf094d659d853094f61059b856b6195ef59292cc task_088/environment/code/data/configs/inventory-service.json +1ff232e3fd08f9aafa082f1e64cd37aac450f961b6c4e279f367f5aa939f4836 task_088/environment/code/data/configs/notification-service.json +4ab1a503adda0ec12f7530592d9344a550833564198ebbf24f8dcfddda48dc48 task_088/environment/code/data/configs/order-service.json +0c5c6cb3c967ce2505a1e26dbbc826f385e1ce8360892498b3627694c5583a0c task_088/environment/code/data/configs/payment-service.json +0f52a71c7143d9622267fde13563cc49c7cb8320408fab4fda9a827f48501b25 task_088/environment/code/data/configs/user-service.json +e8ee33bebd7b23a8ee4c554b32a8fc5d929ff8329da41f0b1106c366556b038a task_088/environment/code/data/services.json +3894f2b9301a58174c8e39c04338be7780bfeec74c913c4250076c815ac11b6f task_088/environment/code/data/state.json +fb7c17eac12f47b036d0945d6725e1b2a1edaac04fd5e92f06de94c31440d48d task_088/environment/code/diffengine/__init__.py +b2e4141ba777a7d164fbc695b2e7ff38179bb00cebc0645b48ac53d027c8d67f task_088/environment/code/diffengine/differ.py +85471e3d43e3d5f32a5d4287125399a5afc756de9d7e25f099f737d93bf2f806 task_088/environment/code/registry/__init__.py +7e8267351678bea58ab41691ff4d2c33ba50178de356eca76e979324578595e9 task_088/environment/code/registry/services.py +4657712e5697821e687777cad03b9fc6bbbbc57a0bba58fec3decb691ac6fc3e task_088/environment/code/rollback/__init__.py +1eb4ca1bd497e4edea3f0f050afa59ccecc0bb4a27e26e3f8013e784e4453390 task_088/environment/code/rollback/planner.py +1b0e1832edadfd20799a1841166953087bb468bbfa4c2e57893db6e998d5bc56 task_088/environment/code/statestore/__init__.py +b179f6ffe468b44aed01715f9f832f5d1330d5f66a515be50c614edae2da00fd task_088/environment/code/statestore/store.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_088/environment/docker-compose.yaml +09fa76243b6e3a5a589bd7570d8178d6dd20fa9b98b019ff182b34db0cbc7c1e task_088/instruction.md +423cda72b924dafc37e41c9b9228671536884160cefea40b1fbeded0cc44e0f9 task_088/solution/code/checkpoint/__init__.py +d144de219be43101b5796789051e3e3e235c56ef3724b47d00f5187f1ce7c5ed task_088/solution/code/checkpoint/manager.py +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_088/solution/code/cli/__init__.py +d9f84d973e46d988d0dfda176dd03650f11ea05520d71016f571dcc9486bf723 task_088/solution/code/cli/__main__.py +72657f050894ae9205d1a119618251977a1b15a7840fc6f620a21338ac31f58c task_088/solution/code/cli/main.py +19b6eff5daf0fe69339520c2e0a66a385ad4a6b90b0ade9d1e09f46ccf42aea7 task_088/solution/code/diffengine/__init__.py +5c4a492b864a361556daf97466a5b4d8fdfd4315b3761b219b95abe33f6ae4c8 task_088/solution/code/diffengine/differ.py +7dfb9b252c13800a8427b3541e4a9618e5dd8b4b20944ff25d6f575d12f732bb task_088/solution/code/registry/__init__.py +76787bfb75eb4b0c29bac23351817dd156457a277fcc22d34a1673067858e250 task_088/solution/code/registry/services.py +0c13eeeeb3f62dcb96dc4deaaa5f307e1e59e85f5f53a055e301015edd14123a task_088/solution/code/rollback/__init__.py +046c972e1c97adb3162c8a81ce6d3e7160c0ebf23a144743c811312032cb0be6 task_088/solution/code/rollback/planner.py +37b256a49941162a8fd56342f58163f03f82aa6dab8c3b409d74a46e9f463574 task_088/solution/code/statestore/__init__.py +f884228edcb9a90d9da740c22a716230a9fb820d4797b30fa4b0a54dec9e0fb4 task_088/solution/code/statestore/store.py +744170a7d814601f9e93f3f541b6281d12bf629607312556df4591f77a95da55 task_088/solution/solve.sh +cb8850a765fba30185914829976e974e0e66cb7c13da12850cfe9e515c38a221 task_088/task.toml +666b86dd74952238e9aaf312f0413122b1a1d2d2a5d0240b86002401af563cd1 task_088/tests/test.sh +e72441a661665d05139b285ad95e68ebcb8f7388567592cfa19fc6818c890b25 task_088/tests/verifier.py +7f7dbd82c010eea6176b36d1cfa63e3acc4a66ef07764b6b6a031a4d723908a3 task_089/environment/Dockerfile +0aac42fa051571efc40e5fd999a71c410d87eb7e760b3a72a9736f7fe62ee43f task_089/environment/code/cmd/collector/main.go +02f335787353151979fa13aa3c952a3d70a82d249c7a3edf820674b42809543c task_089/environment/code/collector/collector.go +4b47ed92d8a651a2344faa3e3e4597c07f63ef10948a5a418b5b60bfa4064f75 task_089/environment/code/go.mod +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_089/environment/docker-compose.yaml +f7d2716590fcc3b54021083a1c4a15cc0471de0fa27bb7bc04ce9ffe484ac0c7 task_089/instruction.md +745259c8e3dcee39a1b8288e8556b082e5db61f9d7bcd7148bbc0f15039c0f20 task_089/solution/code/cmd/collector/main.go +d02b5adda8448df4c9c19961b9cc5af413d33d81a6830dc16ff7570f33758eec task_089/solution/code/collector/collector.go +4b47ed92d8a651a2344faa3e3e4597c07f63ef10948a5a418b5b60bfa4064f75 task_089/solution/code/go.mod +26bad30397a0b5795aef7b7ab2155d5b074d2fc631778584dc27ed445e135610 task_089/solution/solve.sh +829431de0754257f794283976e4e0c4106142a70164d60c9e5e44a8546d47c00 task_089/task.toml +304ca640e1d3e1055236da511b5564892e6cc867f96f62ee1d706428abc9e3eb task_089/tests/test.sh +9fef415b0180ebeebb86019fb5d56089367cef19f8002247a1fa350d7e2e9810 task_089/tests/verifier.py +924260499d8965edf7f3aafcd95677b82e8ae4027742ef3b454d15c9b01ca902 task_090/admission.json +f0337621ac231be0ae598a492f033f6d262dbda31ab5772f39464f5e6f2b6406 task_090/audit.json +26d1548d427c807fa0bc372c9d1aab539b53a6f390a9690053413fa13eeb3061 task_090/environment/Dockerfile +248e12eeb14df0b953191ba8def876d738c39c24b857b4738e32aa4867d6ca1d task_090/environment/code/.infcode/hooks/existing_prompt.sh +248e12eeb14df0b953191ba8def876d738c39c24b857b4738e32aa4867d6ca1d task_090/environment/code/.infcode/hooks/existing_read.sh +b9461b7ec914d9af5c0b3fac8e54f5ac89b545c75fc8769646acef655bde939c task_090/environment/code/.infcode/settings.json +75d4cd9a9b5ec107aa1b5b3f6e31e789e6d0ab8c600519adffb7bdc424d0de30 task_090/environment/code/review_hook_spec.json +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_090/environment/docker-compose.yaml +43b147760461e26cb7d5332bf93e995e3be86a400fc43763aaa3ae41465e101d task_090/instruction.md +2935143707ec575ff252b461bdd9cbe24f516beb158676f0927ee2e14289a1d7 task_090/provenance.json +248e12eeb14df0b953191ba8def876d738c39c24b857b4738e32aa4867d6ca1d task_090/solution/code/.infcode/hooks/existing_prompt.sh +248e12eeb14df0b953191ba8def876d738c39c24b857b4738e32aa4867d6ca1d task_090/solution/code/.infcode/hooks/existing_read.sh +fe7e3017d5c2b3a58da463b621e5bca0e8eea66335d52e342935112e6e85daa9 task_090/solution/code/.infcode/settings.json +75d4cd9a9b5ec107aa1b5b3f6e31e789e6d0ab8c600519adffb7bdc424d0de30 task_090/solution/code/review_hook_spec.json +0a310b15ff80ff60b0c242683ff5a733f5217e1c4c3e659d045b3876d96ed668 task_090/solution/code/tools/install_review_hook.py +688efcc167a9567969e773fba08ee75fd083e5e6a4504cbab3c5a4dec4a34e19 task_090/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_090/task.toml +45cf7b11f656d5092fc1c0a7fb48d51d904ccd0122d2942fd70d22e370df3ee8 task_090/task_meta.json +21a2926d5b096c2f3042fa6eaea26f1635f9f0bd5c025676d0f971084f43cd2c task_090/tests/review_hard.py +88b89832d03063f0e56a75e0e3e1926a44f4e65047a3c99a604c7b53a3fce900 task_090/tests/review_legacy.sh +939c60cf5c1fc2d773b9669644ddf8e8a978aa5dceb194e64da33e6b5510c40b task_090/tests/test.sh +5b27283b81903b47c4af23e4cd8965953532251c828477bde51c6ef512e90d57 task_090/tests/test_behavior.py +9bec056d04900ed11cf45248ceea73d244c68d89f29ecac622f394433195f437 task_091/environment/Dockerfile +8e37c9e10dbcc8676921feeb9a2f569274389e4a4134a76a999c6f9f03dd6cb3 task_091/environment/code/aggregator.py +fb0721d67caac7c4c59b00049ef8060137fb602f71949f2544a79fca4ef9904d task_091/environment/code/deduplicator.py +e5bbb40292856bc69af3d48e137cc2d010e1ec981848062eb1894beb5656e7ec task_091/environment/code/enricher.py +027a7da96171875a358d7eaab1da77c239e49bf865864c510078c75bf499d21a task_091/environment/code/exporter.py +c7033f06c2902b83de2381b289ee3dffa156a46f70b0c84a4ec8215065647a62 task_091/environment/code/ingester.py +e3c29e5a69c9de23833aa3bab30f266f460cb14297ce40bc346736285df1d246 task_091/environment/code/models.py +8b2f0698d2f4e19ecc2d80f2e5bd7389ebbe5beef19521e6df717f10c9cc171b task_091/environment/code/runner.py +ddccfe8cf0a5739f858916691253846890272d521335447c0dd36e095aa7cc91 task_091/environment/code/sample.csv +4a40981c6449de35c7280583a371be80bb5bcafcd86efdbdb120be73e9a6f1ba task_091/environment/code/sample.json +03baec3d338980f673e8b20c321fe4463303a412a3e965d32875af2d9541bd5d task_091/environment/code/sample.xml +e02d5ceace1104a7a4b7852d5bb73ce8874c5129754abb935fa14488361d5eb0 task_091/environment/code/transformer.py +7670b67e875083790082d2c6906e84d8444fe38189d981c042f9c0a5e1552af6 task_091/environment/code/validator.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_091/environment/docker-compose.yaml +93a3cfc2075a73da17b3c15a5395b387cdad61ea784fe343b82f749987ef4456 task_091/instruction.md +8e37c9e10dbcc8676921feeb9a2f569274389e4a4134a76a999c6f9f03dd6cb3 task_091/solution/code/aggregator.py +fb0721d67caac7c4c59b00049ef8060137fb602f71949f2544a79fca4ef9904d task_091/solution/code/deduplicator.py +e5bbb40292856bc69af3d48e137cc2d010e1ec981848062eb1894beb5656e7ec task_091/solution/code/enricher.py +027a7da96171875a358d7eaab1da77c239e49bf865864c510078c75bf499d21a task_091/solution/code/exporter.py +c01a47ec1e2006f9ccb5493be50e7d14cbacfb660b68d7b7def7e13fdc64f2f0 task_091/solution/code/ingester.py +e3c29e5a69c9de23833aa3bab30f266f460cb14297ce40bc346736285df1d246 task_091/solution/code/models.py +1ce784f325410335fcba46e30a1be02c13ab7c5b6f8e6745f1e2e770a7ce629d task_091/solution/code/runner.py +ddccfe8cf0a5739f858916691253846890272d521335447c0dd36e095aa7cc91 task_091/solution/code/sample.csv +4a40981c6449de35c7280583a371be80bb5bcafcd86efdbdb120be73e9a6f1ba task_091/solution/code/sample.json +03baec3d338980f673e8b20c321fe4463303a412a3e965d32875af2d9541bd5d task_091/solution/code/sample.xml +ad37916c146c1c0f6b8af45658666275be91477bca57708f0e44163ed28be637 task_091/solution/code/transformer.py +410af1514872cf91987e4f5d900651affc8ead6f9552a598187cad948aa3b2a3 task_091/solution/code/validator.py +07d241fd4bc073ddad466dc38af4e638fab289ba2601209d723885287ced7af6 task_091/solution/solve.sh +6512f688ccd8bc7bbaf9f759e45f8ff654abfe54f1b40988bfdf789c82a0c4e0 task_091/task.toml +22c68697108c0872d546b87ef45822a9b02efc66aaebcd1a275988f1b5c1f3e4 task_091/tests/test.sh +50b43ecc4b9fe5d23cd49b39eb33541bb9ad6ab31dfecb1e6baec9e740bf3329 task_091/tests/verifier.py +291c4e036cc9c845336885da4af53bbea5f139371353b716e24a509edeefd4b9 task_092/admission.json +6c1484039c481f4f4a7f4119e09e77175b6969419f26e5643cf2bcedd1f19344 task_092/audit.json +26d1548d427c807fa0bc372c9d1aab539b53a6f390a9690053413fa13eeb3061 task_092/environment/Dockerfile +e60ec0eaa9691230e80c00755ac650ac72ee6855abafbfa8eec4467dbc374880 task_092/environment/code/docs/agent_spec.md +219d2af8335b812c4854896f06e4a96d6582861447e022c0a44e8a9c2dca302c task_092/environment/code/docs/需求.md +7c7ed5c01bdf2e0a8eb946ef72cd03bbbd3820643055afd969439f530075ff4c task_092/environment/code/spec_writer.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_092/environment/docker-compose.yaml +18c7e4ef8d1b47785cbf827d31782a1968f12d25752f72fcc0ba80250f49ab94 task_092/instruction.md +17ba25225d08f1d866a292118b2de522b096fbd882932d1dd934039acbf0e504 task_092/provenance.json +219d2af8335b812c4854896f06e4a96d6582861447e022c0a44e8a9c2dca302c task_092/solution/code/docs/需求.md +593ffbe3bea704f80197c65215ea4c1c7d770ca86654af77cd20e9bf67508737 task_092/solution/code/spec_writer.py +e5972bad5fa9ddaa21d0099bcd133d9ad253c5b5d2dba40facd6d3bdaa453cda task_092/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_092/task.toml +2ac0612996d0af0089875efa4c4189a1eaa9ffd14d92b442971a3324e965f94d task_092/task_meta.json +b67f2ef30e4e62bec9c63ce485d52297bf79b1d486bce0660d2b272d63dd56bf task_092/tests/test.sh +f8deb1579eb12a85603ce5eea3d8f373f8cfeb20e8ec39789b355510cfe07faa task_092/tests/test_behavior.py +7621cd6e252a44ebc18fc1461742e52afd85e2998051e83825e54070a22b47bc task_093/admission.json +927e3e4fb7b69da9886ebf6abbd14859dfbb74d6d915962c5468ecc16b4b872a task_093/audit.json +26d1548d427c807fa0bc372c9d1aab539b53a6f390a9690053413fa13eeb3061 task_093/environment/Dockerfile +522cfb6c28cf21df6e060c48b44a391e4a4b71a37bfa36008078400e1085e3ca task_093/environment/code/.infcode/hooks/legacy_read_guard.sh +81569eaf083d09420f1c865fed10162b81dc2252227640f8eb3ed97e3b5b7b60 task_093/environment/code/.infcode/settings.json +4d081617000fb70babbab3bea5a3829e402e565cc136f98f73957a40ba4db3f7 task_093/environment/code/review_hook_spec.json +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_093/environment/docker-compose.yaml +7144acdf19ba48bc3e1da93e9fde7a228a18c4daf722b0540070c68676d2cfc3 task_093/instruction.md +f847b70101c10faa3b25bbe321c08cd21a79e6c0d8fbac7d882651c64c8dedd2 task_093/provenance.json +522cfb6c28cf21df6e060c48b44a391e4a4b71a37bfa36008078400e1085e3ca task_093/solution/code/.infcode/hooks/legacy_read_guard.sh +5e9c94b6666ff4f2e993d4ba2981b7bf9d0ce0f3695d163087ce81bf459be2ca task_093/solution/code/.infcode/hooks/smoke_post_context.py +25627dada1730a67b5ae41a7c629c4f619ec3b21ec94bd78d1d2c249de62acf3 task_093/solution/code/.infcode/settings.json +4d081617000fb70babbab3bea5a3829e402e565cc136f98f73957a40ba4db3f7 task_093/solution/code/review_hook_spec.json +c2794dad30621b9a323aa38e1f634523dc641c02bac86cc2923b380546eda6c3 task_093/solution/code/tools/install_review_hook.py +3ea74d18c03a5f9f34baca2930f4d1ba8fac265659db8643ffc3576d3bb897c1 task_093/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_093/task.toml +ca0cf3de61639e6b05784dd2714550aac5140dcb766d48e881ec8fd7f252f78d task_093/task_meta.json +68042ca6bb1f133373f4bf9ba16f6d967c9bc678294c1bc612a45e57499e37a8 task_093/tests/review_hard.py +eab37afb39219eee6f12093ea8332eaa33d1b4e50254fbad2dd3b0d3e88893ed task_093/tests/review_legacy.sh +939c60cf5c1fc2d773b9669644ddf8e8a978aa5dceb194e64da33e6b5510c40b task_093/tests/test.sh +9ab767060dcb83c842344a999f70aaafb7e03c1c3e83d54302de728b9abfe12f task_093/tests/test_behavior.py +42304a809500e434aca44ce662e5b073900ab4420ff68a726685f74b9fd983c7 task_094/environment/Dockerfile +b6e4bd4745e50c0ec683dd270a9b70d139d88c28adf784b35e48bc81d9bd19d7 task_094/environment/code/evidence/disk_inventory.json +5c82937e5120155a461d086ac6c8ef49eb237f137886f1cacbc42941db736b47 task_094/environment/code/evidence/kern.log +902cd0030f5b7bfdd4e016541f0fad0860795bbeba562389e4f82f8526ac2150 task_094/environment/code/evidence/mdadm_detail/md0.txt +a192a936fb2ce4f956e424bc21a47ee67ad08045b7fdbcd2653c1c4c550a23e0 task_094/environment/code/evidence/mdadm_detail/md1.txt +b354152aef20c535d48e459defb2ed357f9776738a3e6f039e31fe555d37f16a task_094/environment/code/evidence/mdadm_detail/md2.txt +be939d6e6ec6c255f88d7ff9f240c0f975da10537a73b82019e8f69d22044741 task_094/environment/code/evidence/mdadm_detail/md3.txt +902cd0030f5b7bfdd4e016541f0fad0860795bbeba562389e4f82f8526ac2150 task_094/environment/code/evidence/mdadm_detail/md4.txt +7e83bcd8c0b3594471e2f48a431a5e115746107063a9e61f4c747ebca785dad5 task_094/environment/code/evidence/proc_mdstat +09b0db76f64a8928f383edd0b3bbe86f9df92bd3a3a307632e8f80decb29e040 task_094/environment/code/evidence/smart/sdc.txt +e483790ba317f5b6e8bde3d705bc20df4deeaf0a4b1146ba88327ee99a907f77 task_094/environment/code/evidence/smart/sdl.txt +6c154a74449233b30191b37fc2cee81797430402fce5b61e251c08eda93040ec task_094/environment/code/evidence/smart/sdp.txt +4ffd6d2a3edc732b8b820a17259e3403bae96e930792a9321b93cd2a71fe56b2 task_094/environment/code/raid_recovery.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_094/environment/docker-compose.yaml +25a1d8125f3a3daab7643b0bd59f7210f65e70c88adffc0e4e1ec8f47a4b676c task_094/instruction.md +a4da5c87cc1458d4385c31b3fc3111c934441358549b318c493ff220fd2076f7 task_094/solution/code/raid_recovery.py +019baeba79eee0049f0880a1f2e85b3c8a618f67b758d983f03c0d46815e243c task_094/solution/solve.sh +cb8850a765fba30185914829976e974e0e66cb7c13da12850cfe9e515c38a221 task_094/task.toml +804c765b46c766e1c0279498df876abaecd3ee84c91c8e130aec459434fc6ad1 task_094/tests/script_checks.py +3586f60394422298e05de9b3437b7e909697b1347c2a58dfa15d61e6882704a4 task_094/tests/test.sh +3b1ad47688336c8f93d1052d9cbfadfd92385b2608a8ccfb15fe68083beacf71 task_094/tests/verifier.py +6a8ca30ff30af33f50242f07f0bc9f3dbc93ddc3c8d46286bad93d2cfba5d0d5 task_095/environment/Dockerfile +e89932d5c409c9bc7376550e5cb776866342d19c1ada7659340678a71812a981 task_095/environment/code/data/cluster_events.csv +6fb17704882480d9cc939c501f506c35a4179c5bf37f09adbea662fdfbe169bd task_095/environment/code/data/node_1_meta.json +a561d5b1fec94e6aea02d903ca7df1dc8d3d8ee4d690a0897e1e27136a3454f8 task_095/environment/code/data/node_1_wal.jsonl +87501f12e73234e005cb4e5b9a263e033b8b6efe96e3074e902df3f14531dabd task_095/environment/code/data/node_2_meta.json +21b9e75eb0aa29314778c0013501e0edec190ae097a35727762ccab4316fe830 task_095/environment/code/data/node_2_wal.jsonl +54d262fbf4fac74a5891fb850cedbd0fbcf8997598856ae37ed99bacacf81f73 task_095/environment/code/data/node_3_meta.json +011ee65c619ec8be3c0e8f91ae5ba22176bae5912a448fc9dea5282e1b80c30d task_095/environment/code/data/node_3_wal.jsonl +6ab0069a4d96f47a9c161db19b66f475ba807ee981b5e711998fbfc0f57ed43a task_095/environment/code/data/snapshot_manifest.json +89247bbb7525d1d5eeba3a1a061bc7688b0e7ace09f4be4e85743a92fefbb868 task_095/environment/code/recovery.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_095/environment/docker-compose.yaml +e83fc8c70f7327a5c601233caa4081927de512cd7e8d0d5db14cf60cb66b0426 task_095/instruction.md +69cffefb5ba6b18e15b4c182f5e353edd160bbf3579d02b18fa9bd856425f679 task_095/solution/code/recovery.py +c30cc1959113fb84ef1bb24f708de11dfe18e08ba7f8ca7ee3fac524b5667274 task_095/solution/solve.sh +cb8850a765fba30185914829976e974e0e66cb7c13da12850cfe9e515c38a221 task_095/task.toml +1ce41d8832eff0ec84e0284f6d72324eccce5484160a541e66a875f9643aa152 task_095/tests/test.sh +605a5f532ef005b52e205d9c88b0fa220b28fcf3758ea873da8d33d93ebdffbc task_095/tests/verifier.py +a0f246cd19ed54cc530c69a2194e2fe1ba20b0d635565ae95d06f5727b537639 task_096/admission.json +029926e818637d81434f04a6aa6944d0b1601225221010d748c45caaa1b8dbed task_096/audit.json +336beff29c091776f524e86c0b7fef316f18fed11e4e0d6d269b1164880c3e06 task_096/environment/Dockerfile +82c5d683d0d1d7efe2750933199e352e5f073aae755f7a4d40e9a88266a12480 task_096/environment/code/.infcode/settings.json +34dc578b265045c4f1c4650d027b9db186978113b8b08a2ce7dbb070641a892d task_096/environment/code/README.md +c7b2612ea5ac721ba9a6937e7cd728afef957f2ca783796e477a79188382391b task_096/environment/code/review_hook_spec.json +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_096/environment/docker-compose.yaml +a9d9452ee9a0dade2050aa9782deac34c231b5280115f429019a68f54fff80e7 task_096/instruction.md +676531fbd326ee5c1c0cf4182407dd6590dea104193ed0c186b5ec10891b791f task_096/provenance.json +9079286606ecb6f522b9050341a67887a81a25482db7f3a5df0cfb4a7a7de149 task_096/solution/code/.infcode/hooks/confirm-stop.js +abee0c341afd84fa3c333f31733d64b7c0888430aad6f8c3d7bcdd7ed5d8fe28 task_096/solution/code/.infcode/settings.json +c7b2612ea5ac721ba9a6937e7cd728afef957f2ca783796e477a79188382391b task_096/solution/code/review_hook_spec.json +4c540c7c31280f75dc5f107b510dd5f8d3182448d01a31f4300ac9f2915bbe53 task_096/solution/code/tools/install_review_hook.py +53531d7ef37190a74cd788d82a4958829110c9c7a7da5b6cb0236675e51ad86f task_096/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_096/task.toml +abf14918a09224da583ca0c682c87fce09eaaf4aadbb19b5e03e7e14499882d5 task_096/task_meta.json +9a056f837399cfbf4a5b02408f77439ce2b06bb2159fc7c3f7cc70cfe8c2aeb2 task_096/tests/review_hard.py +a0ffd9d2388bc391bdde347795c0b84310bf09362aeabf80679f3bf4e7c04afc task_096/tests/review_legacy.sh +939c60cf5c1fc2d773b9669644ddf8e8a978aa5dceb194e64da33e6b5510c40b task_096/tests/test.sh +b6954dddfc6f11d1db20413283ef7f98d47a14b577cd01f732001e4e2e2558fa task_096/tests/test_behavior.js +efb59bfb161a6cd37862edc74dcdd5c1c35b55f5bcac360ead2dd21c071aecc1 task_097/environment/Dockerfile +0df654bc4d3bc683ae285710a7909d16bf915bcfabd19c30ee20bcf703dcef6d task_097/environment/code/config/config.go +66d42c6ff9fbe1194c3eefef0cc03c68814d7136b57b4c73af736bb50eb7981c task_097/environment/code/go.mod +c8af38928d9fac67c1d92cfd80fdd3111f23fc2b8a9f10f9016e757ee777dc6a task_097/environment/code/middleware/auth.go +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_097/environment/docker-compose.yaml +57bacf42922e43ae02a25f792b25da27afc89e194e700f544b3f0b78f87bdeeb task_097/instruction.md +ab5573dc36d19d2e27a933c53c7449480a0c9e9703fcc9acffbfa1e9a80b8c4b task_097/solution/code/config/config.go +66d42c6ff9fbe1194c3eefef0cc03c68814d7136b57b4c73af736bb50eb7981c task_097/solution/code/go.mod +048126e06869e398ac007b9bc9faa41d879b796ad013076cd0f57607cb309f9f task_097/solution/code/middleware/auth.go +811192de1c3ebff8e841a63adcbc327752c862561b4f3744d9e9a4f41a12bef2 task_097/solution/solve.sh +cb8850a765fba30185914829976e974e0e66cb7c13da12850cfe9e515c38a221 task_097/task.toml +aa95049b9a90bb8e49995ffedafb51c7c5c4d0f6d63293a15c9b5f6881dcb694 task_097/tests/review_jwt.go +c540a92996bd719435db4919309eaaa745cb22c9d3328c754ad72696d0683a30 task_097/tests/test.sh +b612c10226ec3a5c489c533f3df0ff374a53bd8aa74f8bcd00dbdb81efcb8e0a task_097/tests/verifier.go +c2123d92c61fb48f0e2f435cd2925b7b69084a171d5a613fe78f3e14e27240f5 task_097/tests/verifier.py +6de2be089130fad84058eb05534090b452a190fbd8e256c80dac4a9c186c2b29 task_098/admission.json +d49bcb00df85c2225b3caca877fc6174fc4584a3cb809fdead69103cd2363cef task_098/audit.json +26a3545853623005d1d5b3b4e539c326e15ac4e8ceee32e6d5448ef54a67b88c task_098/environment/Dockerfile +15b4df36864ea0e48a76323b47abedeea6d98c4cf18774a357e0613a1496cd6d task_098/environment/code/README.md +1e553fe8081a227e10524a29b66f06c38eba7b742841fe8f669a08f1f3e306eb task_098/environment/code/review_hook_spec.json +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_098/environment/docker-compose.yaml +891e52818fb9f4064f8a00c53debdb9d394cb3388edd72aa208ff31a2e4f6db4 task_098/instruction.md +d657149bb614d885d53518829ddc81871387c2e780afcb778fb031c95d83f3d6 task_098/provenance.json +156b66df749e4c9a05b258de8430429afb98158e95dbb801ba982c308fdef3cf task_098/solution/code/.infcode/hooks/tc02-bash-matched.sh +fb763faeb86ce20a39da4b6ca7e2bb1eda92cf35f33a650a91977f5849fbe383 task_098/solution/code/.infcode/settings.json +1e553fe8081a227e10524a29b66f06c38eba7b742841fe8f669a08f1f3e306eb task_098/solution/code/review_hook_spec.json +86f9c6e959c06aae436b761afd546da9a170f4c3246841a6dbf16d8c3b657d01 task_098/solution/code/tools/install_review_hook.py +00ba3d78d9c4a36840af2e76d849b98f91c8bb78e8fb8d3b46d7fa7783db946b task_098/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_098/task.toml +dd6e2a52bc1423475e0de90458ead6af914c3ae167e1b1f7b137c38761a3a135 task_098/task_meta.json +82415b09849db62ad1275c8040f7459d5e81f2de5e1063628e199229c7146ec5 task_098/tests/review_hard.py +67d65cae84ed51131c15a7439d5992afcf30140631574480268d088646c9a0fe task_098/tests/review_legacy.sh +939c60cf5c1fc2d773b9669644ddf8e8a978aa5dceb194e64da33e6b5510c40b task_098/tests/test.sh +75197e2d4750969209ff870a7b02b0ab910d3a67dd7b92d0cd929ffded85547a task_098/tests/test_behavior.py +0b07ee95269aa87648f0e7b99ed102b2334ab2973be231bea7ffb4ab0a6f940c task_099/environment/Dockerfile +711b0d7177f831d760942c21358f8f61a21d190221326fd5e7670809eea81cd3 task_099/environment/code/backup_manifest.json +cae662172fd450bb0cd710a769079c05bfc5d8e35efa6576edc7d0377afdd4a2 task_099/environment/code/backup_repo/auth/auth-full.bak +ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad task_099/environment/code/backup_repo/auth/auth-inc1.bak +79ebafeb16653453617d8d25724ac076b45f68f810a8599679d95207e7fc9685 task_099/environment/code/common.py +2f05d4b689d270cafb02285f35f44866f7dc8a2d368a3f9d1124373eeab31fb1 task_099/environment/code/db/db-diff1.bak +ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad task_099/environment/code/db/db-diff2.bak +cae662172fd450bb0cd710a769079c05bfc5d8e35efa6576edc7d0377afdd4a2 task_099/environment/code/db/db-full.bak +57ad67f5c3dcc48dc462886fc9b00115cf2ca979f6806e825d6e1abfb23dee70 task_099/environment/code/discover_backups.py +57ad67f5c3dcc48dc462886fc9b00115cf2ca979f6806e825d6e1abfb23dee70 task_099/environment/code/generate_report.py +2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881 task_099/environment/code/order/orphan.bak +57ad67f5c3dcc48dc462886fc9b00115cf2ca979f6806e825d6e1abfb23dee70 task_099/environment/code/plan_restore.py +59b1f8964ce0a56f2348f1e28253724536893b61b9e54b4be5e8f91ff076dfb7 task_099/environment/code/previous_restore_log.json +f97c66b4074794a51fc5c0835687366137c0e05cc3b6e59ecdabf238e009766d task_099/environment/code/service_dependencies.json +57ad67f5c3dcc48dc462886fc9b00115cf2ca979f6806e825d6e1abfb23dee70 task_099/environment/code/simulate_restore.py +2e9a73bbb4bc11f717f3d0d769d660f59ab3cf6ecdd24d28578d385035f9b8d6 task_099/environment/code/sla_config.json +57ad67f5c3dcc48dc462886fc9b00115cf2ca979f6806e825d6e1abfb23dee70 task_099/environment/code/verify_integrity.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_099/environment/docker-compose.yaml +1054701a88a4a81c39c9e8e3efabc69bfa3e4ef71d23eaeb7069093270167027 task_099/instruction.md +fc7ae7733d3ef89dba1ac9bb04bfebfb4934a305b398ad4ce76f61fd7d524117 task_099/solution/code/common.py +44069cac6bb9a3951747be600b592268083c7007c441d332b698d421ee188741 task_099/solution/code/discover_backups.py +44069cac6bb9a3951747be600b592268083c7007c441d332b698d421ee188741 task_099/solution/code/generate_report.py +44069cac6bb9a3951747be600b592268083c7007c441d332b698d421ee188741 task_099/solution/code/plan_restore.py +44069cac6bb9a3951747be600b592268083c7007c441d332b698d421ee188741 task_099/solution/code/simulate_restore.py +44069cac6bb9a3951747be600b592268083c7007c441d332b698d421ee188741 task_099/solution/code/verify_integrity.py +d6befbf315cb76c5f44bdfce45a2df0d08f6453e1b30471ec10095b89410a238 task_099/solution/solve.sh +cb8850a765fba30185914829976e974e0e66cb7c13da12850cfe9e515c38a221 task_099/task.toml +fd16f118f50c8c839f569976c57571c765c4957d4f4c374cfb7c94104ae2939d task_099/tests/test.sh +596c11f468f46dfd1925742671a46d7db8cf0f723c5caea675e64f51baabde79 task_099/tests/verifier.py +1b191560a57ee653ae19ac66cd69217a3b500f5634db2a421b7bba8bc09343d5 task_100/environment/Dockerfile +a5f9c9da8aeaff58336ae83c80011298f5fcc9986478dd45669acd9b99f1c3b4 task_100/environment/code/fixtures/sample.sh +60a492f32b7870d7bef8191693c998515052c60d4b7e2e0720884916c4812cc8 task_100/environment/code/harden.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_100/environment/docker-compose.yaml +b3b2a85961aec506efbefdd08b95873edea76922eaedb2ddb063b979f1987c8b task_100/instruction.md +0058949573cbd85fae4555dff3da85a7c60d9ceb81dbda7125e43a420ca86383 task_100/solution/code/harden.py +dbeff841b765c64212436ee30724e9d3c73cc6f69a26e6b885e0bab67748d74e task_100/solution/solve.sh +cb8850a765fba30185914829976e974e0e66cb7c13da12850cfe9e515c38a221 task_100/task.toml +acaf6410c1b887b80733ba64c6d1a4938a167b2a9bba3783b1c4f4383d92301b task_100/tests/test.sh +9791d883675341ccd8571c490cf37e86f3cb9f17aaa809531f86392d0c4c24e5 task_100/tests/verifier.py +039c04abc160826678d20f2076e663ad5b37f8120e03332c28fdf6eb9279f015 task_101/environment/Dockerfile +92303b99500b8640559987b6260fdeb08300c31ed241dc56eade7968938f3646 task_101/environment/code/go.mod +1de234398f8f7cc85f5b2ad566a3c70216f5a69c171e1e6a0007a295e340bae0 task_101/environment/code/pool.go +de21aede58847b74b88e1cd2f6f26bce51176a703d336239d0bf14144d7c902f task_101/environment/code/pool_emit.go +23518195ce700e1aa5e27c4c141214c0e7a5c39b9cfaede29697f5a110dc7faf task_101/environment/code/validation.go +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_101/environment/docker-compose.yaml +7516697357800e72331a5a8581c4e693276f41fd24d743f7bbe0f2a75fb7962b task_101/instruction.md +92303b99500b8640559987b6260fdeb08300c31ed241dc56eade7968938f3646 task_101/solution/code/go.mod +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_101/solution/code/go.sum +eb575eaa2addbfdfc15aec308b0d74c27dd5a1f5a28c734b602b49eb7e3e8872 task_101/solution/code/helpers.go +e72183307f6c799d0209bbc6008f565e9483fe18f1f9d1615eeab4e8b6df3493 task_101/solution/code/pool.go +25db90550fbaffc4513d744f147ffba6178d2e9404aae4b3b6f93c485adfa88c task_101/solution/code/validation.go +811192de1c3ebff8e841a63adcbc327752c862561b4f3744d9e9a4f41a12bef2 task_101/solution/solve.sh +d927de65e9460cc75089b3f6bab9ad56df12871469de8b6ef3dba4c6438e0708 task_101/task.toml +096bb0fc39b63502abb613dd41570ec045020e019e595de81b2b3d05c92020b2 task_101/tests/test.sh +2bd79d2c3533c89ed82d453a090e403e41f000dc3f81ebdba4d81dc2f6fa97d8 task_101/tests/verifier.py +1a9b7e2498050264b73cab66bcafb07bd9e32ad4b1ced7711a480a345b778a76 task_102/environment/Dockerfile +3cd53bbb78347b975194da06e6495da6271214b1302dcab474e8122810285322 task_102/environment/code/go.mod +608486ce2ecb615784ad890e8b77da8e0af8008ef9e90fd4b0712b91444bcaab task_102/environment/code/util/controller/compat.go +d0308af4545627022a452ca1d272e561ca0a3f4a07be90fbef3237a58694c73a task_102/environment/code/util/controller/delete_response.go +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_102/environment/docker-compose.yaml +ca98edffc67b38899d65f16530fcb0f1b107a3fdbbfd1360cc6320cdfa7edca9 task_102/instruction.md +3cd53bbb78347b975194da06e6495da6271214b1302dcab474e8122810285322 task_102/solution/code/go.mod +ed18621c54268c2527d8cd76520236fdaf431e9713d876158a2aaff1c1e731e1 task_102/solution/code/util/controller/compat.go +23ed4b877c8b03b22aae173a051fca015120bc8e7d24e6d72af99c98b6924549 task_102/solution/code/util/controller/delete_response.go +bb5fe59e9db8d1d217cfce67a33bf9e3c0e4fa9a93bf98bffabf2df5bada8bb1 task_102/solution/solve.sh +d927de65e9460cc75089b3f6bab9ad56df12871469de8b6ef3dba4c6438e0708 task_102/task.toml +119ff915f4c7d54eb37b26a45bf613f75febddee58c2e7e28ca6353157d17037 task_102/tests/test.sh +b75f5b79fdeed604123f2c8d7a6caa830730f8f28606d2b38880b237cde63a26 task_102/tests/verifier.py +d4f9500edcc55d6a0a5a37c915173043c1fc93402ce7e8222f877b78e71b8c01 task_103/environment/Dockerfile +b25372d628c9279b9185a0d276d522828a286305c5a5df7a84208a8de8b7eed5 task_103/environment/code/Makefile +5e0ac0cacf5020ac568da7bd690adf630629c73db6428fdbc6864236adf5c359 task_103/environment/code/include/allocator.h +973d55ce7fe458966c2527fa91ba601893d499ad7678ff67e079e0f002098c70 task_103/environment/code/main.c +2057a6985237d955de8fddc5269fb5ec25c2bb7c69013430986e5f2225e4a42d task_103/environment/code/src/arena.c +161ad82c04974cb3f868c5e030e456e5762aab44a9f172a2ccb4e0685813c1d2 task_103/environment/code/src/coalesce.c +1769182d128acb2ca1dffaafa5a8682eb11dc80389ae58794dc834773c020248 task_103/environment/code/src/freelist.c +8941c697b00cd9956dad7dff5633f27aaeecca34c9c9ad205037b85576814a18 task_103/environment/code/src/internal.h +f3c7bc11fb6ba392c887fd6302a62a0e5f17fd8325b68fb280d2336d116bd23c task_103/environment/code/src/pool.c +98a23efd20cf96aeb1526bdc15e95c192ca5d636e00f99f02e21fbf329b0e399 task_103/environment/code/src/stats.c +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_103/environment/docker-compose.yaml +01402b32d1a9d5d293ce9e2897135c5f1a42b08ac4ad49efa77f8558405f2763 task_103/instruction.md +dbd41c8ff505c2fec51c1857548d81a68a161f81522b53fffb4136f961176a16 task_103/solution/code/Makefile +e9b012d3743b0a018fbcca998970b14457435103203a1cc90dac177b6e21da7e task_103/solution/code/include/allocator.h +a92510a613c700bc98b8be370beb3948a356aead3f979fa56b05fe21b233d560 task_103/solution/code/main.c +e672636f764ea87679a47c1fe4047e26c7ef9ced14fca06acc268b8f9e42d43d task_103/solution/code/src/arena.c +8ecd6c239ec4eb66fc3227e9b9dc86c9ea3df2c0b2ccf19dc5c29f6830612bbc task_103/solution/code/src/coalesce.c +ce7869c55851f4aea8ff13ce2566e79180ca517631d1df75dabb76cbcfdd667e task_103/solution/code/src/freelist.c +f0926ab32736798b637955380c1e5f4b4a2309c8f6398f2e3b4710d8e5f1a3e2 task_103/solution/code/src/internal.h +e5eed3584ca1f94f2a135874924ed8abb34db7dfceccded7b67c26cc6653b91e task_103/solution/code/src/pool.c +7e85ad38b77e52810454137a6ee6f9e426dd95faec4b2cc96583effb04437535 task_103/solution/code/src/stats.c +8db1233ab207d9c61fc2e77108f6492e1cb72953c0e94e7dacc2e18aa7ad144e task_103/solution/solve.sh +829431de0754257f794283976e4e0c4106142a70164d60c9e5e44a8546d47c00 task_103/task.toml +119ff915f4c7d54eb37b26a45bf613f75febddee58c2e7e28ca6353157d17037 task_103/tests/test.sh +0dfcaace6fbee351d76451abc682d0ffe8631d82f0bf4e381859f352463b658a task_103/tests/verifier.py +f8fd6bb7be1f20c7457c23f06cb8d8f99ea91ea13b00f536eb97dfd0bc17ded5 task_104/admission.json +fe986387523789829a6b93352cb08cbc44a588038761905b22e6ccfc2159dd44 task_104/audit.json +90fa18be359c95ddf76d8439e36f52ae6427b41276df0b55db01df17480b32df task_104/environment/Dockerfile +06864c4dd7557e9bbbc94ca5ce9c7b1f3a6245aae135e26bb2da0a07bdb76aa8 task_104/environment/code/.infcode/hooks/log-read.js +12d36640a1ef9bb0e55d4b07f3854b089c55fcc032b0b890cc2baa8effe9330d task_104/environment/code/.infcode/settings.json +012dcff01e82040fb530554e89f7c3fc2f7f6960447966d350ebf56ad8b6fba1 task_104/environment/code/review_hook_spec.json +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_104/environment/docker-compose.yaml +35da7b24db4b4fc93c1b9c418cb22c1bc8e2493c2efef990638086b36d571f0f task_104/instruction.md +1a9fd117bb344404c53b3402d6a293d252624e59919394b98f88a04e57bb31bd task_104/provenance.json +fc9802421f4a7d24b02de2644bf9ec58a57e35fbaa3e92d729cec06c46910f78 task_104/solution/code/.infcode/hooks/block-rm.js +06864c4dd7557e9bbbc94ca5ce9c7b1f3a6245aae135e26bb2da0a07bdb76aa8 task_104/solution/code/.infcode/hooks/log-read.js +119cf81f95a28981c0f5c015f031ec8482fe9c51ab2c03aab2d0b6abf0becbbc task_104/solution/code/.infcode/settings.json +012dcff01e82040fb530554e89f7c3fc2f7f6960447966d350ebf56ad8b6fba1 task_104/solution/code/review_hook_spec.json +06ee618358b609235218b3993fea1522d667e07206c54f0f456ff46bb09cbd3a task_104/solution/code/tools/install_review_hook.py +72f7288ba2eea2a043f5192d7cb4d07a5842b31a45226c0b4de8d9734431cdcd task_104/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_104/task.toml +1e4d49b413e78cfed6e041790f3495970394cc9d2dcf46201966b7aaf242ad45 task_104/task_meta.json +1bfbf6109e89defcf2320991c0389f4c52ecbe1548e8cf03942da8bdc2d0f3ad task_104/tests/review_hard.py +72db4d637d484354c55e2fe24ec1afa06336054db40637912c5c8d8e094db800 task_104/tests/review_legacy.sh +939c60cf5c1fc2d773b9669644ddf8e8a978aa5dceb194e64da33e6b5510c40b task_104/tests/test.sh +ee55e13454c8e577c5c55fdb34199f6da9172c427c585a051cac71404a83fbe6 task_104/tests/test_behavior.js +70a51539aa0ff6d3b7bf36dd88f608e5d01323b910e788f8f7570454025f4d51 task_105/environment/Dockerfile +62bcb2299c16b94db6555e1975c882b7ee49d03db5857d31cd73dc4c2209513f task_105/environment/code/pom.xml +a33d92efc95e861af82128d26c10e4049b8866c9103d80c250c9df58a163434e task_105/environment/code/src/main/java/com/mayfair/wms/AbstractSigningHandle.java +380aba062df22c3f3e24b5a65f314810ddb4fa19b993e773b62fec8d62b86833 task_105/environment/code/src/main/java/com/mayfair/wms/DefaultSigningHandle.java +7cba03a066180a88b09ecd691c63fe53de47d18a628245ad7f9dace5048ce614 task_105/environment/code/src/main/java/com/mayfair/wms/Good.java +b5008f679600c5d9475d17af43e66a9880fce0e7eaff58c56c8a1e512d8af9f6 task_105/environment/code/src/main/java/com/mayfair/wms/ISigningHandle.java +71b205d849275dca8f2e1cf5d42eadef24b41dc79830c264cfd7634e9591b13a task_105/environment/code/src/main/java/com/mayfair/wms/InboundCoreBizService.java +fab619bbf6f4aee8a9d519861d03e3bbb6af8e5074ad8c920115ff07c5ae2d90 task_105/environment/code/src/main/java/com/mayfair/wms/InboundCoreBizServiceImpl.java +f27ea2628666d877e733aa90efcada02e7de2b1afa428ef3f5c6a4f7fe9c7335 task_105/environment/code/src/main/java/com/mayfair/wms/InboundType.java +373932d644aaa0561684f8186dd16604f9eb2d128bd21a69a0b8d596e9f23c8c task_105/environment/code/src/main/java/com/mayfair/wms/LocalPurchaseInboundBizServiceImpl.java +506003a95a48e051997576337daedc6887b2e6cd397cd6afdc58ad3fd89f71c1 task_105/environment/code/src/main/java/com/mayfair/wms/NormalSigningHandle.java +b12268fcc8f9f8418bc5581dbfcd7141fcf6c8a701ce99ab67950d2683309710 task_105/environment/code/src/main/java/com/mayfair/wms/PackageRecord.java +9fc9871ba299abd764d9ad1fb2eaea5493eb1587d8239002bc8575dce9cf0d33 task_105/environment/code/src/main/java/com/mayfair/wms/PutAwayTaskFlagEnum.java +d7a69cedbd09d712d339051b702e787a2c6a52e670d7d5ebc267e0d13574d8bb task_105/environment/code/src/main/java/com/mayfair/wms/ReturnedOrderType.java +10071f21b51671f8a1a1bdb5a335c5d739480a93c800002510c8a356ea822b09 task_105/environment/code/src/main/java/com/mayfair/wms/Runner.java +f3b628152fdf0c2f6b7e045655f81497a178e55c75ccb3dfb91ec062a902b981 task_105/environment/code/src/main/java/com/mayfair/wms/RuntimeConfig.java +048a02cf78d62d3e6b43714c7630dfed3d7ab7c736ce8d24226e9357dd63586e task_105/environment/code/src/main/java/com/mayfair/wms/SigningFactory.java +14075f1ce7fcdcd2ecfe13c34326a1a817674c4704951cda9f48c1e978d820ac task_105/environment/code/src/main/java/com/mayfair/wms/SigningRequest.java +63add82997109d498724b12a32761df08318e712768505d412c04db968f2efae task_105/environment/code/src/main/java/com/mayfair/wms/SigningResult.java +f22bc0e8f6acc4f609b2fba3a5a2e9c55d9e6c8ba6a63b0dd7ca69987938cb6a task_105/environment/code/src/main/java/com/mayfair/wms/SigningTypeEnum.java +7ab4ccfcfc58ab6a5eae529f62ac3e884c1b2e0b194452223012149018699707 task_105/environment/code/src/main/java/com/mayfair/wms/SnapshotTransactionManager.java +a9d5d2aebf9311306252e7082b968baa37d71ac7ab6d64dcd8861fcab3870ad5 task_105/environment/code/src/main/java/com/mayfair/wms/Store.java +335775cbbb9b364231bde892785902dadd8304cd4425549e3096556d2b609359 task_105/environment/code/src/main/java/com/mayfair/wms/Task.java +509b11edc4beb62bdd33a7c5716326bca56748911f1410d185e5a2a7f01a17c9 task_105/environment/code/src/main/java/com/mayfair/wms/TaskConfigEnum.java +e695ad83ac7469bc67ad2e68206fc90ad92770e6597b41899370ea7b108c8933 task_105/environment/code/src/main/java/com/mayfair/wms/TaskDetail.java +c3640fa7a7fd86ad76d8e7610eeb019e59d933e4685463fc1c3421f33060cedd task_105/environment/code/src/main/java/com/mayfair/wms/TaskOperateCoreBizService.java +bd7059ad91530b7db32e000f93824b0f1933d1477f7f360aa89375cb83442b0e task_105/environment/code/src/main/java/com/mayfair/wms/TaskOperateCoreBizServiceImpl.java +a433e9e53d1e894e756d08be0154c6bd9b30738899ace3c497ec98c0043b4089 task_105/environment/code/src/main/java/com/mayfair/wms/TaskTypeEnum.java +9055a57d32842ca139ef80e96a8c96bf0e896f9a82b4a5f2ea2cc4a2075d1f78 task_105/environment/code/src/main/java/com/mayfair/wms/TransferSigningHandle.java +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_105/environment/docker-compose.yaml +db62bbd25d0efef028ce678b657fdb790a83b1b4717b7b2ff0f42e04b1879075 task_105/environment/settings.xml +b12f59ad15164f9e12e5ac80c749df6f4c05eeaeddcc7dadb9fdf802da5f93db task_105/instruction.md +62bcb2299c16b94db6555e1975c882b7ee49d03db5857d31cd73dc4c2209513f task_105/solution/code/pom.xml +e36a728cd9c898b2b91fe324f56d3389e2aa10093b62191daac7ccc7cdde7ac4 task_105/solution/code/src/main/java/com/mayfair/wms/AbstractSigningHandle.java +fd5ffbcf0175e5dd7f0a49521ab31bf821aa6a1712d924fce2b2b3de2d5597be task_105/solution/code/src/main/java/com/mayfair/wms/DefaultSigningHandle.java +7cba03a066180a88b09ecd691c63fe53de47d18a628245ad7f9dace5048ce614 task_105/solution/code/src/main/java/com/mayfair/wms/Good.java +17ee104449a74d13c8a8e1b198db1bd30b29ab2e9786a07a3f0d6160b509cfc2 task_105/solution/code/src/main/java/com/mayfair/wms/ISigningHandle.java +57db0519a7669c05aae7afacac2d0b22df3bda776bc4c6ba4d3b1cbf514c1b28 task_105/solution/code/src/main/java/com/mayfair/wms/InboundCoreBizService.java +fab619bbf6f4aee8a9d519861d03e3bbb6af8e5074ad8c920115ff07c5ae2d90 task_105/solution/code/src/main/java/com/mayfair/wms/InboundCoreBizServiceImpl.java +f27ea2628666d877e733aa90efcada02e7de2b1afa428ef3f5c6a4f7fe9c7335 task_105/solution/code/src/main/java/com/mayfair/wms/InboundType.java +8b7f83301c39a7cb495ab45143a9acd35d71ee78f928fec1338af1a1b0956778 task_105/solution/code/src/main/java/com/mayfair/wms/LocalPurchaseImportSigningHandle.java +6f1acdd2bb1fa5b1986d5f8c61ee2a1cb68393e1c29882aec4db75e35fed1268 task_105/solution/code/src/main/java/com/mayfair/wms/LocalPurchaseInboundBizServiceImpl.java +fc8df59a4d3c99de099a5f7d6e8a7d92fe0bc8197dca44d5e5eeab66be325d7b task_105/solution/code/src/main/java/com/mayfair/wms/NormalSigningHandle.java +b12268fcc8f9f8418bc5581dbfcd7141fcf6c8a701ce99ab67950d2683309710 task_105/solution/code/src/main/java/com/mayfair/wms/PackageRecord.java +5c66c6f390621de3a019fbf04704904f95bd2442a57f4ebc842afe4ad342a82e task_105/solution/code/src/main/java/com/mayfair/wms/PutAwayTaskFlagEnum.java +d7a69cedbd09d712d339051b702e787a2c6a52e670d7d5ebc267e0d13574d8bb task_105/solution/code/src/main/java/com/mayfair/wms/ReturnedOrderType.java +f3b628152fdf0c2f6b7e045655f81497a178e55c75ccb3dfb91ec062a902b981 task_105/solution/code/src/main/java/com/mayfair/wms/RuntimeConfig.java +17b882f564ceca69629c89226aba5eb812b3844dde82ea060bc452f2113fcdc7 task_105/solution/code/src/main/java/com/mayfair/wms/SigningFactory.java +14075f1ce7fcdcd2ecfe13c34326a1a817674c4704951cda9f48c1e978d820ac task_105/solution/code/src/main/java/com/mayfair/wms/SigningRequest.java +63add82997109d498724b12a32761df08318e712768505d412c04db968f2efae task_105/solution/code/src/main/java/com/mayfair/wms/SigningResult.java +481b5bb1efd32d907dad9ab557667b32e8a6c57d14665d183177a630aa78bd9d task_105/solution/code/src/main/java/com/mayfair/wms/SigningTypeEnum.java +7ab4ccfcfc58ab6a5eae529f62ac3e884c1b2e0b194452223012149018699707 task_105/solution/code/src/main/java/com/mayfair/wms/SnapshotTransactionManager.java +a9d5d2aebf9311306252e7082b968baa37d71ac7ab6d64dcd8861fcab3870ad5 task_105/solution/code/src/main/java/com/mayfair/wms/Store.java +335775cbbb9b364231bde892785902dadd8304cd4425549e3096556d2b609359 task_105/solution/code/src/main/java/com/mayfair/wms/Task.java +ff15c1629aa3f653303a708ffabf4a30222623fa4fb4a2ca1103b46c9b29d098 task_105/solution/code/src/main/java/com/mayfair/wms/TaskConfigEnum.java +e695ad83ac7469bc67ad2e68206fc90ad92770e6597b41899370ea7b108c8933 task_105/solution/code/src/main/java/com/mayfair/wms/TaskDetail.java +1d9772cb4db7e46159f171a4f2f53862212233483b60613668f5a91f9fd76fc7 task_105/solution/code/src/main/java/com/mayfair/wms/TaskOperateCoreBizService.java +bd7059ad91530b7db32e000f93824b0f1933d1477f7f360aa89375cb83442b0e task_105/solution/code/src/main/java/com/mayfair/wms/TaskOperateCoreBizServiceImpl.java +a5268193cdb4b468114c5343b0feedbef789921cfb05ad85edcb08d07f53de39 task_105/solution/code/src/main/java/com/mayfair/wms/TaskTypeEnum.java +36f261335480fd845d9feabee75c6272c74c8e28e9b8a17c1a709b627696a004 task_105/solution/code/src/main/java/com/mayfair/wms/TransferSigningHandle.java +dad8cbae454710fb33b2552229c2d5dc5cd2d8221968a0310e972cc676a19aae task_105/solution/solve.sh +5baf1970d6ac12dab20cd195c415bf9df82f8c85b9d34f294b7a7ecf1e926e05 task_105/task.toml +9c842112af8f358a37a1bf874fa19ba2ddcc5bcb7d21e27ad77a488b7c98afea task_105/tests/Verifier.java +dc92ab790e81b73780b5ae25e5226a62bbd03a9636cfc08975469b1009d154b7 task_105/tests/test.sh +64f740eca92fa234b69ddf54acf82bf1fae28db0af2a68fdb10ddbf3695b6752 task_105/tests/verifier.py +e2cfa2b1bd9094edbc238e38a59a5fa3d4dc52b44d0e1c4c4d7f2b7cd0d8df9a task_106/environment/Dockerfile +6768b205e53710737e45a5a7bb68d453cf0c522cab79de619f5e324c5e461c0c task_106/environment/code/data/mock_samples.json +ebd2042b2488987284a7c97c7ddebf649c5ae36e9daa8c4793f7f7f75fecc477 task_106/environment/code/index.html +1e9a83f5d4ceaaa2966d95f48a6535bdcdde7532b115c27a080e77b02cff32f7 task_106/environment/code/package.json +e21310d26824b9ddd7abd73d65d5c716d1091d1ff959706e184390ce91f7bf00 task_106/environment/code/src/index.css +40d5e67be165b5aab0b8e6527ed77b7b5fa6438369b7d375cc4ee4abc931a46b task_106/environment/code/src/main.tsx +7da685250bc8e4c1babdc7f9386f5116285f2bb44ee3bc41d9787661d73f59d6 task_106/environment/code/tsconfig.json +2135b388a00990bbc1924abf7f6b42aedccea089ea7504665f175022483cac75 task_106/environment/code/vite.config.ts +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_106/environment/docker-compose.yaml +34ce2ead721835dd6325ae7f65e9c433b1aea5cee94d7cad7376f637b9b5ff2d task_106/instruction.md +6768b205e53710737e45a5a7bb68d453cf0c522cab79de619f5e324c5e461c0c task_106/solution/code/data/mock_samples.json +24b314aff2534d4e56f1fe6b333c8c0f0a5dc56cd00e44eb7264dc353fda3676 task_106/solution/code/index.html +aeced87c26ad9f8d08959a1aaf0535af7a4cfd9895e15dff55c31de1a29e6b2e task_106/solution/code/package.json +fcaf0007d6d1a6024fd9e3dd98a03440cb72a9a34aef1deffaf08be4b967605d task_106/solution/code/src/index.css +8b533e117425b24ad8dfbffda3dd328ac4a97c5140890b39bfaa248c6ff12d96 task_106/solution/code/src/main.tsx +26bd08bc9ad6c5fb82a921c85e62cec62007a7e9af35170ce2e16dac01e16e86 task_106/solution/code/tsconfig.json +2c89d396fa9b72d0675424aabc7cd2c582b5b97719bb5d422600c57d2de06547 task_106/solution/code/vite.config.ts +c35e00a07135354c239dc5bad21a66f9bca5b5a252303620e82bc9a4c2635430 task_106/solution/index.html +24da0b6947920eca7f1870b8df2e5cc61ba0c897b0f901d24a403a9d5387650b task_106/solution/preview.png +42c683bbac81ad22edea940ccb83c9c0a4d9e39e2fa0b3383613731729672dad task_106/solution/solve.sh +2ee5ed017f30a6db134637d1b341c837b01cdf6c6a6d8416cfbbbd33eadc499f task_106/task.toml +fb3ab6d9e0d5da01e6cd5830fcf46381e315f0c5f7c3320216bcf12805f1745b task_106/tests/browser_verifier.mjs +6768b205e53710737e45a5a7bb68d453cf0c522cab79de619f5e324c5e461c0c task_106/tests/mock_samples.json +3404f529820750287af18a9ce28c9b8d6756588f1f8a4133cfab477aa9f1fb80 task_106/tests/test.sh +8e263ecbfd640b00c69a145952aaafdda17e02d425dd41b2672fc2167ef4c224 task_106/tests/verifier.py +a8723c8f16bf2ce0cf3f4a17b4b5010b4e9d274ed1dac09567e03272c669b9e6 task_107/environment/Dockerfile +82b30f144417a072dd354baf0e649de2a68fa6571b11956d4c8d4e9a2b74247e task_107/environment/code/index.html +d620814e8d89c7df01db30439e7f63c16a2d67c70f32929150aa896600ccfcba task_107/environment/code/package.json +8054b593427cc677611fb54cba40ee7ace649287c0d662e2f40952cf6e20f64c task_107/environment/code/src/main.tsx +bc88e8f5ac4a908d4ab78bc136cce17f12131d5eada2b400afde092cc1748a59 task_107/environment/code/src/style.css +ba155bb7f637cf78751e6e3e8ed0e34718fdb0a3c3f64e155942aa762aea7f07 task_107/environment/code/tsconfig.json +2c89d396fa9b72d0675424aabc7cd2c582b5b97719bb5d422600c57d2de06547 task_107/environment/code/vite.config.ts +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_107/environment/docker-compose.yaml +b2e771779464c6eb4bcc20de4d987ce51856c1b2e4d09d57a8ba63b0f1a049d3 task_107/instruction.md +82b30f144417a072dd354baf0e649de2a68fa6571b11956d4c8d4e9a2b74247e task_107/solution/code/index.html +d620814e8d89c7df01db30439e7f63c16a2d67c70f32929150aa896600ccfcba task_107/solution/code/package.json +e74483bf70e219f7fa316c8ec6d6dd76eb29985db57e47e1c169637ba8391eed task_107/solution/code/src/main.tsx +704f46a30a70988afe23f1303f2d25b8c9fc19b5990be6042619690709ce9eb2 task_107/solution/code/src/style.css +ba155bb7f637cf78751e6e3e8ed0e34718fdb0a3c3f64e155942aa762aea7f07 task_107/solution/code/tsconfig.json +2c89d396fa9b72d0675424aabc7cd2c582b5b97719bb5d422600c57d2de06547 task_107/solution/code/vite.config.ts +a62eed5171d5127fd019bca3c34252247c07dde189a5d77b80b74440c2871e03 task_107/solution/index.html +b38328e3a817403adab3886ccb62353cee34ada7abacedc4ce78286d5c9e8e8c task_107/solution/preview.png +39f0a8b6d2651001271ff8b1813b0185af0b4fccad197cde21d688d2eb500836 task_107/solution/solve.sh +2ee5ed017f30a6db134637d1b341c837b01cdf6c6a6d8416cfbbbd33eadc499f task_107/task.toml +eb935277325454e9fe78eb1070ad7a0b86ddff07bde736e87fa23ad01f4602a6 task_107/tests/test.sh +91397182038c1ab3563be8c2de5265493f5e6db1fadb4a1a84407ce34e22e40d task_107/tests/verifier.mjs +f24e7aa65c8bd7441c0f4ff3a58dead0e67894906a23ffc65278ef383698670d task_107/tests/verifier.py +38841cb7201ed54fdd163d6cf9fcb7b58756ecc6fc2d3ab35d14a77938491191 task_108/admission.json +bee18830191b1ad53004198710f72cf4421d429e32cdf4d97946b9e6409c2fcc task_108/audit.json +75b0983daeb843a7aa666d432fb453918adc336878455c4db69c725f146d4459 task_108/environment/Dockerfile +3b10493d76bc45019ba3f654187c135b58c88eb041054cdf8c45f5e98d65eaf9 task_108/environment/code/node_modules/@infcode/icon/dist/index.js +4b75efaa4dd35cdaeaa840c124c61370526d4ebe7369e94d4eb4536966117aa1 task_108/environment/code/node_modules/@infcode/icon/package.json +46fcb124bdc83b0bd376d3b55b66a511bb6dec4e69168a409cd35e43a09c555d task_108/environment/code/package.json +39ec938801f9ae7a5a2d26cc337d61fa2a2e58f262a7245f1c03fbdfbbb38ea0 task_108/environment/code/scripts/start-gui.mjs +7a9c2307d2883acea3d62d642d949b3b07b272ab6341b3168c1c86529cf71e4f task_108/environment/code/src/components/upload/icons.tsx +eadef44ce600213cb996ba59d19ad89c9d0930309ecb1c39fd0b43a203e25e0c task_108/environment/code/src/screens/screen01.tsx +4a0ff2c466ece3015727be5b00bf104e23be9687fa2cde4a8e2d8aa73324b9a1 task_108/environment/code/src/screens/screen02.tsx +d8459c5563e5bda1ffe0ac0e3f05da8f8d13d666880c29dd6f6f645b421ce7fb task_108/environment/code/src/screens/screen03.tsx +b2ac0caddd22f3da70ead457d1c39c0dc18e1a1827de86a170a8d59a2aaf4274 task_108/environment/code/src/screens/screen04.tsx +40d42c092906f12391da1a56549dd2a7a660341bae32dd44aa01562f76f4dd64 task_108/environment/code/src/screens/screen05.tsx +7a565118959e7dee893aeca9e2900de3580c84576847029054e20e49a98ee16a task_108/environment/code/src/screens/screen06.tsx +092e2d9dacabf4ca0d780445f4f1736fabaf59d6b8348dabcf15a4ba2754fc3d task_108/environment/code/src/screens/screen07.tsx +56573b0eefa709e835cf0c0e9f6f96469dae4422477290361ac347b0437fcd75 task_108/environment/code/src/screens/screen08.tsx +56e5809b14aa7a762127a9f75dda22a447b54f0461886bd956a13a2b19ba93f4 task_108/environment/code/src/screens/screen09.tsx +05be90e102419b49b0dd368447529067e03769c043b88975bc6d5e22ea5b2804 task_108/environment/code/src/screens/screen10.tsx +2eefb58b7ac43a571612d69d8f5693530ca314493218d582256acb18e81f48a8 task_108/environment/code/src/screens/screen11.tsx +4427434ea60344fa17db908c8d3d0c6ade3cb1b2d2f651e354f4a255c99c2927 task_108/environment/code/src/screens/screen12.tsx +0b0f488ad0df7d8b3215c5451239bbe0fe03e6517052a3dc3b6621211355f610 task_108/environment/code/src/screens/screen13.tsx +61f6cb3d80ec93b2f126c417da4d1028ca457a82cdea21ddba47b5cf21e75533 task_108/environment/code/src/screens/screen14.tsx +d938b23baca7c8220527bef8f1398677c6d089d8a9c82ffcb34bf66d8d941af6 task_108/environment/code/src/screens/screen15.tsx +54c5b8725124bc674c6d71cf447f20b433f9e4432c23670f5a1ac07610f9fe0a task_108/environment/code/src/screens/screen16.tsx +6e0cc2844c60bfdba40451e131c8afe7f1cf05e706ebcc18493107e7e50b3e68 task_108/environment/code/src/screens/screen17.tsx +dc385c3300a855b6780dfcae38ee3d72b3a7358d0064706cf20f4f30f4dd528a task_108/environment/code/src/screens/screen18.tsx +89fcba26ca9ea7ba2f71130de92e5941b4dad020d5cfaf3564307995148c2793 task_108/environment/code/src/screens/screen19.tsx +b650cbd898ecead144ba1808eb0022535d6f6d4cf5cc98b4b294f9da6d952604 task_108/environment/code/src/screens/screen20.tsx +0d0247b63b08dd2b84d0febcbf6d4c1d0606f73e988d566042f3f5518b7c30b2 task_108/environment/code/src/screens/screen21.tsx +5bc2cd8da4ea0665eabc9265af72458eb44d5b435ba910714ddad0a6fcd30ef9 task_108/environment/code/src/screens/screen22.tsx +beff0886814fc040b171f6bbfefd450f980186cad7900a162aee42e2dd32f49c task_108/environment/code/src/screens/screen23.tsx +8100ddaa559720284a1f6ab80977ce8e016945c125a0b94a682fff07adbad26f task_108/environment/code/src/screens/screen24.tsx +3ff0873a82c421dbe8dafb40efe6e47337db4299721131335b5ef3b1dd4d2b3c task_108/environment/code/src/screens/screen25.tsx +a7b9fc45e6e3061a1ed30a4673625f44f28bd9002537b3bb585124165cbd7677 task_108/environment/code/src/screens/screen26.tsx +285db45b28c49da282b56e4e8c21c5d01299130a4a99ef90278f66413fb42e94 task_108/environment/code/tsconfig.json +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_108/environment/docker-compose.yaml +61f69232d90d16515594025f7be57812a55a81d17da41a8cefb2da81dd50de57 task_108/instruction.md +8024c0bc2abab332e80a10b64a5f8cfd64535257dcdf232583d20cce03d62682 task_108/provenance.json +ade8098a5d96be67c7e33d4b2d5d342c101b2f6da3f1625a06c17bdcf6542273 task_108/solution/code/src/types/infcode-icon.d.ts +688efcc167a9567969e773fba08ee75fd083e5e6a4504cbab3c5a4dec4a34e19 task_108/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_108/task.toml +73549d5bdd16b007bfd4ee417832a890628802a5ecf579489895e14c51861ad0 task_108/task_meta.json +04519455065f0d13a5934f0bb77dcfa626849ee07b8f1be153aa669ae2e1f81d task_108/tests/review_hard.py +965678a9f1553d3c61af4d6742ac8c846d7a7f184126597622b13898d2b72469 task_108/tests/review_legacy.sh +939c60cf5c1fc2d773b9669644ddf8e8a978aa5dceb194e64da33e6b5510c40b task_108/tests/test.sh +2a626bc47cdc9d47aa8248fefb5ca9089ec4039e368b63fc145a0251bc2b18bc task_108/tests/test_behavior.js +46a071e72b1902b4ac3df03dbe105478c7a9a8b9fc5582b652f1ba61ed6d946b task_109/admission.json +56a6cdc0905e2c5afdfd770b0ef7973c51877f8eb841d52e3a1522219e432abc task_109/audit.json +26d1548d427c807fa0bc372c9d1aab539b53a6f390a9690053413fa13eeb3061 task_109/environment/Dockerfile +dafda54eeaef13d200583bf123be94a1103942c6b27bf8c70b91d56c2f809b12 task_109/environment/code/build_tasks/__init__.py +22eb876874b08c4f9de0b3735b7367c0b164cd3b0a5a6aacdbd026d028a81b0c task_109/environment/code/build_tasks/prepare_local_cli.py +acd2b6e32f568009e77a9bb88bd69b20ba2e90c9ea94288d2e17a89e3867abce task_109/environment/code/tests/test_prepare_local_cli.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_109/environment/docker-compose.yaml +957f2237322e05181c51481a7aa1c8c014443d4d18dac3abbc9aaa11292aaa33 task_109/instruction.md +2094226c50bb9b1eccbc2f8ed17210e1fd253968c4d8c80ff5926f01ecc9a46b task_109/provenance.json +dafda54eeaef13d200583bf123be94a1103942c6b27bf8c70b91d56c2f809b12 task_109/solution/code/build_tasks/__init__.py +22eb876874b08c4f9de0b3735b7367c0b164cd3b0a5a6aacdbd026d028a81b0c task_109/solution/code/build_tasks/prepare_local_cli.py +c5319816e93fe96652d56e2f58966490ea4e570179c44c571fb06212ae6726b2 task_109/solution/code/tests/test_prepare_local_cli.py +d60571006b9758f5c0b833b2e05eb2268e429ae0d5de8fed3e25a85f5990883b task_109/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_109/task.toml +da06f1c0257d77950931ea0a4369f43eff4f8ff22db48a18d7db450a9f76fca9 task_109/task_meta.json +b9da5c8aeb3292bf9c63b7d7ef8bb280fd459f5f51566f97094a5fc10e71a0dd task_109/tests/review_hard.py +9c867bbce3f12b5e8bc79bb6eb84b8ef79676a53780110de6f7f952801c2cfee task_109/tests/review_legacy.sh +939c60cf5c1fc2d773b9669644ddf8e8a978aa5dceb194e64da33e6b5510c40b task_109/tests/test.sh +e224e8a79726eab6f1d0b75a0018637fe38c25229031550218faa8d63652c34c task_109/tests/test_behavior.py +19b4896442e8538abbdd9f5f42d325188d3d8d2afd020de9ea338682e0ab5480 task_110/admission.json +15456c795d65fb5698fddbcfa1c106910e4ab6a587aa9db174989a3757dbe709 task_110/audit.json +26d1548d427c807fa0bc372c9d1aab539b53a6f390a9690053413fa13eeb3061 task_110/environment/Dockerfile +115df39c377bb81afa09e2c0fd2ef3c500b27eebe909f19f20dd05543ad56964 task_110/environment/code/data/2.储备项目/teaser.md +4bfaec47c840c14ade1b978bfab3e4154db3ed73c6fdb86b44dd33dd2ec3a015 task_110/environment/code/data/2.储备项目/tle工商信息.json +949f6997f8a171a869435507b76a7138706c773c9a6f6f1c7a5f61093010314f task_110/environment/code/data/2.储备项目/公开信息.md +89db1ec6cd9e3fac6a86175599e9f8a6b24b09f8f0a68f577fed2a9e5b2a3951 task_110/environment/code/project_assessment.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_110/environment/docker-compose.yaml +8de6c280cb3a9a81615d846b44677682ef466c4ce4f6a98764486b86b54d73f4 task_110/instruction.md +4c725242a50606551dbc1258cb08a383e47cfd4c9f700f073b651da2a37ae899 task_110/provenance.json +115df39c377bb81afa09e2c0fd2ef3c500b27eebe909f19f20dd05543ad56964 task_110/solution/code/data/2.储备项目/teaser.md +4bfaec47c840c14ade1b978bfab3e4154db3ed73c6fdb86b44dd33dd2ec3a015 task_110/solution/code/data/2.储备项目/tle工商信息.json +949f6997f8a171a869435507b76a7138706c773c9a6f6f1c7a5f61093010314f task_110/solution/code/data/2.储备项目/公开信息.md +74315de2249f4910e0439ca7b59a0378e81902f9adf83823303470b87ec299af task_110/solution/code/project_assessment.py +26bdef7fbfafad0523bcb6b50e47824a480ea2d206afcc2bdca520a511a1860e task_110/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_110/task.toml +ea5d929d50a2c10ab3f95f7d6ef2f67ee38b5923593ef987bcc7194edc10b6a4 task_110/task_meta.json +43675d13c690c5de1a9e5d13e548c133159b581a35ddabace9cb6b5921488d50 task_110/tests/test.sh +4b5772d06ac0ce3bde0f026fb2812e7322f629ac44aad192590b2ee7be03fcba task_110/tests/test_behavior.py +a204f40f779388cecf03a2078d325405fb82d255eddb241e8d777c64595c7123 task_111/admission.json +1d0503b5dad7035c76dffc004be2d5869dd1845d4703c6a8e824e7e93c09978f task_111/audit.json +26d1548d427c807fa0bc372c9d1aab539b53a6f390a9690053413fa13eeb3061 task_111/environment/Dockerfile +fef6c88d4b688b8fd279c7c3b9e38ed9cd613589e2a9150766fc9892b8be39cd task_111/environment/code/README.md +5fb9b85cdfaae5b88c7eb1a8268bf0f2b17c5aa1df45293eeab5bb3b02482d8f task_111/environment/code/docs/RUNBOOK.md +27db2744b3927852eb72354b9191b6a20762910f51b6bbc6e31891c702cd4feb task_111/environment/code/envs/bsd-uat.env +0cfd723b8e164258e3e84544bc09058346895487d5cc078a590d7d6043fa9805 task_111/environment/code/envs/example.env +7f7c2cc058a55385ec4cb12ffa3384ced99d3232521e0fa31cf55ab15123a09f task_111/environment/code/envs/qa.env +aab1e84c1f9534fb3b4a874cadd4a682ac078494c724d19a544cf603561ec63c task_111/environment/code/scripts/check_env.py +791b2c568bca544d49c5309c25b611826a1cc29b65884a4eb204dd29b92672f1 task_111/environment/code/scripts/envlib.py +58f687739671b0387f93f3940accefdb90049a9cba9cc35c297db6a56b860f39 task_111/environment/code/scripts/render_manifest.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_111/environment/docker-compose.yaml +82bca47a15928cbc653e8c43480f08b00932021057fb27c75c190a42df867766 task_111/instruction.md +fa5dec78a689b82e7eebcbd17b0e55ffb8fa8d6d2eb1e3e830536b1d32f7b46e task_111/provenance.json +e2a784e51845730758ad08d47a9f7b02b7d3e3faa1494b5eebbeec838b78acab task_111/solution/code/README.md +14ecb558ff4868e9ff05f8cc6167df205c9358330c00661875f61dbc07734a0d task_111/solution/code/docs/RUNBOOK.md +e6004debcfae7a7012ab618e2bb7337bddb193c5c01d44a49f4884727d5ecff5 task_111/solution/code/envs/bsd-prod.env +27db2744b3927852eb72354b9191b6a20762910f51b6bbc6e31891c702cd4feb task_111/solution/code/envs/bsd-uat.env +0cfd723b8e164258e3e84544bc09058346895487d5cc078a590d7d6043fa9805 task_111/solution/code/envs/example.env +7f7c2cc058a55385ec4cb12ffa3384ced99d3232521e0fa31cf55ab15123a09f task_111/solution/code/envs/qa.env +aab1e84c1f9534fb3b4a874cadd4a682ac078494c724d19a544cf603561ec63c task_111/solution/code/scripts/check_env.py +791b2c568bca544d49c5309c25b611826a1cc29b65884a4eb204dd29b92672f1 task_111/solution/code/scripts/envlib.py +58f687739671b0387f93f3940accefdb90049a9cba9cc35c297db6a56b860f39 task_111/solution/code/scripts/render_manifest.py +efdd16acdd986c1a04ad4d6d6a47cf6c7100f9cb122b07cc28a5b4e00151c79e task_111/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_111/task.toml +7cce035abf8eb910ce0347b6116957bb4b9e19bf6df0e35f9e11092c3492ca04 task_111/task_meta.json +65d6e0939bddf36e11a4a0b93c5c0ca02b06ce6aa3af5382cd512a52edb8b58b task_111/tests/review_hard.py +3de90713458f0abf307d46672edebaf8c1cfcf1b48a109233af8736c7e39255e task_111/tests/review_legacy.sh +939c60cf5c1fc2d773b9669644ddf8e8a978aa5dceb194e64da33e6b5510c40b task_111/tests/test.sh +7fb493713ef7008a1345371ea64ceffcc6969c2d437c4050bc4bdca27fb9415c task_111/tests/test_behavior.py +503ca32ec541c7cf8b8944d645e89841e4131fb405bce2a0540ed1d017547351 task_112/admission.json +ba588ecc6e71fbaa73dc9739ef92acbe6fe4e24a64a37aa90327051e2021d093 task_112/audit.json +26a3545853623005d1d5b3b4e539c326e15ac4e8ceee32e6d5448ef54a67b88c task_112/environment/Dockerfile +58edefbdbb6529d4f83937c2490359957e4b7fcbe2fe57ffd14ed5b9ce41b126 task_112/environment/code/Fish20/Assets/Code/Lua/FishCoreFramework/Pool/Common/PoolAble.lua +5bb8f099c646f6702e9e468176fbe40a7c380ebbae1da51adc193d6559e37543 task_112/environment/code/Fish20/Assets/Code/Lua/FishCoreFramework/Pool/Object/ObjectPool.lua +fbdae9adbe76efd85887d7611b434048ad5f1191a7d49653a1d5f47ce6bf6de3 task_112/environment/code/Fish20/Assets/Code/Lua/FishCoreFramework/Pool/Object/Pool.lua +976ee955d14dabfece27fb44125e4be7710b0baa9413883404327a3da4bb0aad task_112/environment/code/Fish20/Assets/Code/Lua/FishCoreGame/Fish/DeadExceptionBT/DeadExceptionBT_7044.lua +9de832487242e3abb5c8fd4b7fbf4d824a4ebdb5032bb36c653090c65ddf271c task_112/environment/code/Fish20/Assets/Code/Lua/FishCoreGame/Fish/DeadExceptionBT/DeadExceptionBT_7092.lua +425355412b7fa6bf69e5f45fbfb9905260deea756758dd31ba8b01cb15e3a899 task_112/environment/code/Tools/ai_review_output/20260803_061709_0242cc0d__TO__51fbabd__exploration_standard/prompts/verify_prompt_Fish20_Assets_Code_Lua_FishCoreGame_Fish_DeadExceptionBT_DeadExcept_3008c1f44df1.txt +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_112/environment/docker-compose.yaml +3bb4bb7d67365ac465e148cb78a82bc831ebd76a217eb728cda43cf784767f05 task_112/instruction.md +69419c36c19b56b2ce622c912f5910fa9236f53118813f5258b3fd14d2bb6b11 task_112/provenance.json +49eb7b768243640ac3975f48a2b9b190da555937062809b5612ee8d7ee1ced32 task_112/solution/code/tools/ai_review_output/exploration_reports/verify_Fish20_Assets_Code_Lua_FishCoreGame_Fish_DeadExceptionBT_DeadExcept_3008c1f44df1.json +aca661c7d80e3f00982fa66f6018df2e0c0850e2849e47479f4636d276bb178e task_112/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_112/task.toml +941a108e2f3db9cb2c2349052e4c031daac1b691501e81ed5a7ac7fddb44c176 task_112/task_meta.json +8bb525c53da1420313350b18ad32f2ea16dec8f8a4ced2a5756592608f07cabb task_112/tests/test.sh +4f1a36809e790859d6ae767a3fd4e4377e73c26601f88ec42fa80e9d037b2b8d task_112/tests/test_behavior.py +d7e3f29298db902d6931fa1cf7de55eae9e897b4ea80645c286cce9c7db1c4fe task_113/admission.json +1289c0981b8cf9ef7ce0633a21888a6a8ec80ca48e315b2a48d795512f5f76bc task_113/audit.json +26d1548d427c807fa0bc372c9d1aab539b53a6f390a9690053413fa13eeb3061 task_113/environment/Dockerfile +e2e6ae6f6a7c4029526719fc0fdd98f32e57d28ccdd51bf6a59e35650beaae11 task_113/environment/code/nexus_index.json +76d80f2ca695b87b41a1db29eae5a0aa8cd799a796e22491dfd36aa162e4a447 task_113/environment/code/pom.xml +7481dd0e5d7edd8ef3e74a96ac75aebc7e62878ff3f5747f9e27b464f922b1f5 task_113/environment/code/tools/deploy_preflight.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_113/environment/docker-compose.yaml +21195dcf7067e72c3ff54619a68eede533db974192c29f0386fa7dae641a23a8 task_113/instruction.md +38e71084125f343347dd093aacbb46972dca82b854ce78920745f773dcf20e87 task_113/provenance.json +15a828a3a3b4c71e2abb71e3e39ef7f0f0388b1b2cc88ecddd897aa6f9648636 task_113/solution/code/pom.xml +fbd8dce3338a68bc0f5f51fa253c04673548469e9a47fe16af6baad32941039e task_113/solution/code/tools/bump_version.py +9ea8273183d19eb7779dbc68f5a75ea730215bde13e4345f3a32c7f3de9b49b5 task_113/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_113/task.toml +a9c8cd27912c6a042889af689f311fff0ce78d632f3c1c5d7db82e79a8832727 task_113/task_meta.json +a3acc77de0f509365a882d7c797d69d779e69fdd46dfe567a98900d24ac8c501 task_113/tests/review_hard.py +a3ef4ba6df1091e34fb75cfccb4ac155600df1bab349a76ce18622d2965f688f task_113/tests/review_legacy.sh +939c60cf5c1fc2d773b9669644ddf8e8a978aa5dceb194e64da33e6b5510c40b task_113/tests/test.sh +93036f92ec7e4e36c974722a2574da9615e31bad916d1a035d6c79c957a16f9b task_113/tests/test_behavior.py +4108142260443fab10340a00dabad706482e61910ee616b8feed1decaa3dc9ca task_114/environment/Dockerfile +d2c18b977453569ec793dd1bc0e8b9cf93cde56197f8ba927d4a36b81e7b801c task_114/environment/code/index.html +29771feb8d70b14a0bd920063648fcc9e5c21639c6d7912dfa0a851ca76f68f6 task_114/environment/code/package.json +86210ce32dfd29b4f181654ce8d52395f08e773a02112a7f010d96fcc7a4ca39 task_114/environment/code/src/main.tsx +0a8900d42f239356bfc367f9a35d64742210482b9c506ef16ff2b0c790290fc3 task_114/environment/code/src/style.css +3eeba0bfe80257f3acfcaac77bf0c7c51caed08e3e24a5affd77b64b70106abf task_114/environment/code/tsconfig.json +db1298ad51620260daf856a90d32b4646c10437ad43595c73fcf1a084b796bfe task_114/environment/code/vite.config.ts +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_114/environment/docker-compose.yaml +46fd716c258daf1b61800e274fec84b8de64d891fb2c0b074537f20e0628ed92 task_114/instruction.md +f16ae86c7805e92e202a27a880c0f1b6801321ca0b7ac1ee1b28cb5899d0a314 task_114/solution/code/index.html +29771feb8d70b14a0bd920063648fcc9e5c21639c6d7912dfa0a851ca76f68f6 task_114/solution/code/package.json +a9fa097ae8f8c947e83847c3e0d450a46da05cfa92abe9043e9756fc095fa1cc task_114/solution/code/src/main.tsx +f13161c9cf3104933356c20f3463c3e14327fdcd42592a5f15e833dae62a52e9 task_114/solution/code/src/style.css +3eeba0bfe80257f3acfcaac77bf0c7c51caed08e3e24a5affd77b64b70106abf task_114/solution/code/tsconfig.json +15955c9125b8c3ada737bcf1a5b2a471632079946c9c0032c30d57a50aa7a96f task_114/solution/code/vite.config.ts +783c2763107ab835fce97be24baab98da10f86fa3ad448c7dd1c7aed3af5a3ab task_114/solution/index.html +f350ac31fae6c888e7757762dd86cded6d1cf98f8edd73ad3eead89ea137c134 task_114/solution/preview.png +cbb107922507303f99bc106a6241426c1f95c1f07aba33e6fb542eed63f396e4 task_114/solution/solve.sh +2ee5ed017f30a6db134637d1b341c837b01cdf6c6a6d8416cfbbbd33eadc499f task_114/task.toml +f9914a91f90d67fa1e1361feb97f32fd68ba403b44147657fc79d2ff699f4ba6 task_114/tests/browser.mjs +3cb92978d2fa5591e29ac38ffe7c6d6e17cc4a4634074d27e5b3ac6ad8624ec0 task_114/tests/test.sh +1368bceb73a08cd3a831c908056af6baaa0210cd11ee7eb075e38ab92c38c795 task_114/tests/verifier.py +21776bf6647292c26a53d9fc6317a3419820fcd1c36ec7382e6703c89f002691 task_115/environment/Dockerfile +b314e7855b276c0bbb9a9038a83c2afdca48ec176f89d3442c4e9a2d8dd96669 task_115/environment/code/code/.claude/skills/_shared/artifacts/state.md +29c369ab1b538eea9f1b6d877478da651dea7019acffd59bc72579741bb499e9 task_115/environment/code/code/.claude/skills/_shared/guidance/before-dispatch.md +da04b2ffdff65a571bde51ce7be2a9c6994d0202e488e541ca9bebcba813fb46 task_115/environment/code/code/.claude/skills/_shared/guidance/before-finalize.md +41e6565539c371f1f991622517c4e317b18d639630e896e3c4658541d4782687 task_115/environment/code/code/.claude/skills/_shared/guidance/before-write.md +e97c6e28165beaf9039e23bad0fe40c8628ef0304fcd8024c18f11e062d15ba0 task_115/environment/code/code/kflow/__init__.py +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_115/environment/code/code/kflow/atoms/__init__.py +b3299dbe77c58999b17edca1d372ed79e85378aa329d10782e5a49f544f68c4c task_115/environment/code/code/kflow/atoms/model.py +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_115/environment/code/code/kflow/check/__init__.py +8ce4a3df46b676a0c06a0c3d26c8a588e079b57a0fe601a610bb309b16e8206c task_115/environment/code/code/kflow/check/stages.py +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_115/environment/code/code/kflow/contracts/__init__.py +840ad14089f56a4a21068d4f5786fe05df693553a02e8f1915d0d73b1bc97a58 task_115/environment/code/code/kflow/contracts/verdict.py +c256e393bb41bc579c34693558110f1fd37363b2055170ace5cd1d317650d5dc task_115/environment/code/code/kflow/lib/paths.py +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_115/environment/code/code/kflow/tools/__init__.py +e8510a88e659a8fdb509cac91c6c35268f57557ec09d76126b80beba050e87a0 task_115/environment/code/code/kflow/tools/guidance.py +64f0b58a845161cc72b0058943de2496ae64038e4b4e250a0086836fa13aa3fa task_115/environment/code/code/kflow/tools/stage_manifest.py +df89f3afbc955ec7ea655bba10148d6471a6f7ad5deb36ad07409b42f6545964 task_115/environment/code/fixtures/runtime_review.yaml +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_115/environment/docker-compose.yaml +df89f3afbc955ec7ea655bba10148d6471a6f7ad5deb36ad07409b42f6545964 task_115/environment/fixtures/runtime_review.yaml +c0a88d787ea8c78ffba467d2a59be1d238cf18b793f05802c196db7cc43621ea task_115/instruction.md +04fcc1095f98b63f1f090b87ecdb5b2ca2a3041844f98279d12ff5348c437ea9 task_115/solution/code/report.md +d2426f5e2c466f3ce28d2da06e55632fa6296892ad995563764ae6c9d09a688a task_115/solution/solve.sh +dbe171a3022946ba8e07da64b1a4d7a3659790add84c12569ae6bdf2a3d5d5ab task_115/task.toml +a6a9a20b19389034193bd723bb2bd28ba3e596e9e68edcc43efb3b57ebd8e515 task_115/tests/fixture_guard.py +b314e7855b276c0bbb9a9038a83c2afdca48ec176f89d3442c4e9a2d8dd96669 task_115/tests/input_code/.claude/skills/_shared/artifacts/state.md +29c369ab1b538eea9f1b6d877478da651dea7019acffd59bc72579741bb499e9 task_115/tests/input_code/.claude/skills/_shared/guidance/before-dispatch.md +da04b2ffdff65a571bde51ce7be2a9c6994d0202e488e541ca9bebcba813fb46 task_115/tests/input_code/.claude/skills/_shared/guidance/before-finalize.md +41e6565539c371f1f991622517c4e317b18d639630e896e3c4658541d4782687 task_115/tests/input_code/.claude/skills/_shared/guidance/before-write.md +e97c6e28165beaf9039e23bad0fe40c8628ef0304fcd8024c18f11e062d15ba0 task_115/tests/input_code/kflow/__init__.py +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_115/tests/input_code/kflow/atoms/__init__.py +b3299dbe77c58999b17edca1d372ed79e85378aa329d10782e5a49f544f68c4c task_115/tests/input_code/kflow/atoms/model.py +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_115/tests/input_code/kflow/check/__init__.py +8ce4a3df46b676a0c06a0c3d26c8a588e079b57a0fe601a610bb309b16e8206c task_115/tests/input_code/kflow/check/stages.py +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_115/tests/input_code/kflow/contracts/__init__.py +840ad14089f56a4a21068d4f5786fe05df693553a02e8f1915d0d73b1bc97a58 task_115/tests/input_code/kflow/contracts/verdict.py +c256e393bb41bc579c34693558110f1fd37363b2055170ace5cd1d317650d5dc task_115/tests/input_code/kflow/lib/paths.py +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_115/tests/input_code/kflow/tools/__init__.py +e8510a88e659a8fdb509cac91c6c35268f57557ec09d76126b80beba050e87a0 task_115/tests/input_code/kflow/tools/guidance.py +64f0b58a845161cc72b0058943de2496ae64038e4b4e250a0086836fa13aa3fa task_115/tests/input_code/kflow/tools/stage_manifest.py +1fe24c968486d2640f741fd9aab98693112914408dc7089fd16988c667b4d49c task_115/tests/test.sh +442027e6e5dbb1ee5a9751261c5f9d94db5f673cd1587378362373eebc1f595b task_115/tests/verifier.py +79805ca39df46cd0ed019392f2a01c74ec84b35ac45ed9ee941de9b6ffdda189 task_116/environment/Dockerfile +8daef7157c674e528cabadd87dc028d8ca512c7a729f5daa0d1f767b05b42065 task_116/environment/code/com_placeholder.txt +de8ecb97724a5b7674086dda9adf921467d2a3f20929ff08b86db2f23a6a8b81 task_116/environment/code/fixture-src/com/sexytea/miniapp/dto/CreateOrderRequest.java +d530e0cd0665859dbac751f1ec3d83591a5c672318b4452031cf45a1c750cf03 task_116/environment/code/fixture-src/com/sexytea/miniapp/dto/MobileCodeToken.java +3e6c21a9b082c6a3e3e92ca4fb48a70504498a13b8883f6119acbef0935e0571 task_116/environment/code/fixture-src/com/sexytea/miniapp/dto/OrderSummary.java +44c59982a2cb6032d340dff19c9fbe70675dff3ec4a997a1c3277afd4b037e6c task_116/environment/code/fixture-src/com/sexytea/miniapp/dto/Result.java +bfecdff23589f8168f6527480f8893914ce51a72a28ff14e3a5bc6264bb5449b task_116/environment/code/fixture-src/com/sexytea/miniapp/web/controller/LoginController.java +6bb32d978dc1cc47beb9c0aaabb940d8c3dd0695e993c37ff52a8cbdb83927fb task_116/environment/code/fixture-src/com/sexytea/miniapp/web/controller/OrderController.java +46c663463329acd7039bdef0a9145293aad32e04d7f0dd06ca2719c99f0eb014 task_116/environment/code/swagger_agent/__init__.py +8b42cb2ab801db5bbbd4c14c8204eb74ad28cc620aced2ae99a94096bac206a0 task_116/environment/code/swagger_agent/__main__.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_116/environment/docker-compose.yaml +ffa4a289ad9417e34e3cb84718efc15d604cc200b6f66b82ef8639686d365da1 task_116/instruction.md +46c663463329acd7039bdef0a9145293aad32e04d7f0dd06ca2719c99f0eb014 task_116/solution/code/swagger_agent/__init__.py +fe88990f1d064d7796a26127512986ec1d6c05e53fe5cd2692bee6de2fcdd2e9 task_116/solution/code/swagger_agent/__main__.py +5e2c3003ffe46878821b595fddbb9c5e9dbae215ba1f18c640a6d744c69945ef task_116/solution/reference_swagger_agent.py +0049d2e71ae0b00eb27262b1f3697c0235fc4edbacb473fe00580736be4f6991 task_116/solution/solve.sh +32a0e6499a64ebea4814e99ccf0c2471d6d5abe846d314f2508b68a9dbc3aeca task_116/task.toml +666b86dd74952238e9aaf312f0413122b1a1d2d2a5d0240b86002401af563cd1 task_116/tests/test.sh +8c3560fce78becd0cc74677d9c5f23b0d593f308111b42a2ec80c32b8e620b4b task_116/tests/verifier.py +cda0c8557f3a2ab0519ef986535b296a05d4c1491dc887c2fb2cdf28dd5381df task_117/admission.json +9dd269c34368f9301f83e6466fd03079acdebb15fc327e322dd2aaf061873a8e task_117/audit.json +26d1548d427c807fa0bc372c9d1aab539b53a6f390a9690053413fa13eeb3061 task_117/environment/Dockerfile +487c3126b3eec18817c16fa7276ea5562a236bd6eeafe8aeba64249c6f22e795 task_117/environment/code/configure_hook.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_117/environment/docker-compose.yaml +0b1063231cd729fcf472e422a1647492ea19e0313e10d0e7ea0e5f1ac9aae8db task_117/instruction.md +202baf934c8b73e93d3e3668b0fcda4857442b8353e86d7c68b6cf7b677b2f02 task_117/provenance.json +a5686f2fbec19cb48060d541f511005d81991a323739f2ad9312a9a4ef7c633d task_117/solution/code/configure_hook.py +f82e431ca7c51baf295e6020fd94ea7d4e777a0c4b682ef1af1d872575460936 task_117/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_117/task.toml +6c67a378a7f3b65a5b971dd918de3105a37114e5bb98d193b6639babd2ec431d task_117/task_meta.json +47b8c417262482c462b7861c541439a094b306d100394e36d9394c8273283115 task_117/tests/review_hard.py +943b1b3727b42376ec5b78ce162a182fe1d34bbe3ffc81ac539e9f0bb73485ad task_117/tests/review_legacy.sh +939c60cf5c1fc2d773b9669644ddf8e8a978aa5dceb194e64da33e6b5510c40b task_117/tests/test.sh +3ff6427ea271da1869ac609174166eded284ae572bef091ec1c9aa31880035a8 task_117/tests/test_behavior.py +a24484e10d8793808f93765588979c78772aa7666af6dd48048bdb7ca99321d3 task_118/environment/Dockerfile +55c5d637fcedff503b3d0c92470d480032b02674622d06c7f9e85a8e22b6fe90 task_118/environment/code/cmd/rwdecode/main.go +196e407311c5a28fa5fec7ac999a1b091cf39eafde919c2f9d8e736a4d8a5fac task_118/environment/code/go.mod +e5cf00382e23e5d3923167aa5a77ac23747d798d8e155aec2776793f11b85cf4 task_118/environment/code/remote_write.go +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_118/environment/docker-compose.yaml +5de2322f3d3ea207080bac5d795fced854ce6643b35cea4137bdd8944efaab83 task_118/instruction.md +4b5f32c3fa32b01c6177840425ab66edbed3cc5b6eb7bd96b693b3b0f3e51f09 task_118/solution/code/cmd/rwdecode/main.go +196e407311c5a28fa5fec7ac999a1b091cf39eafde919c2f9d8e736a4d8a5fac task_118/solution/code/go.mod +ccb79f473319c0c427eec5f79036c74bf42fb6d2711b9d485c4b5bef42a01ffa task_118/solution/code/remote_write.go +b42dfb1836cf40637961a96e15680d67a4a5ad7e58b360db40eea9453a3ada54 task_118/solution/solve.sh +9d02623bba69f280700b68182421670cc11178c3e035fffcfe3a8dc668f2cab3 task_118/task.toml +16067cff9b215cf2214aa758f48bbe2f5c3b9a45f352b8b2b5ca5355760aeea3 task_118/tests/test.sh +fef66c9602810d3d3a3fb7ba3c00ace52c470ab49bcddfa3fadce2bfa284775c task_118/tests/verifier.py +fe60ee6377c2eaf8a5d2b28f072c1375a7bae67c1fa839686eea7cd2f601c26a task_119/admission.json +9dd6801d160e38e220a08c5afaf2c22d80672ea3f84f0944f7c05d715142524f task_119/audit.json +26a3545853623005d1d5b3b4e539c326e15ac4e8ceee32e6d5448ef54a67b88c task_119/environment/Dockerfile +2eceedeb39df939afb3978c199b95eace82432312feb94b8d0adb3c218bb6a1d task_119/environment/code/result_service.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_119/environment/docker-compose.yaml +41f2468e4db7b9a36d0d155aa646a931e7fcccf4f5f6c07a68f2684e3a96476a task_119/instruction.md +e7a98ede321029cb523a1fdbe2f4230f2ca7796c22b3297e3cd5c39c4908dfdc task_119/provenance.json +f1330b370961ab02cda8e79b33bb0f9ebf4eee41c403674ba4806e6e965fd5b0 task_119/solution/code/result_service.py +7dc8f22e1fb32231a0988fa0f83d69e3fcfd5814706ed7844b174a9032a66ea2 task_119/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_119/task.toml +235e54c3910c3e6f95264d0abb6bfab5b3073c337e170d1612a7965a0a79229e task_119/task_meta.json +88d0e24ffb316d78254545a357e498cf3b318c4bd3ab79f8f2a85e3bc7532f88 task_119/tests/test.sh +590572c26afd4529466c17511621644e3bfbb65ef295313221e05abd5342f120 task_119/tests/test_behavior.py +23107d73a34b5a4ceca104d5c2c75c3b15c622da61d157612978bd73a911fa60 task_120/environment/Dockerfile +924299574efdc37cf48b204a02067025b4e6812482b552e747478c36852956e7 task_120/environment/code/__init__.py +5873d6a68deb76706bf007f6a3fd06f12caa79ae83da34ecc2f268e8a5473ff8 task_120/environment/code/pipeline/__init__.py +ba08488d23c8e59b2fac979c32b11a35be3c5d994ec33ca5b1f53462c913bdd4 task_120/environment/code/pipeline/aggregator.py +467c44497b816f059b4d2307c4f14ef025386cbd0aa3889dc44fe68796d42e0d task_120/environment/code/pipeline/reporter.py +0e220d928057d3113a6527f3cf067b28e7b278d8febaebdb163960bd01c59517 task_120/environment/code/pipeline/sampler.py +163c6e2f25dad521844589f44a8a141683197c3479cc69c8a80aeac68bf7e1c1 task_120/environment/code/pipeline/tests/test_aggregator.py +a2a4564e4c5b1c20b8f06d77fa6d15f09adee3a679278dbab3185b21e855e16d task_120/environment/code/pipeline/tests/test_reporter.py +c0b9d2c56ca3e8ee8cc36b723263fff9adeb8c5c9ed82049b09ac3d521895992 task_120/environment/code/pipeline/tests/test_sampler.py +4e2fa56cae6b47f145f01a956c4514194256d0fecccf05ab5713c7f41d240247 task_120/environment/code/pipeline/tests/test_transformer.py +51b19cc387bcece7ad9e9fd51c2620f2c6702b7326ad3a5540109ad494825312 task_120/environment/code/pipeline/transformer.py +a5c636d86a4fb508f70e2fa3dfac39fa29081dfc9838a15a37d9b9527d737403 task_120/environment/code/reproducibility.py +ecdbba9b3284b093e38c36de64d4c308b6d9ea8f36d0a9aebc4c8b8b6d2b76b1 task_120/environment/code/run_harness.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_120/environment/docker-compose.yaml +700522116ab1dfb3c8a6e355f8d9cf3193fb2c08ca6cc0db79f9a900da62b94a task_120/instruction.md +924299574efdc37cf48b204a02067025b4e6812482b552e747478c36852956e7 task_120/solution/code/__init__.py +f6bbd8b1e545276e30ee10811405cd55899cb36a7254da8f6a19dad3bd6a18dd task_120/solution/code/pipeline/__init__.py +f668205c78643898c7b6af018524c36b01e5e95253212563054afeb7fdf516f2 task_120/solution/code/pipeline/aggregator.py +b54d8c30ca7c293e66f8a54a0db12a10a81a44539a6d3fd085bacc33e357fbf3 task_120/solution/code/pipeline/reporter.py +e62ec0f0a724d4978fc1cff815e65cf10c054485968605122a5f09d60706bb51 task_120/solution/code/pipeline/sampler.py +2853833e7e6391db5217096b3624da70274ed29e5dd6a6fd9b3a00887b3bd3d3 task_120/solution/code/pipeline/transformer.py +25b1f7aa78350d2902ea21ffff0c01d84e8e8cad961afb85f183710806a11e1f task_120/solution/code/reproducibility.py +ecdbba9b3284b093e38c36de64d4c308b6d9ea8f36d0a9aebc4c8b8b6d2b76b1 task_120/solution/code/run_harness.py +340b23401b7bf7e13bab7822327bc358f8112f5d4aec3a8f0bc12c19a3d85d4d task_120/solution/solve.sh +93129f1435bebefd88b801a278048dbce42b8c839aafb6dc9224bee76d2271dc task_120/task.toml +7557036f64fd446e074a91a604c72afa5dc5b01b92d4fa79435276f7a9f4532e task_120/tests/fixture_guard.py +feb0a2f98ea998a0ded2133e6df90725a9eb1b63dc02a0cde5ea528824bed78b task_120/tests/test.sh +e7c1e0beb7a72ddad392ccfad47850503b7a2bc43c0fa6779fc86f3b707d3991 task_120/tests/verifier.py +6dac5b9c0bb453acbd9652b5fc40398f57104e85707026ac1936ea9bf5eb8f40 task_121/environment/Dockerfile +d4522ac30b742555d552c92ed3f62b6338e764fbb26f6433df32c9392bcb1f16 task_121/environment/code/statemachine/__init__.py +d548f464a2ba71bc14a1aa9b5247149bccc201982415072886b859b073fbe874 task_121/environment/code/statemachine/actions.py +55cfb7ba305a85ea14e11f14dcad30dfce402e2d2558a9f664807735c635416f task_121/environment/code/statemachine/core.py +d94a389a15306ebee0df30ac928f6072261d4e04b3e26a785b15e792b9d39d9c task_121/environment/code/statemachine/events.py +53f1cbc6064f196af26b7743d0e5f5cf5e3bcdcc57efc251a1c414a703d5b861 task_121/environment/code/statemachine/guards.py +ec8ec7afc2fc8cead58f64deb211463a3da18f82e68b9922862c07a49a8e001d task_121/environment/code/statemachine/history.py +2af8b22b2a939c07e8c0e0b5ab0d959b9b40677a2c4060a9769a5dbf37d6bf6f task_121/environment/code/statemachine/transitions.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_121/environment/docker-compose.yaml +fbc01147df56087a10451568f3565fe8dc5dfb2f05db7c9039d39ec131ea1900 task_121/instruction.md +d4522ac30b742555d552c92ed3f62b6338e764fbb26f6433df32c9392bcb1f16 task_121/solution/code/statemachine/__init__.py +fa83489795bc0078741b4b217c45f31c2814abd52dc0ed3e0944f04e397d0308 task_121/solution/code/statemachine/actions.py +eb48832e0c9c4b4fcba937cefbccdd59ab506ab54a9555468b4930ad41df79eb task_121/solution/code/statemachine/core.py +075e14f5843d66d5e420603948484cb3a799b00a7797f29b78eeaf34b421f7d3 task_121/solution/code/statemachine/events.py +86884c0cd75519fbff9f49106d66e585c72d1c6cd31d544b367ee82dba62c6d2 task_121/solution/code/statemachine/guards.py +f6638036e5727c389e3d1be71fc80ef58b33af5ca9ed189c19d8ee3b66a5a5f2 task_121/solution/code/statemachine/history.py +b183249e35b768c092635313fbfe6b6e480dd6f7cec909e03dafe05b11f2798a task_121/solution/code/statemachine/transitions.py +fdb242cdda97c1a8ca541825c430798a64feb8c417e760ad2ecff5cd4aa85538 task_121/solution/solve.sh +ca74af0c6c5aa6a76c388f3bf329bfa73cc8ffcb5b43a69ea62d77417e1dbfab task_121/task.toml +7e603e998158b0a10bdeea42da9c839d1cefeeeb036da6c00a47977b8b3520cc task_121/tests/test.sh +66359f81139a9e23928b7ad2e8839affad32544216d39d430cced269913fafda task_121/tests/verifier.py +aa16e3f24136d20d6b32dbc5d4dcb5b70abaf091c3ad433c7f6471f75c9e8cd8 task_122/environment/Dockerfile +0c10789476e639ec6b7a595adeae47e77ee19359339f496e8b6ef31b85f37dd3 task_122/environment/code/README.txt +5d52b09b97afeca59d0b2dfeffa288d81810900a78d0155c3bf297cd2d7ab04b task_122/environment/code/cron_analyzer.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_122/environment/docker-compose.yaml +6936993d61798e1662504d8267a6714781626c11e641afa3b131ca71a889beb1 task_122/instruction.md +a105834b46ffc355a5c56c838a65a4f64fe30a4f38db435cc56115ebe361f14c task_122/solution/code/cron_analyzer.py +1e41e0d0e0ad383d38df4a934ccc3ba52c73aea0dd3e29a2b9c1ba423094d900 task_122/solution/solve.sh +417d94d77014acd541204a183f96a5c1371ece8a4ddc6b721e0cf1af80cfab2f task_122/task.toml +fd16f118f50c8c839f569976c57571c765c4957d4f4c374cfb7c94104ae2939d task_122/tests/test.sh +9116dfb4bef7c648c0ed2ad2c35454691ccbb0d5a4ce9bf0d1c30c874c4a08cd task_122/tests/verifier.py +3b19d060df5443692b05267bf92a446274abb35812635e1d8d594daea85ec0d7 task_123/admission.json +1fb84514ee4b9c33b1eecf2cb3bca4cf3407e149fe829774035d475718208d53 task_123/audit.json +26a3545853623005d1d5b3b4e539c326e15ac4e8ceee32e6d5448ef54a67b88c task_123/environment/Dockerfile +3f91bf6af5efaaefa79b3594284c42c069cf3124f02f72173eba4be8d853488b task_123/environment/code/.infcode/settings.json +fb33f7a0ceaf933fa673fe545637dd1adbd0dd434a817d7a5a3fa7129aa6f49a task_123/environment/code/README.md +97b5d7f0771062b529d11632e57a648ad4b8bdd205b5f4291c06ec22b0d19ad1 task_123/environment/code/review_hook_spec.json +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_123/environment/docker-compose.yaml +54ef700fc498d7a171e01605abe8a4ef89349daba66925f748470c9a0f20ea3e task_123/instruction.md +0afaed8b28f86705d6dc74993adc8da1326912680cb7bcbf6cd9529755b2a835 task_123/provenance.json +048d8b82fb70ae39b840b99ae418d31b4bbc8762d7995125395a94f0ca5a4447 task_123/solution/code/.infcode/hooks/allow_introduce_current_project.py +1978290ec059a6e61c0cced70928fc3d0ea73b0935d3536308f25cbcdec125f2 task_123/solution/code/.infcode/settings.json +97b5d7f0771062b529d11632e57a648ad4b8bdd205b5f4291c06ec22b0d19ad1 task_123/solution/code/review_hook_spec.json +fff64da8a906d18b1f43d351dc094d8f6fbf9c7ec1b39abf3553cfe525cd58a8 task_123/solution/code/tools/install_review_hook.py +771cd7542267af379948db46ce21a0f07d784fb36776c48c70d0b6a379fe3974 task_123/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_123/task.toml +cac72e5d7885c6d003184f52fd5918b8feeae19effeaf8ee150257b495db2071 task_123/task_meta.json +2adeecce136398605f442b79fc71033b9f31a586f3b732325b5f45653d9de8fb task_123/tests/review_hard.py +b090194e6f9e906e73b316028245b4134170118769d126c73dccdce4594c0862 task_123/tests/review_legacy.sh +939c60cf5c1fc2d773b9669644ddf8e8a978aa5dceb194e64da33e6b5510c40b task_123/tests/test.sh +c451a217896dda52f0c1cbe7b6c6e5703c1e157e3825281832e803841add8f80 task_123/tests/test_behavior.py +778f539e575ed980dce473951a2d99b87798c115c88a84e69ff9ebb2e221261c task_124/admission.json +a3326a8349d39716a00003a0abb38f20284da8ef8662820e30a337ccc5090191 task_124/audit.json +26a3545853623005d1d5b3b4e539c326e15ac4e8ceee32e6d5448ef54a67b88c task_124/environment/Dockerfile +92df92fabe989e77f4cbba95363293c7d112105d2e39389e7291ad68a4b8e904 task_124/environment/code/runner_system.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_124/environment/docker-compose.yaml +ecebcb585cb7a717b4d5ff2356a83b94cc76bb31978917311e25b80ce0158a9d task_124/instruction.md +91656e8754f0bcc9cf6ce8917b6b070a9cfc2514e19374e0bb7fcc8d7408e0bf task_124/provenance.json +8407d6bd332965d8e5f459f7fa38973b90df4bf224619be05dc82f1c34d6e769 task_124/solution/code/runner_system.py +688efcc167a9567969e773fba08ee75fd083e5e6a4504cbab3c5a4dec4a34e19 task_124/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_124/task.toml +0bde3769514ea642bd408243fe71a757d63842a827b50307abd3832d084b078c task_124/task_meta.json +d89e535f74dcd9ccd6f3086a97772dea45e1ad2171439372b9e61c0579ac2981 task_124/tests/test.sh +d56a64680daa63c2a413f8529e41e782bae38ffe5563d3ea7742b054f22701be task_124/tests/test_behavior.py +c3c0045da837747ba566333be707beb54a90b3bbfc965a053405058dbd804a38 task_125/admission.json +dc71cb38132bd5d6bec74fd7d37e9da1fbc7eeebbeda88ce0e93c600b4f1991d task_125/audit.json +90fa18be359c95ddf76d8439e36f52ae6427b41276df0b55db01df17480b32df task_125/environment/Dockerfile +ad19783a747a54fe999292e391cf7b2ed5cd0a30d075b32ebdbdcb6b7c9998e6 task_125/environment/code/.infcode/hooks/audit-read.js +aff28fc4a627ce907d226b20216062d7452c9edf54630c7a8da6445ad8ce56c4 task_125/environment/code/.infcode/settings.json +bd2e13f5e5328535b0626a002d9f42f6f47a5e474a963ede27f16419db1eea00 task_125/environment/code/review_hook_spec.json +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_125/environment/docker-compose.yaml +009033db1cb317cde02cddc525b03d1f97a297320ad38a277c5cf84dcecc72e2 task_125/instruction.md +07494eb3e092d52ab5446ab5008b4fa9d67f2187de05c1d50d08b52a72ea4870 task_125/provenance.json +ad19783a747a54fe999292e391cf7b2ed5cd0a30d075b32ebdbdcb6b7c9998e6 task_125/solution/code/.infcode/hooks/audit-read.js +c1ecea60d22cb48c682a21bd3c79e76000f412bb73be6555cc572859d338384f task_125/solution/code/.infcode/hooks/confirm-bash.js +99e02e65a76d28383bb07fb237d7b63e9a7fbd07fb8300a04f611c093e38a907 task_125/solution/code/.infcode/settings.json +bd2e13f5e5328535b0626a002d9f42f6f47a5e474a963ede27f16419db1eea00 task_125/solution/code/review_hook_spec.json +670d5df70e5179f326c076db3af7ba1a9e868f929c2783ff03fc097dde776c11 task_125/solution/code/tools/install_review_hook.py +53660aad19bf1ae9fd8b255eea92f0aa42379f8b4704448130bc2e36c15890c4 task_125/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_125/task.toml +e3c4c9316a63ddf53206286e687e2ed5f6e766d2f46671efa74ec0ba2241131d task_125/task_meta.json +ab6a9e5eb202b867e86e081262618455e5dcb555ff2acf474a435a6146c64e2a task_125/tests/review_hard.py +b9584b9d80fb85e48fabf5b1d7fdf62e01de61e1d40e2a4c97e5d7b8909d263e task_125/tests/review_legacy.sh +939c60cf5c1fc2d773b9669644ddf8e8a978aa5dceb194e64da33e6b5510c40b task_125/tests/test.sh +14609010c1b99772b54e40421c7108fa588c5b5714d3b1c616e3d9cee3cb0502 task_125/tests/test_behavior.js +f9cd078b783958189e2f147b3b006721583cd60a76cdc8ffe35db836f7ed243e task_126/admission.json +dc83d8c46be098e72a6165bb7502ab2fa76403c2a7d0e518a77ea578419f7e83 task_126/audit.json +26a3545853623005d1d5b3b4e539c326e15ac4e8ceee32e6d5448ef54a67b88c task_126/environment/Dockerfile +ad983f9f00398f2f329ab9204b200a378268ddfb47330685420e8935b7f9a5c3 task_126/environment/code/infcode_hooks.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_126/environment/docker-compose.yaml +10162420a8291ab1db3d0b0c93c30eea157c5cb024c91ee5cbc3d60dd03c7547 task_126/instruction.md +04ec979093cfc6783810546184e3e76e50208c06c309656de1a3f51fdc17ecb0 task_126/provenance.json +97f20d647f21bd8135a9539459112f4462417ccc89bd6278a2f7417393a26322 task_126/solution/code/infcode_hooks.py +561a3a5d3fcf043c4512e4534540d436fabd6b50c9afb65f35c975602b443868 task_126/solution/solve.sh +fe8d466a9829b82900aedf4e50ef90bb1b763ff43d0d08433b60b3d80ed52e54 task_126/task.toml +5b80f8cfd73b063e65c2af6bdfc74eb75b4988d1dff73a4755fc58782611440e task_126/task_meta.json +e3b68283f08717d4412be0505334808d0747db33a249d1aa02e8972e1732b165 task_126/tests/test.sh +bd79aceeeeefc82e4d9941ebd94bfc58e9fdaf4633899accadf0b1001bd24b19 task_126/tests/test_behavior.py +43b6c8d6690b20b0de32416c8968a025d4a5a9d2adf199f7aa7236ec8e088d71 task_127/environment/Dockerfile +194ee64caf5ca31f40c689a5e155fcfe00499f0d7d5bb55aeae8bc02bc65ff3a task_127/environment/code/app.py +b16fdbdb629add4a4b97eae4f47cf23f02a7a1d3b34cd822bf89a1f4c4a264d1 task_127/environment/code/init_db.py +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_127/environment/code/uploads/.keep +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_127/environment/docker-compose.yaml +30eacbde986c2325e849d93ff7287b99d379cdc3949f7184618490a3b6372e1a task_127/instruction.md +70166bd7588795f1944f340d3ec6fb500ee5cd65367a06b395e552d77f96b5ae task_127/solution/code/app.py +16f9d00e0399b041620f5c709484cdf0ac7e8bb28c2c60511fabfeee21c71e8d task_127/solution/code/init_db.py +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 task_127/solution/code/uploads/.keep +ca817c449bf16dfd721a6338bab38696a14cd0b40a45e814ee955e2425877b4f task_127/solution/solve.sh +8a7929c2147b7f54982e2dca6739f6348b01642ad122aa689b57617ef0084c70 task_127/task.toml +22c1cce9d47a77c9580ba025a20d94367c1275671bec08e2903be9e28232aeb2 task_127/tests/test.sh +983862938238e8643929644d7710147c5e0b6f7d4c389818812703f7cbbf2bb7 task_127/tests/verifier.py +da5ca15d835569307e80962827a5b6e7ac4c51269cafdfda747cae2a5fd6a814 task_128/environment/Dockerfile +25e74dbbd5836791c57d82ec7ea1594100e42ea043464880257a48df11a08174 task_128/environment/code/runner.sh +47b57c253f26994d0eb02297e5777a899c66a0ae4196ee6ffcf65e55638473ae task_128/environment/code/simple_runner.py +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_128/environment/docker-compose.yaml +a1a906781ddb7e4014e9310538b8d13be900cad4dbd2e25f9aa3f4b730585fd9 task_128/instruction.md +e9f0e3f7cbce1701bf04487032eaf73f910efe2422643fe643606132f7d3e821 task_128/solution/code/runner.py +60ab6d35b9c2658b24343630aa4c605899d9edbeddd42e9988aa028f139a1028 task_128/solution/code/runner.sh +0586e690c1efecf55f1728484192a69b2d4cb06f7fb260892f4a8fa3ecff1767 task_128/solution/solve.sh +8a7929c2147b7f54982e2dca6739f6348b01642ad122aa689b57617ef0084c70 task_128/task.toml +17ba1598ec799d291acd63c7d3f6632f19d085c2a9e1617902f5323bc8a5ffb6 task_128/tests/test.sh +5be4afe3799ba75ce781d1ff35f2e71d7587882f271789d66851fa8be8c2f5a5 task_128/tests/verifier.py +fd105f3cf40805fcf182a52c42ff328e4bbfbfba2008006f041ab4d77a7103e8 task_129/environment/Dockerfile +255687a34bf321b2d5cb57d96de4ddaf60d205612ae6366232e4ddf9d8b9f8b3 task_129/environment/code/Makefile +6a8565cc5bf1c94f631eb22c761c44619c940c7b4f84f318525da2b0443a7610 task_129/environment/code/tlv_pipeline.c +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_129/environment/docker-compose.yaml +4256e41e9e4f1b4340620c0b5a81176aeff1aed2e55ac3c2a6ac2da88be11266 task_129/instruction.md +255687a34bf321b2d5cb57d96de4ddaf60d205612ae6366232e4ddf9d8b9f8b3 task_129/solution/code/Makefile +4a61bf69016059e0e5bd8437090c3800ac1f3801203c68e65b0b80ca1502cd83 task_129/solution/code/tlv_pipeline.c +b31bc2da8edd7ff917205195c81b4e09da4cd03b84ebec6f15c6cecd052c724b task_129/solution/solve.sh +93129f1435bebefd88b801a278048dbce42b8c839aafb6dc9224bee76d2271dc task_129/task.toml +2ef2a555117b1301fd850c0fbb3c7413f95e04a40e43865d67fd9b0d61ed367a task_129/tests/test.sh +5cd1201ab2fef705e81aeb3e4d7fe1d64336cccfb419c0e5ff7fee3d3ee66350 task_129/tests/verifier.py +3efd187fcec17283c8226f72bea015e366d75ef59a20dd008ac2409243d48cda task_130/environment/Dockerfile +6429e74ac6c9b4542e2643a1a106b31daffdd6435f2885839a9cd86bd34f3d72 task_130/environment/code/README.md +4b535619f01c1ad69165eacd586f6b51fde0529eab158e4237ab3de3cd90fe6f task_130/environment/code/provider-routing.sh +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_130/environment/docker-compose.yaml +801b72f1a6ff007c2b75fdbe183a19ca0c7358b27e953e0a6d16f7a23d567bdd task_130/instruction.md +c20b4e7751d24392959e4cd0d8912c80acc111581805bc82474d5ea5e128f4c9 task_130/solution/code/README.md +9b6411eeb5b754375eeb7b8b100a1d4ebd34b27a19baec83402a8e2b2e998ee3 task_130/solution/code/provider-routing.sh +dca97708137b078d783e8ea02f07842140eb824636ccfdb5ec07257cb15a83f6 task_130/solution/solve.sh +8a7929c2147b7f54982e2dca6739f6348b01642ad122aa689b57617ef0084c70 task_130/task.toml +e6319873d8b634e3eb136e94b370761e610f8be2f6afd92fa721152b31a44ac0 task_130/tests/test.sh +242f794a160db8398a05cdc56d2f5ed294e37f97538743ba87f1201ec39c267e task_130/tests/verifier.py +79dcd278786ae8c4a8e5a44fc4667e81b6ff76100c4c433c6da4baeded83ed3c task_131/environment/Dockerfile +a0076111bde16af50755ea82cace7f7b80f23f665f5352133db2994e16027948 task_131/environment/code/csvq.c +a9047d255665ea718d7476a8ac47c7c20eaebb6f128f00b26e5bacfc6d3d1d46 task_131/environment/code/data/employees.csv +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_131/environment/docker-compose.yaml +d2bc9a0d88c496cea11a446e94da5f5fc32b02261eaa6150e30e9ce1af525e90 task_131/instruction.md +05f5772791565f38413ff715d00fd77e1dea5d71b04d28dca2bff6593f0f4829 task_131/solution/code/csvq.c +173b7113ed61b59d8e18346e420cf434e55eb31b152b96a2de255db720eb9ac9 task_131/solution/solve.sh +8a7929c2147b7f54982e2dca6739f6348b01642ad122aa689b57617ef0084c70 task_131/task.toml +666b86dd74952238e9aaf312f0413122b1a1d2d2a5d0240b86002401af563cd1 task_131/tests/test.sh +67928f37284e0874384d558d38e98c573dc32ea1f18378e591fa10e23ab4a449 task_131/tests/verifier.py +3a64ab1468b49ad8535cb430f68c83d562d57d45c3fad88e5b00b3ec80e6aafd task_132/environment/Dockerfile +f32a8751a9c2450badc261a6b2d7c5326a325b569fdd54718997b293a822f5a0 task_132/environment/code/code/cache_builder.py +6afeb8c9cde61928e760fab3c4cacd08e864c6eb49cedb5536e539afed35fdd0 task_132/environment/code/code/common.py +7250db6d69b5af9d454b380633fbccb93bb72b5e56ec41c86f81838c57f22972 task_132/environment/code/code/config_merger.py +6e5da778b75f1ef660836033ea8639c8027049c88d5eaeab21fa644e76bf4f2a task_132/environment/code/code/data_sampler.py +e4a64811583ce09b20b0192a366ea83ba89b2cbb48aeea191206cb7377521df2 task_132/environment/code/code/export_formatter.py +c9df6573772829d708a27a576ff04295eeb51eb4cdd20db08aee15f63b813f8e task_132/environment/code/code/health_checker.py +8a8178f1ea3e0d01c80bfbee929ac3d77c3c6f05e63f1c55029dacc97d452875 task_132/environment/code/code/log_rotator.py +5f72e9af0bb4585bba669a2d697838b9bd3f0d7e9d89f30b579f1b0d748dbe26 task_132/environment/code/code/metric_aggregator.py +a6c668f7cc08e29263bd06a90de5a1b932cf829b0bf8c7149be5c16ea8975903 task_132/environment/code/code/report_generator.py +ef19010c0c4231cca2e32588667283f858ef6ec7efa788cba0304b0ad18a5c9f task_132/environment/code/data/configs/cache.yaml +8375e0be56184419b3b05cbb81225a37d6bb9cc20eccbb76860ccb911b3bb4cd task_132/environment/code/data/configs/database.yaml +0ad7431aff341519ab630dd25d82bb36e2c0cd8784b5353d3d0e769b2b3f4f64 task_132/environment/code/data/configs/logging.yaml +b6a98d9ce9a2d9149288fa3df42d377c3e42737afdcdaf714e33c0a100b51060 task_132/environment/code/data/logs/app_2024_01.log +f2c82decdd7181cf98945929a62598db7e6b477e11f6e0eb0ae97020eff151ad task_132/environment/code/data/logs/app_2024_02.log +ae9a6306a205417afddd14316cc1d0d5e04a98f1be10865dce643925ee070ce2 task_132/environment/code/data/logs/app_2024_03.log +356c19cd5dfedfbf5027e55484c81e9a0bbc58e4f41bb8f1b2c5b47b525568c4 task_132/environment/code/data/metrics/cpu_metrics.json +213a415c04185762d3926c71b5c5f465a7438703ce8c3982292b6bb7e29f0ebb task_132/environment/code/data/metrics/disk_metrics.json +da7f14346cdf09c081eb257d0deedb85ff6a621c3406517ca9b31699725c2721 task_132/environment/code/data/metrics/memory_metrics.json +fa1e25c3686336acb7a68f613435d9e0fd65b1562d738e4f7345f03fc2d2e831 task_132/environment/code/data/metrics/network_metrics.json +6faaf2c9677a9fc3b7e0b302b3f3791e7c944bd2e2b7c5c5ac5af215f1da64ff task_132/environment/code/data/products.csv +8890d76eb4370093227aa7b03f21f77185e831459228c813c00faa988d249fea task_132/environment/code/data/records.jsonl +23fdca0f8f2fde888f8083ab21cd917b3a9c1d17282070958b1c006a2558e700 task_132/environment/code/data/sales.csv +cbd31e15f3cdc3ed53cee1bf5c16d34da970d77c944a972779582a863802a3d0 task_132/environment/code/data/transactions.jsonl +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_132/environment/docker-compose.yaml +1797a1cbb473790fdb078d74d8fdffb044e02f9c20cc9de100fb9f0b5f8dcf15 task_132/instruction.md +d43636b502987912b795a629093c2769321735a22a3ddcd0eac5c2e073980699 task_132/solution/code/build_artifacts.py +c0080f619e3308cfa09722bdcdf046524e209089f1be910eb0c22b3ece5369bb task_132/solution/code/cache_builder.py +f260857d1cf48b05b8ddbbc66339a10a50e52eeb2e0e4354a451f06093fd2528 task_132/solution/code/common.py +08096d58f38f3aa909871630dba233d10b662d3571ee8faffee5dba9db9f09bc task_132/solution/code/config_merger.py +71ed267b700829f736e93f499bb1bd5121d4c95b19c43a798ecdb6d33f532e56 task_132/solution/code/data_sampler.py +c4e9728830097b1941decee3f8182169e169c421f05714c0871437c418656021 task_132/solution/code/export_formatter.py +8e7869fca7c9cae8941aa39be553609cdbb2eb5e1395a32cf0e33c83356b622d task_132/solution/code/health_checker.py +6ef63770c92d4246be7ad776c8775b2a8040013753b25e6b109688f1fb93e3c8 task_132/solution/code/log_rotator.py +5946ac1bd33d44b2872cbb7bb4b838aed6474810563d59adc8df9ae6d34d1f6f task_132/solution/code/metric_aggregator.py +f32a8751a9c2450badc261a6b2d7c5326a325b569fdd54718997b293a822f5a0 task_132/solution/code/originals/cache_builder.py +7250db6d69b5af9d454b380633fbccb93bb72b5e56ec41c86f81838c57f22972 task_132/solution/code/originals/config_merger.py +6e5da778b75f1ef660836033ea8639c8027049c88d5eaeab21fa644e76bf4f2a task_132/solution/code/originals/data_sampler.py +e4a64811583ce09b20b0192a366ea83ba89b2cbb48aeea191206cb7377521df2 task_132/solution/code/originals/export_formatter.py +c9df6573772829d708a27a576ff04295eeb51eb4cdd20db08aee15f63b813f8e task_132/solution/code/originals/health_checker.py +8a8178f1ea3e0d01c80bfbee929ac3d77c3c6f05e63f1c55029dacc97d452875 task_132/solution/code/originals/log_rotator.py +5f72e9af0bb4585bba669a2d697838b9bd3f0d7e9d89f30b579f1b0d748dbe26 task_132/solution/code/originals/metric_aggregator.py +a6c668f7cc08e29263bd06a90de5a1b932cf829b0bf8c7149be5c16ea8975903 task_132/solution/code/originals/report_generator.py +12728d5cf42ca4c2c9afb67d22718fee76be6c0d82fba9d1540adb0927958b63 task_132/solution/code/report_generator.py +0b18f9cace7634233284996fb0485e53f30e22119ff6c9137667e42879b9b7dd task_132/solution/solve.sh +8a7929c2147b7f54982e2dca6739f6348b01642ad122aa689b57617ef0084c70 task_132/task.toml +cc65fe2b4f62ecc1b49b22c6cd823b0e72100639906e43d4f0666407329b66e8 task_132/tests/fixture_guard.py +f13991f64d569d306d5594676546b4f93eae505abbfc0b1730ecf93d65901aeb task_132/tests/test.sh +f0e1964ec8a81f04459862316b05322f3016c36e657744baaeca5f9cca2617fa task_132/tests/verifier.py +6feea298fb292ecf503e23768a740b2cfe945e518cd639654ded699d07ed1a89 task_133/environment/Dockerfile +e3888f3e627ec3ecd98a464b67250fe5364f00b5d3cb3cf2123c8ec6d5002a94 task_133/environment/code/dispatch.sh +51300f61f3eb77778f5a646f8e620355e9e4db49a870c5eca4f61ec7247549f4 task_133/environment/code/model-resolver.sh +c602040bf9bf54356646e4683943759f3240332d0a58b7e6ce45f7e0620c6eee task_133/environment/code/providers.sh +3fb907d1a2793eb8eb0aba90310d7648a6bb9c446600b745cc0e95050e97fa3c task_133/environment/code/routing-cli +4ef65149a20560601509988ce7315af71e6b06b7c48b0e18b2939e28defe67d4 task_133/environment/code/validation.sh +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_133/environment/docker-compose.yaml +18c2b61b17aa08a469c21921ebe93983aa23d4d198b4fb1b1e4885091c922a33 task_133/instruction.md +d73fd950843ed35a4abd74bf49a1c279b545f3f79cd48bdb02993aa15bee6db5 task_133/solution/code/dispatch.sh +223108701a8f70c31e727d1cb4f74d4b4f37d903d3d7731e5fc8e5dee2f483b9 task_133/solution/code/model-resolver.sh +58dbef3887a8a2f0ba782855436f5a9b47dab1e7694747a6886acfe409a95866 task_133/solution/code/providers.sh +32749c257e3150817b22110eeaadb15bc548b7618354aaff4fd4a93f27c369de task_133/solution/code/routing-cli +1bfa183fb3f406f00d8ee35ff3ea6f8d72dc1e3e27b0a3e1f23728e191e5c3fc task_133/solution/code/validation.sh +7d66d9593966c21c8d018b0fa109f7377e4750985c80ba02b6275d439ea6f7d2 task_133/solution/solve.sh +9d02623bba69f280700b68182421670cc11178c3e035fffcfe3a8dc668f2cab3 task_133/task.toml +b71758d681d29b95f07929a73d70fcad8065865968a2c3637ca23ca1b0d174e7 task_133/tests/test.sh +27abe8118f8cf079cd9f1fb26ed590cab9b4eecb627f898f29ddb237351392a9 task_133/tests/verifier.py +a2d47d11bc4e2cea64c397e77f04516520b00e59ed3031ae163c2130916c0a9c task_134/environment/Dockerfile +de07fd08f6a373c84aaad4bf63e01c1feca3f94348d18b297d9a20efa6460f92 task_134/environment/code/config_tracer.py +e84f276402351300708155c487e0d023ce049f9e5aacddbc7357bf0b29731281 task_134/environment/code/input/cli_args.json +6cf941522c3930da8c576027e6ba9e05df0378ccce5c1d20a56b51c9b230b5ed task_134/environment/code/input/config.toml +1645ba09ef33d60ecfdb8fd7ebe5dfc2de396f4884ffff0a690ca442a3b62753 task_134/environment/code/input/defaults.json +cd5638b60183467091e1ed15d7ab38c2e3333e36f4e543c3643f740b046c192a task_134/environment/code/input/env_vars.json +32f8a576c460ad2c5bbba12c5a9d1319e4a82a579489b8ab367213ece6ada974 task_134/environment/code/input/resolved.json +7c9443e37549e9097f24270c111ac77cc2a34ee5f1b59eabf7c01c4974db6ae3 task_134/environment/code/input/schema.json +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_134/environment/docker-compose.yaml +2ec64c448550b16a53887cfd98dd52a2f915b0e924ec76cdd4cf4d20ed8ba0e3 task_134/instruction.md +588cd296ef3aa7d36eb8be1d4844547e1e0dd2b73b681a29c512dd6b8162811a task_134/solution/code/config_tracer.py +c2c527920cc0fa782b6b3a88883c6b9a51111037d40dace94a9b45f2273f2cb9 task_134/solution/solve.sh +417d94d77014acd541204a183f96a5c1371ece8a4ddc6b721e0cf1af80cfab2f task_134/task.toml +c1d8882a1df200d285d6917f7457d19b16bb8204de856348f8c6e35c2694cf89 task_134/tests/test.sh +b7f1944f7e06a591d4ce2e2f1f4c8fc46f336f7f9e1ee1e93709c8a48bcbac92 task_134/tests/verifier.py +2a1c44012b223663938fd684c2601be5665b6f72a3c3664bdef34cbd29402d30 task_135/environment/Dockerfile +a8d61779d32949907aec8cebf538e3d42479386ac676a43f599c1a28a55253c2 task_135/environment/code/data/arrivals.jsonl +c7a5f7d13844652e782023955a2ea78459e9fba853573f936ffb0af793292de8 task_135/environment/code/data/config.json +ca5321631bd6695d2b4fe5f98640eff61e8540a1ebba2999c1b5ac54db38f544 task_135/environment/code/data/output_schema.json +afa3678fc6a6c371d3d56da3e76811a6727da6bf6fcfb4f73eb8f4386d2a8ff5 task_135/environment/code/go.mod +2c726ec512fc529295b8063c2d84bb580e850f565383d1059f5a9bcf7443c2f5 task_135/environment/code/main.go +aff7e1fb4166d2a05917a877991a1548a0ed391b2f991bc4dd5fbd07fbaf4131 task_135/environment/code/simulator.go +d68dcb6dfe41f991fdbb7e3640c83118d48b87cd561a780bccd8c535bd227c38 task_135/environment/code/snapshot.go +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_135/environment/docker-compose.yaml +414f6e444aaed81f959f0f72ecad0a43a6b3fa84f87cfe64aa633c181c60afd7 task_135/instruction.md +a8d61779d32949907aec8cebf538e3d42479386ac676a43f599c1a28a55253c2 task_135/solution/code/data/arrivals.jsonl +c7a5f7d13844652e782023955a2ea78459e9fba853573f936ffb0af793292de8 task_135/solution/code/data/config.json +ec1644861a8713de345e6225a1cc4e035fc58291b571e78a3ccf498e3fbe6191 task_135/solution/code/data/output_schema.json +afa3678fc6a6c371d3d56da3e76811a6727da6bf6fcfb4f73eb8f4386d2a8ff5 task_135/solution/code/go.mod +3525bb578a73e7f60cd6cb850d3a7dd81b6416d6c23af61664c3fbae99affbe3 task_135/solution/code/main.go +a5376ec2c3d204b190e3cc0955adef86637b686e5608dc7316c939fa2b4ba857 task_135/solution/code/simulator.go +ef0185a359824bbf6b0f9534cdcb1d2c6df617522d1f305bcffad260858179b2 task_135/solution/code/snapshot.go +2df6b02b558a7e9563eb90a8ea6ba7e9c0c88920777dfcf94aa8df52cf5527ab task_135/solution/solve.sh +9ccc00bd06302398759d8d590ab0ed45ef3880eb15c1bc522359995177236545 task_135/task.toml +355f1680bfd5c3c2fc7d5773be14dcb025b602f1964661e80a3410565ab30fce task_135/tests/test.sh +1e069fc2d9dffb12fe74c31ec234d0b842f7ffe8923688f46113ef4610498649 task_135/tests/verifier.py +67a38361804b8a25cff75e26e3f93d6853ccd83f7de842552556704300a0e23e task_136/environment/Dockerfile +18cd7c845f1217f37738e5270350431f3882e84dc5df52aa475839507a51aadc task_136/environment/code/index.html +c574873b38e8353182b9e805ec48746df258a8ac92ea7033ddfa5c7094dcba8e task_136/environment/code/package.json +7044c095c99931c7273c198a05768d71d99281053816efd4b6b132953476750a task_136/environment/code/physics.js +e52fcbe8b10b1160cb4abdb8f322ccbcaa3f2d72b87d6514f32603c7f7a5fa16 task_136/environment/code/server.js +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_136/environment/docker-compose.yaml +ae904f598a11f77c2414756acf776c96349720d6660fadf42753a5b3ced82cb1 task_136/instruction.md +18cd7c845f1217f37738e5270350431f3882e84dc5df52aa475839507a51aadc task_136/solution/code/index.html +c574873b38e8353182b9e805ec48746df258a8ac92ea7033ddfa5c7094dcba8e task_136/solution/code/package.json +18f8d30f9879843ddc13476fb2e3193580f7abd1ae8586277edd24e200245e13 task_136/solution/code/physics.js +e52fcbe8b10b1160cb4abdb8f322ccbcaa3f2d72b87d6514f32603c7f7a5fa16 task_136/solution/code/server.js +6a727d36270fc2afe5af911163d0e471513b3afabc4fac023e90437b172c0ceb task_136/solution/index.html +0e8a2b9738bd8e3b0cef3eb252858436d91fa59b48eaee7a836e277caae8a711 task_136/solution/solve.sh +3fa48991b38568dd8564a443e27a71a02befde02eed5d214143e16a1f13ae7ce task_136/task.toml +d5357c87acd6d7a8f2cb1cf4e42ecdc818bbf50345ca8fd9b28e95c23bf3e849 task_136/tests/direct_open.js +b1bc830c34aeb3bbd995c0dba9d442cd1509b50e804c93512aeba9840508bb87 task_136/tests/physics_edges.js +67304766dd76fbfa3278583f1ce462c68c8d21f1bb25311abb7477bc623e4a73 task_136/tests/serve_smoke.js +73a984e1b2d62428518558427cb6c81fff9de7947466b250859f867604c3900f task_136/tests/test.sh +23833920726d6c5062ee18d63a592d35e749ff9173ae38f1b307de7aee997d7f task_136/tests/verify.js +67a38361804b8a25cff75e26e3f93d6853ccd83f7de842552556704300a0e23e task_137/environment/Dockerfile +f1821a453967b11c3f77b1872ac7f4f582d98324ee9c0b593cabef86264d9e71 task_137/environment/code/index.html +c574873b38e8353182b9e805ec48746df258a8ac92ea7033ddfa5c7094dcba8e task_137/environment/code/package.json +d7591a85322bbe47053bfabe118f3099784c2718893e93eddb1e5872007445ab task_137/environment/code/scene.svg +e52fcbe8b10b1160cb4abdb8f322ccbcaa3f2d72b87d6514f32603c7f7a5fa16 task_137/environment/code/server.js +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_137/environment/docker-compose.yaml +7a3e178c3405584f74109627d46d591c9fd70f4e8364de5c9e9a9668071e7c21 task_137/instruction.md +f1821a453967b11c3f77b1872ac7f4f582d98324ee9c0b593cabef86264d9e71 task_137/solution/code/index.html +c574873b38e8353182b9e805ec48746df258a8ac92ea7033ddfa5c7094dcba8e task_137/solution/code/package.json +f8a46c25f90bbbb4a9c28024bbb73b66036bfc357a70a9b4c91cb9fb897b6035 task_137/solution/code/scene.svg +e52fcbe8b10b1160cb4abdb8f322ccbcaa3f2d72b87d6514f32603c7f7a5fa16 task_137/solution/code/server.js +6a727d36270fc2afe5af911163d0e471513b3afabc4fac023e90437b172c0ceb task_137/solution/index.html +0e8a2b9738bd8e3b0cef3eb252858436d91fa59b48eaee7a836e277caae8a711 task_137/solution/solve.sh +3fa48991b38568dd8564a443e27a71a02befde02eed5d214143e16a1f13ae7ce task_137/task.toml +7e5d3fa7296bc955938ff95957dd4c3926d8686aa539158276feed8797822af8 task_137/tests/direct_open.js +44785c12ea8d1ed9c0b6bd5aa39ff9d0cbdee212a726bea384537d99333b60cb task_137/tests/motion_check.js +67304766dd76fbfa3278583f1ce462c68c8d21f1bb25311abb7477bc623e4a73 task_137/tests/serve_smoke.js +7ad4986b9d3148fa2bb6debe398e59915670b99ddf9b391769dacb2075eff7ab task_137/tests/spec.json +4ab46cc2f97755fad563f4beeea901b89cc669cdcafcae40268e801a799f7120 task_137/tests/test.sh +4cccc465cb4c9676dfe2f62e1dc49803b1b0d1efaabb6f07b02e5055f7081c22 task_137/tests/verify.js +d8746983eba3db896c1ac3d3df8232988f35289adcb1945771553cbc833e2e5e task_137/tests/visible_change.js +67a38361804b8a25cff75e26e3f93d6853ccd83f7de842552556704300a0e23e task_138/environment/Dockerfile +f1821a453967b11c3f77b1872ac7f4f582d98324ee9c0b593cabef86264d9e71 task_138/environment/code/index.html +c574873b38e8353182b9e805ec48746df258a8ac92ea7033ddfa5c7094dcba8e task_138/environment/code/package.json +d7591a85322bbe47053bfabe118f3099784c2718893e93eddb1e5872007445ab task_138/environment/code/scene.svg +e52fcbe8b10b1160cb4abdb8f322ccbcaa3f2d72b87d6514f32603c7f7a5fa16 task_138/environment/code/server.js +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_138/environment/docker-compose.yaml +5d7b7d15d6df7c86cabe7072d17765a756e13ed68c2e6e30ffa6fdc4edd4f422 task_138/instruction.md +f1821a453967b11c3f77b1872ac7f4f582d98324ee9c0b593cabef86264d9e71 task_138/solution/code/index.html +c574873b38e8353182b9e805ec48746df258a8ac92ea7033ddfa5c7094dcba8e task_138/solution/code/package.json +42465f940c94d4d040a2630f234b217937a5f8a68760c601df3133013fc3b03f task_138/solution/code/scene.svg +e52fcbe8b10b1160cb4abdb8f322ccbcaa3f2d72b87d6514f32603c7f7a5fa16 task_138/solution/code/server.js +6a727d36270fc2afe5af911163d0e471513b3afabc4fac023e90437b172c0ceb task_138/solution/index.html +0e8a2b9738bd8e3b0cef3eb252858436d91fa59b48eaee7a836e277caae8a711 task_138/solution/solve.sh +3fa48991b38568dd8564a443e27a71a02befde02eed5d214143e16a1f13ae7ce task_138/task.toml +7e5d3fa7296bc955938ff95957dd4c3926d8686aa539158276feed8797822af8 task_138/tests/direct_open.js +19f3484784d22990557d0482e7030a6ca75d0486fb7cd14404db9637a9f67484 task_138/tests/motion_check.js +67304766dd76fbfa3278583f1ce462c68c8d21f1bb25311abb7477bc623e4a73 task_138/tests/serve_smoke.js +d3066b56a3f3893a23eaa921593297939c420f083df6699d89a5a340f9034a76 task_138/tests/spec.json +4ab46cc2f97755fad563f4beeea901b89cc669cdcafcae40268e801a799f7120 task_138/tests/test.sh +4cccc465cb4c9676dfe2f62e1dc49803b1b0d1efaabb6f07b02e5055f7081c22 task_138/tests/verify.js +d8746983eba3db896c1ac3d3df8232988f35289adcb1945771553cbc833e2e5e task_138/tests/visible_change.js +67a38361804b8a25cff75e26e3f93d6853ccd83f7de842552556704300a0e23e task_139/environment/Dockerfile +f1821a453967b11c3f77b1872ac7f4f582d98324ee9c0b593cabef86264d9e71 task_139/environment/code/index.html +c574873b38e8353182b9e805ec48746df258a8ac92ea7033ddfa5c7094dcba8e task_139/environment/code/package.json +d7591a85322bbe47053bfabe118f3099784c2718893e93eddb1e5872007445ab task_139/environment/code/scene.svg +e52fcbe8b10b1160cb4abdb8f322ccbcaa3f2d72b87d6514f32603c7f7a5fa16 task_139/environment/code/server.js +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_139/environment/docker-compose.yaml +06c3279d61e756f3fc752c35d3054b139a57dc0c69534253866f7e5f32688773 task_139/instruction.md +f1821a453967b11c3f77b1872ac7f4f582d98324ee9c0b593cabef86264d9e71 task_139/solution/code/index.html +c574873b38e8353182b9e805ec48746df258a8ac92ea7033ddfa5c7094dcba8e task_139/solution/code/package.json +136ea7ef539f7433cdd9bd1e9dffd7ac043c87f8b50d341409530c0db42d0e38 task_139/solution/code/scene.svg +e52fcbe8b10b1160cb4abdb8f322ccbcaa3f2d72b87d6514f32603c7f7a5fa16 task_139/solution/code/server.js +6a727d36270fc2afe5af911163d0e471513b3afabc4fac023e90437b172c0ceb task_139/solution/index.html +0e8a2b9738bd8e3b0cef3eb252858436d91fa59b48eaee7a836e277caae8a711 task_139/solution/solve.sh +3fa48991b38568dd8564a443e27a71a02befde02eed5d214143e16a1f13ae7ce task_139/task.toml +7e5d3fa7296bc955938ff95957dd4c3926d8686aa539158276feed8797822af8 task_139/tests/direct_open.js +8e1439e20a0cc150167073556f36ab843bf03614f5328f018faebb2075cbda90 task_139/tests/motion_check.js +67304766dd76fbfa3278583f1ce462c68c8d21f1bb25311abb7477bc623e4a73 task_139/tests/serve_smoke.js +2f1384ce7cbc8dacd6d4775fbc0323bd968f6d1b6755dd1ca088c4e018500799 task_139/tests/spec.json +4ab46cc2f97755fad563f4beeea901b89cc669cdcafcae40268e801a799f7120 task_139/tests/test.sh +4cccc465cb4c9676dfe2f62e1dc49803b1b0d1efaabb6f07b02e5055f7081c22 task_139/tests/verify.js +d8746983eba3db896c1ac3d3df8232988f35289adcb1945771553cbc833e2e5e task_139/tests/visible_change.js +f3babf986d0ab11d05389cd6d58c307008bdba60e7cdc654510ef0e34558ec6b task_140/README.md +f6977c2faae8f4e454fb191a1ac5675a752831b4642d81e474c543e2c1f5a281 task_140/environment/Dockerfile +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_140/environment/docker-compose.yaml +6645e8bcaee90f19cb3ce6d676f3fbc41b56bdcfab56c11f3a27ff98445d86d8 task_140/environment/index.html +514dbed326f0dbeaee4827c4d970290ce28d251724aae303d825a8d7d64df91b task_140/environment/levels.js +3bdf87b3e33aa5438faac5eaf74b403210a57aff267e48c7c10c2052c7f248a7 task_140/instruction.md +9eb55a555e981cf16da842e2bfd73b9d712dd4b99a396e22619d805b27d2c83d task_140/solution/index.html +514dbed326f0dbeaee4827c4d970290ce28d251724aae303d825a8d7d64df91b task_140/solution/levels.js +c6957d8211171b7deb17e0830bb9dda2355f5a2431d2af9ecc43423ff4af33f9 task_140/solution/physics.js +5c4cf408a4dddaa1cfe972240b77a391e36c92d58358f574404e16b0c1253869 task_140/solution/solve.sh +3d7b8c6e77337812a643fecc07a0e269c694af0a9a133925de482d81a7bf061e task_140/task.toml +514dbed326f0dbeaee4827c4d970290ce28d251724aae303d825a8d7d64df91b task_140/tests/levels.js +c4af53627a5eef8fa0b59e02aace3b427e7925dff2c9753fed8aa13f442465f7 task_140/tests/test.sh +dd6cfdfbb7d66d1b5ee62a56a2f618ce84385bb67f1c3a306673870676c8e147 task_140/tests/verify.cjs +2d4831b2ede76f8d18619586d60b1520ce5d8b3f5f7619e1181c939c9c769376 task_141/ASSET_CREDITS.md +b045b5c7ceed469f27bae026e802b83ae6d37953f80670cfb90fc214f335c64b task_141/README.md +0cc3223a8893f6cf1ce347b2e0da6736a0d3d86a78b0a27c47bb77b95592fe5d task_141/environment/ASSETS.md +58c2e1244ce2950fb408a496a990e370f0aafc76cdc92a7846d131db5976f2cb task_141/environment/Dockerfile +00cffa8a88bceb0ef31d407fed49a64ebadb8982714a73fcd416cb31e8c4897f task_141/environment/assets/arch.webp +fd417bba692a02187498a7fccedff1fdff835e3191cb48ccbbd0bc5151726a1b task_141/environment/assets/basalt.webp +6a40afdb5caf23cbfe65fe09e8dc4fbb05cb385c3500e3cf5462c454e749e11f task_141/environment/assets/block.webp +271ecfeee90ede53d0edcba13d91ed1f59cf843474904810aa73118125efb6fe task_141/environment/assets/boot.webp +9e61bf2ce1737d18553ddbb08f7a0edb4e56a7a0f23c3a0bb5ee6a4a7224c190 task_141/environment/assets/brazier.webp +479e9c4f62114c08538cff343b377a4e37007a36c5b724e9db00c70a20fb9fc9 task_141/environment/assets/calf.webp +9e6296e064a86167cd230319179edc5977fb551f88ade6b186c34b707ff0a584 task_141/environment/assets/cistern-walk.webp +a41302d096e705fec8419aaafe78c4411bee476ad8f741e2a9c592d365f9ec6e task_141/environment/assets/explorer-data.js +f3c190dadf384c5263448767f746f4a7158b89428c8c6b28a1446c2aafab4be4 task_141/environment/assets/explorer-slide.webp +f783e545d7a2754cd785b4e62e093185524f872f2b365b4b5c492573e7d7e08a task_141/environment/assets/explorer.glb +05ff2c8813670f8d500ea71da5cec0e5de6e9df4138294779f5cfea9c85dd61c task_141/environment/assets/explorer.webp +d09c402fa630e46fee857183d793a41e81c2aca7bd08a335a6ab65e234e752e2 task_141/environment/assets/fern.webp +4186ebb590c1569f67aac6fb0c544a2e7628691f4b22a751fb0113e96ab834ad task_141/environment/assets/gap.webp +ea04deb2397f3a7cf5f712602660015e0c4e408e8ad1e9e37a5b59c888450b8d task_141/environment/assets/lantern.webp +b720047c42c9379adbc9a857fd641c4201e61436d57d21ce7d64b99ae4985efd task_141/environment/assets/moon-gate.webp +44d51e81dd7ffcc7655d8ec9e70b32c62a19676b6dfd46db393f9573fa5abfa8 task_141/environment/assets/shield.webp +cc80d9a8721ca1d3d3ea030073e0708c865751931c0ca669df142fc3f31affe0 task_141/environment/assets/sleeve.webp +66d103b3a2856f5f83ec12899b18316ea0f649d75872464e61099af2762362d4 task_141/environment/assets/sun-court.webp +9d8d3609637c45e4608df9e224139a20556f015e7d90765d4d57524c2b002e23 task_141/environment/assets/thigh.webp +602d9577353c2ad2470b9e04f66882a2c0c9c9f904937aebb516a52f0bf158ec task_141/environment/assets/trunk.webp +229fa3c2e3598b62ca8af5ac8ac6f43a60c702c364d4a4adb7093b5d0fc85eab task_141/environment/assets/wrist.webp +31c9dd6a4c3fbd82a13010b62e4e6298cf557c138345f7903aaaeafc197118ec task_141/environment/docker-compose.yaml +c81113fcfec0c4132a4373499194f5b4baf4b90e0c694fd657aaebba8bbd8db2 task_141/environment/index.html +3bcf107c88949cf5b410ffa27c51406800fac8d1a59380ddcae98b00745a11a9 task_141/environment/route.js +bfe119ea4fd413f5f7ca3fcd63adb0c4a073ed39daa2fe7d3e6b769e21272601 task_141/environment/vendor/THREE-LICENSE.txt +185570777134e2c5d90c8458bcc87beb5e270e622f5051b6700809637eb60ba5 task_141/environment/vendor/three-gltf.js +58e356aa5634c983525096cbebfdcd36330dde973c150727d23ec28208cdb02f task_141/instruction.md +00cffa8a88bceb0ef31d407fed49a64ebadb8982714a73fcd416cb31e8c4897f task_141/solution/assets/arch.webp +fd417bba692a02187498a7fccedff1fdff835e3191cb48ccbbd0bc5151726a1b task_141/solution/assets/basalt.webp +6a40afdb5caf23cbfe65fe09e8dc4fbb05cb385c3500e3cf5462c454e749e11f task_141/solution/assets/block.webp +271ecfeee90ede53d0edcba13d91ed1f59cf843474904810aa73118125efb6fe task_141/solution/assets/boot.webp +9e61bf2ce1737d18553ddbb08f7a0edb4e56a7a0f23c3a0bb5ee6a4a7224c190 task_141/solution/assets/brazier.webp +479e9c4f62114c08538cff343b377a4e37007a36c5b724e9db00c70a20fb9fc9 task_141/solution/assets/calf.webp +9e6296e064a86167cd230319179edc5977fb551f88ade6b186c34b707ff0a584 task_141/solution/assets/cistern-walk.webp +f3c190dadf384c5263448767f746f4a7158b89428c8c6b28a1446c2aafab4be4 task_141/solution/assets/explorer-slide.webp +f783e545d7a2754cd785b4e62e093185524f872f2b365b4b5c492573e7d7e08a task_141/solution/assets/explorer.glb +05ff2c8813670f8d500ea71da5cec0e5de6e9df4138294779f5cfea9c85dd61c task_141/solution/assets/explorer.webp +d09c402fa630e46fee857183d793a41e81c2aca7bd08a335a6ab65e234e752e2 task_141/solution/assets/fern.webp +4186ebb590c1569f67aac6fb0c544a2e7628691f4b22a751fb0113e96ab834ad task_141/solution/assets/gap.webp +ea04deb2397f3a7cf5f712602660015e0c4e408e8ad1e9e37a5b59c888450b8d task_141/solution/assets/lantern.webp +b720047c42c9379adbc9a857fd641c4201e61436d57d21ce7d64b99ae4985efd task_141/solution/assets/moon-gate.webp +44d51e81dd7ffcc7655d8ec9e70b32c62a19676b6dfd46db393f9573fa5abfa8 task_141/solution/assets/shield.webp +cc80d9a8721ca1d3d3ea030073e0708c865751931c0ca669df142fc3f31affe0 task_141/solution/assets/sleeve.webp +66d103b3a2856f5f83ec12899b18316ea0f649d75872464e61099af2762362d4 task_141/solution/assets/sun-court.webp +9d8d3609637c45e4608df9e224139a20556f015e7d90765d4d57524c2b002e23 task_141/solution/assets/thigh.webp +602d9577353c2ad2470b9e04f66882a2c0c9c9f904937aebb516a52f0bf158ec task_141/solution/assets/trunk.webp +229fa3c2e3598b62ca8af5ac8ac6f43a60c702c364d4a4adb7093b5d0fc85eab task_141/solution/assets/wrist.webp +bec9922ee28e4c29d04088154025640d2c0a6a965f8900ba360edfd9caea144a task_141/solution/engine.js +18e0325fb45715c4a07a89c69ff85c7ae12959dfca7902b529f430539529836c task_141/solution/index.html +3bcf107c88949cf5b410ffa27c51406800fac8d1a59380ddcae98b00745a11a9 task_141/solution/route.js +af220bfe63d7387723c27897507aca169649a62a5147ff8ef38c2512871caa52 task_141/solution/run.css +a8b12569dc6ed799edbbe3d6f81b0bb6449d76bbc0f99dcee757cb66e07b8b85 task_141/solution/runner.js +a402d98640dffb9f43d25ab30f89128ad127f5df98652d6ae40b6b20876c70e6 task_141/solution/runner.src.js +5d0320120758bdf7ad7f2be7f204637c7e20d9828fa3d6f3926e3e81fe040683 task_141/solution/scenery.js +a2d04c9712c289c1da7287e953322ce668184e74c438291d5fe4fc8c44d73dfd task_141/solution/solve.sh +bfe119ea4fd413f5f7ca3fcd63adb0c4a073ed39daa2fe7d3e6b769e21272601 task_141/solution/three-LICENSE.txt +399bea37fb8470fc292a6d85ef6a50914cf5fc9bc05c36d9bf8b4a59d90ff994 task_141/solution/trail.js +88b42f36047b827948a8d610980474cf35f623becd8dde88a9e0213e16611311 task_141/solution/view.js +39b6dcc505e5754c0eb1de66d2ad6fe6ff85ea64254eff3523a39151b83fba71 task_141/task.toml +c4af53627a5eef8fa0b59e02aace3b427e7925dff2c9753fed8aa13f442465f7 task_141/tests/test.sh +6589af2e7882dd9e06316d6dc7b8b8cdb85c24d5cdee94da739ccb254c2d6797 task_141/tests/verify.cjs +38f1c28e658244df1e06b62f5719d6ba8cf4c620bd520feac00f5a4478e548c1 task_id_map.json +70d59805322b4270c1fb4ee819c8b40441f2b7c17f2063e46319edcc2089171c task_map.json diff --git a/VALIDATION.md b/VALIDATION.md new file mode 100644 index 0000000000000000000000000000000000000000..8c3371abe0125fedcd2ba762774c5a1828c7f0a3 --- /dev/null +++ b/VALIDATION.md @@ -0,0 +1,204 @@ +# Validation + +This release adds `task_141` to the 140-task snapshot. Validation records identify the task snapshots actually checked. + +## Lantern Run + +`task_141` passed all six browser scenarios with the reference solution and earned reward 1 under Harbor 0.24.0 on Docker. The unchanged starter earned 0. Neither run had an execution exception. Local controls accepted an SVG-based runner and rejected arm-only animation, static scenery, invisible scenery markers, a short jump, and an overlong slide. A fresh offline browser loaded the art kit and the three bundled animation clips from the starting environment. Visual polish and naturalness are reviewed separately. The historical results below retain their original scope. + +## Sky Orchard + +`task_140` passed all nine browser scenarios with the reference solution and earned reward 1 under Harbor 0.24.0 on Docker. The unchanged starter earned 0. Neither trial had an execution exception. Local browser controls accepted higher ground friction and rejected missing board gravity, missing vertical support, missing bounce, and missing ground friction. Artwork is reviewed separately from the automatic reward. This is model-free validation; the new task is not included in the historical model scores or control table below. + +## Recorded review and regression + +| Check | Scope | Outcome | +| --- | --- | --- | +| Independent instruction/verifier review | 139 tasks | Every task compared with its earlier instruction and traced through its actual verifier entry point | +| First verifier revision and coverage extension | 51 tasks | 228 controls matched expectations | +| Latest instruction/verifier alignment | 7 tasks | 40 controls matched expectations | + +The 51-task regression used 51 reference solutions, 51 unchanged starters, 51 alternative implementations and 75 incorrect variants. Reference and alternative implementations received reward 1, unchanged starters and incorrect variants received reward 0. + +The latest seven tasks are `task_025`, `task_027`, `task_037`, `task_041`, `task_049`, `task_106` and `task_107`. Their final snapshots were checked on 2026-11-17 with Harbor 0.24.0 on Docker execution nodes. + +| Latest control | Count | Actual reward | +| --- | ---: | --- | +| Reference solution | 7 | All 1 | +| Unchanged starter | 7 | All 0 | +| Reasonable alternative implementation | 10 | All 1 | +| Incorrect implementation | 16 | 15 at 0, one at 0.9 | + +The 0.9 result is the `task_049` variant that ends play when the bird's outline touches the boundary. It loses credit for violating the required center-coordinate threshold under the task's existing fractional scoring rule. + +Two batches contain 51 recorded attempts. The final 40-control set selects the latest task snapshots, including the follow-up checks for `task_037` and `task_041`. No execution exceptions remain in that set. The 51-task and seven-task regressions overlap in task membership and must be reported separately. + +## Latest behavior checks + +- `task_025` checks complete source-column retention and the computed per-capita GDP in the 2007 JSON export, including equivalent numeric and table representations. +- `task_027` accepts SVG text and Canvas `fillText` or `strokeText`. Positive controls cover both Canvas methods, RTL/max-width text and SVG polygon marks. Transparent-text output is rejected. Reports are checked again after the input data changes. +- `task_037` accepts PNG, SVG, JPEG and WebP. Actual decoded images establish gallery order and preview identity while original stored bytes and MIME types are checked independently. Separate, revoked Blob URLs are accepted. Wrong-image, reversed-order and format-restricting variants fail. +- `task_041` checks the home menu, separate Start action, both player modes, item-value ordering, visible explosions and default/custom victory thresholds. A local boundary control accepts 100 changed pixels and rejects 99. +- `task_049` checks that ceiling/ground collision uses the bird's center and freezes state after game over. +- `task_106` checks the browser title, visible heading, rendered distribution bars, proportional lengths, filters and empty results. Horizontal HTML/CSS and vertical SVG alternatives pass. +- `task_107` checks the article-detail drawer at either edge while preserving surrounding workspace. A centered modal fails the drawer requirement. + +The regression used model-free `oracle` and `nop` agents. The static review and finite controls do not provide a model leaderboard or measure model discriminability. Full internal control artifacts are maintained separately. + +## Remaining limits + +Independent review identified open-text false-rejection risks in three verifiers. `task_073` can reject a negated quotation about therapeutic efficacy. `task_080` can treat a quoted misleading tooltip that the report proposes replacing as an endorsed statement. `task_112` checks fixed vocabulary in a free-worded refutation and can reject correct synonyms. These limitations remain in this release and should be considered when interpreting affected results. + +Other recorded limits include presentation constraints for `task_030`, `task_033` and `task_048`, prose matching in `task_115`, the untested over-1,000-row sampling case in `task_027`, and partial visual coverage. The 139-task review traces requirements and executable checks. It is a static review rather than a fresh container execution of every task. + +## Historical controls + +The following table retains the 2026-10-22 control results from earlier snapshots. It is included for lineage and must keep that earlier evaluation identity. There were 557 applicable results across 139 tasks, including 140 incorrect variants. Later instruction, verifier and budget changes require affected controls to be rerun before transferring those results to a new snapshot. + +| Task | Reference reward | No-op reward | Incorrect variant reward(s) | Alternative reward | +| --- | ---: | ---: | ---: | ---: | +| `task_001` | 1 | 0 | 0 | 1 | +| `task_002` | 1 | 0 | 0 | 1 | +| `task_003` | 1 | 0 | 0 | 1 | +| `task_004` | 1 | 0 | 0 | 1 | +| `task_005` | 1 | 0 | 0 | 1 | +| `task_006` | 1 | 0 | 0 | 1 | +| `task_007` | 1 | 0 | 0 | 1 | +| `task_008` | 1 | 0 | 0 | 1 | +| `task_009` | 1 | 0 | 0 | 1 | +| `task_010` | 1 | 0 | 0 | 1 | +| `task_011` | 1 | 0 | 0 | 1 | +| `task_012` | 1 | 0 | 0 | 1 | +| `task_013` | 1 | 0 | 0 | 1 | +| `task_014` | 1 | 0 | 0 | 1 | +| `task_015` | 1 | 0 | 0 | 1 | +| `task_016` | 1 | 0 | 0 | 1 | +| `task_017` | 1 | 0 | 0 | 1 | +| `task_018` | 1 | 0 | 0 | 1 | +| `task_019` | 1 | 0 | 0 | 1 | +| `task_020` | 1 | 0 | 0 | 1 | +| `task_021` | 1 | 0 | 0 | 1 | +| `task_022` | 1 | 0 | 0 | 1 | +| `task_023` | 1 | 0 | 0 | 1 | +| `task_024` | 1 | 0 | 0 | 1 | +| `task_025` | 1 | 0 | 0 | 1 | +| `task_026` | 1 | 0 | 0 | 1 | +| `task_027` | 1 | 0 | 0 | 1 | +| `task_028` | 1 | 0 | 0 | 1 | +| `task_029` | 1 | 0 | 0 | 1 | +| `task_030` | 1 | 0 | 0 | 1 | +| `task_031` | 1 | 0 | 0 | 1 | +| `task_032` | 1 | 0 | 0 | 1 | +| `task_033` | 1 | 0 | 0 | 1 | +| `task_034` | 1 | 0 | 0 | 1 | +| `task_035` | 1 | 0 | 0 | 1 | +| `task_036` | 1 | 0 | 0 | 1 | +| `task_037` | 1 | 0 | 0 | 1 | +| `task_038` | 1 | 0 | 0 | 1 | +| `task_039` | 1 | 0 | 0 | 1 | +| `task_040` | 1 | 0 | 0 | 1 | +| `task_041` | 1 | 0 | 0 | 1 | +| `task_042` | 1 | 0 | 0 | 1 | +| `task_043` | 1 | 0 | 0 | 1 | +| `task_044` | 1 | 0 | 0 | 1 | +| `task_045` | 1 | 0 | 0 | 1 | +| `task_046` | 1 | 0 | 0 | 1 | +| `task_047` | 1 | 0 | 0 | 1 | +| `task_048` | 1 | 0 | 0.9 | 1 | +| `task_049` | 1 | 0 | 0.9 | 1 | +| `task_050` | 1 | 0 | 0.8888888888888888 | 1 | +| `task_051` | 1 | 0 | 0 | 1 | +| `task_052` | 1 | 0 | 0 | 1 | +| `task_053` | 1 | 0 | 0 | 1 | +| `task_054` | 1 | 0 | 0 | 1 | +| `task_055` | 1 | 0 | 0 | 1 | +| `task_056` | 1 | 0 | 0 | 1 | +| `task_057` | 1 | 0 | 0 | 1 | +| `task_058` | 1 | 0 | 0 | 1 | +| `task_059` | 1 | 0 | 0.8888888888888888 | 1 | +| `task_060` | 1 | 0 | 0 | 1 | +| `task_061` | 1 | 0 | 0 | 1 | +| `task_062` | 1 | 0 | 0.875 | 1 | +| `task_063` | 1 | 0 | 0.875 | 1 | +| `task_064` | 1 | 0 | 0.875 | 1 | +| `task_065` | 1 | 0 | 0.875 | 1 | +| `task_066` | 1 | 0 | 0 | 1 | +| `task_067` | 1 | 0 | 0 | 1 | +| `task_068` | 1 | 0 | 0 | 1 | +| `task_069` | 1 | 0 | 0 | 1 | +| `task_070` | 1 | 0 | 0 | 1 | +| `task_071` | 1 | 0 | 0 | 1 | +| `task_072` | 1 | 0 | 0 | 1 | +| `task_073` | 1 | 0 | 0 | 1 | +| `task_074` | 1 | 0 | 0 | 1 | +| `task_075` | 1 | 0 | 0 | 1 | +| `task_076` | 1 | 0 | 0 | 1 | +| `task_077` | 1 | 0 | 0 | 1 | +| `task_078` | 1 | 0 | 0 | 1 | +| `task_079` | 1 | 0 | 0 | 1 | +| `task_080` | 1 | 0 | 0 | 1 | +| `task_081` | 1 | 0 | 0 | 1 | +| `task_082` | 1 | 0 | 0 | 1 | +| `task_083` | 1 | 0 | 0 | 1 | +| `task_084` | 1 | 0 | 0 | 1 | +| `task_085` | 1 | 0 | 0 | 1 | +| `task_086` | 1 | 0 | 0 | 1 | +| `task_087` | 1 | 0 | 0 | 1 | +| `task_088` | 1 | 0 | 0 | 1 | +| `task_089` | 1 | 0 | 0 | 1 | +| `task_090` | 1 | 0 | 0 | 1 | +| `task_091` | 1 | 0 | 0 | 1 | +| `task_092` | 1 | 0 | 0 | 1 | +| `task_093` | 1 | 0 | 0 | 1 | +| `task_094` | 1 | 0 | 0 | 1 | +| `task_095` | 1 | 0 | 0 | 1 | +| `task_096` | 1 | 0 | 0 | 1 | +| `task_097` | 1 | 0 | 0 | 1 | +| `task_098` | 1 | 0 | 0 | 1 | +| `task_099` | 1 | 0 | 0 | 1 | +| `task_100` | 1 | 0 | 0 | 1 | +| `task_101` | 1 | 0 | 0 | 1 | +| `task_102` | 1 | 0 | 0 | 1 | +| `task_103` | 1 | 0 | 0 | 1 | +| `task_104` | 1 | 0 | 0 | 1 | +| `task_105` | 1 | 0 | 0 | 1 | +| `task_106` | 1 | 0 | 0 | 1 | +| `task_107` | 1 | 0 | 0 | 1 | +| `task_108` | 1 | 0 | 0 | 1 | +| `task_109` | 1 | 0 | 0 | 1 | +| `task_110` | 1 | 0 | 0, 0 | 1 | +| `task_111` | 1 | 0 | 0 | 1 | +| `task_112` | 1 | 0 | 0 | 1 | +| `task_113` | 1 | 0 | 0 | 1 | +| `task_114` | 1 | 0 | 0 | 1 | +| `task_115` | 1 | 0 | 0 | 1 | +| `task_116` | 1 | 0 | 0 | 1 | +| `task_117` | 1 | 0 | 0 | 1 | +| `task_118` | 1 | 0 | 0 | 1 | +| `task_119` | 1 | 0 | 0 | 1 | +| `task_120` | 1 | 0 | 0 | 1 | +| `task_121` | 1 | 0 | 0 | 1 | +| `task_122` | 1 | 0 | 0 | 1 | +| `task_123` | 1 | 0 | 0 | 1 | +| `task_124` | 1 | 0 | 0 | 1 | +| `task_125` | 1 | 0 | 0 | 1 | +| `task_126` | 1 | 0 | 0 | 1 | +| `task_127` | 1 | 0 | 0 | 1 | +| `task_128` | 1 | 0 | 0 | 1 | +| `task_129` | 1 | 0 | 0 | 1 | +| `task_130` | 1 | 0 | 0 | 1 | +| `task_131` | 1 | 0 | 0 | 1 | +| `task_132` | 1 | 0 | 0 | 1 | +| `task_133` | 1 | 0 | 0 | 1 | +| `task_134` | 1 | 0 | 0 | 1 | +| `task_135` | 1 | 0 | 0 | 1 | +| `task_136` | 1 | 0 | 0 | 1 | +| `task_137` | 1 | 0 | 0 | 1 | +| `task_138` | 1 | 0 | 0 | 1 | +| `task_139` | 1 | 0 | 0 | 1 | + +## Reproducing controls + +Each task includes its reference solution and initial environment. Run `oracle` and `nop` with Harbor 0.24.0 as shown in [README.md](README.md). Use a separate jobs directory and record exact task-package hashes with the new results. Incorrect and alternative controls from the internal review are not bundled. + +The release retains the recorded evaluation budgets of 3,600 seconds for agent execution, 300 seconds for verification and 1,200 seconds for environment builds. Metadata privacy cleanup removes personal result paths and leaves executable task content unchanged from the reviewed candidate. diff --git a/task_001/acceptance_checklist.json b/task_001/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..dbb98a6a2a8c53126906a9ce6b6b660130451462 --- /dev/null +++ b/task_001/acceptance_checklist.json @@ -0,0 +1,16 @@ +{ + "task_id": 1, + "category": "frontend_development", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies." + ], + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "risk_notes": [], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_001/environment/Dockerfile b/task_001/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_001/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_001/environment/code/.gitkeep b/task_001/environment/code/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/task_001/environment/docker-compose.yaml b/task_001/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_001/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_001/instruction.md b/task_001/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d8e4300c868413e5238acc99b1fef589b08c0bfb --- /dev/null +++ b/task_001/instruction.md @@ -0,0 +1,16 @@ +# Gomoku with a victory reveal + +Build a two-player Gomoku game in HTML and JavaScript. Open the root `index.html` directly in a browser; the game must work offline. Show a 15×15 board and both players' stones. On a win, display the winner and reveal an Easter egg. + +## Game rules and state interface + +Players alternate placing stones. Either player wins by completing five consecutive stones of their own color horizontally, vertically, or along either diagonal. A gap or an opposing stone breaks a line. + +Expose `window.gameTest` with `reset()`, `move(row, col)`, and `state()`. Moves use zero-based coordinates and update the same state and board as user moves. Return `{size, board, current, winner, easterEgg}`: `size` is 15, `board` is a 15×15 array with `null` for empty cells and distinct piece values for the two players, and `current` identifies the current player. When there is a winner, set a nonempty, consistent player-specific `winner` and independently set `easterEgg` to true or a nonempty value. + +## Acceptance Checklist + +- The page renders offline without browser errors; legal API moves update the visible board. +- Occupied and out-of-bounds moves leave state unchanged. +- Both players can win in all four directions. Winner and Easter egg stay unset before a winning line, including for disconnected stones. +- Reset clears every cell, the winner and the Easter egg, and restores the first mover. diff --git a/task_001/quality_notes.md b/task_001/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..125a20b7b283c909235a49e7cd080f13240f2b2a --- /dev/null +++ b/task_001/quality_notes.md @@ -0,0 +1,2 @@ +# Quality Notes + diff --git a/task_001/solution/README.md b/task_001/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_001/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_001/solution/code/index.html b/task_001/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..b25aa1970d4930a0421ce87ea1bc72118cd5fb70 --- /dev/null +++ b/task_001/solution/code/index.html @@ -0,0 +1,145 @@ + + + + + +15x15 Gomoku + + + +

15x15 Gomoku

+
Black moves first. Place a stone.
+
+ +
+ + + + diff --git a/task_001/solution/solve.sh b/task_001/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_001/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_001/task.toml b/task_001/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_001/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_001/task_meta.json b/task_001/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..487fe8a0de11e4fdca4925404dc291d07fc3e139 --- /dev/null +++ b/task_001/task_meta.json @@ -0,0 +1,18 @@ +{ + "task_id": 1, + "task_category": "frontend_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 1, + "language": "javascript", + "tool_files_from_selected_trace": [ + "gomoku.html" + ], + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "source_row_id": 6, + "repair_revision": "2026-09-29", + "instruction_sha256": "6903869c3ab59a41ffbc5c295b71f2b0cf6f156ca59035b2a00de02426946ea1" +} diff --git a/task_001/tests/_shared/contract_checker.js b/task_001/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..2871da7ae3ffc95310f2c0e3176de2548e591f55 --- /dev/null +++ b/task_001/tests/_shared/contract_checker.js @@ -0,0 +1,576 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const boardSel = pick([sel.board, '[data-testid="board"]', '#board']); + const canvasSel = 'canvas'; + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const cellCount = await page.locator(cellsSel).count(); + const canvasCount = await page.locator(canvasSel).count(); + + // A 15x15 board is a visible requirement, not a DOM-structure requirement: + // accept a grid of cells, a , OR a [data-testid="board"]/#board container. + if (cellCount >= 40) { + // ---- DOM-cell board ---- + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + // turn alternation: two stones placed on distinct cells must differ. + // A stone may be rendered as a child element, a color class on the cell + // itself, visible text/glyph, or a CSS pseudo-element / background. + const stones = await page.evaluate((cellsSel) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const sig = (cell) => { + if (!cell) return ''; + const parts = []; + const stone = cell.querySelector('.stone, [class*="stone"]') || cell.firstElementChild; + if (stone && stone.className) { + const cls = String(stone.className).replace(/\bstone\b/g, '').trim(); + if (cls) parts.push(cls); + } + const cellCls = String(cell.className || '') + .split(/\s+/) + .filter((c) => /black|white|stone|piece|chess|player|red|blue|dark|light|^b\d|^w\d|^x$|^o$/i.test(c)) + .join(' '); + if (cellCls) parts.push(cellCls); + const txt = (cell.innerText || cell.textContent || '').trim(); + if (txt) parts.push(txt); + try { + const pb = getComputedStyle(cell, '::before'); + const pa = getComputedStyle(cell, '::after'); + if (pb && pb.content && pb.content !== 'none' && pb.content !== 'normal') parts.push('b:' + pb.content + pb.backgroundColor); + if (pa && pa.content && pa.content !== 'none' && pa.content !== 'normal') parts.push('a:' + pa.content + pa.backgroundColor); + } catch (e) { /* ignore */ } + return parts.join('|').trim(); + }; + return { a: sig(cells[0]), b: sig(cells[1]) }; + }, cellsSel); + if (!stones.a || !stones.b) { + throw new Error('placing a stone should leave a marker on each clicked cell'); + } + if (stones.a === stones.b) { + throw new Error('turn alternation failed: two consecutive moves produced identical stones (' + stones.a + ')'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + } + } else if (canvasCount > 0 || (await page.locator(boardSel).count()) > 0) { + // ---- canvas or container board: assert clicks change the rendered state ---- + const useCanvas = canvasCount > 0; + const targetSel = useCanvas ? canvasSel : boardSel; + const sample = () => page.evaluate(({ targetSel, statusSel, useCanvas }) => { + const el = document.querySelector(targetSel); + let canvasSample = ''; + if (useCanvas && el && el.toDataURL) { + try { canvasSample = el.toDataURL().slice(0, 200); } catch (e) { canvasSample = ''; } + } + return { + canvasSample, + html: el ? (el.innerHTML.length + ':' + (el.innerText || '').trim()) : '', + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + }; + }, { targetSel, statusSel, useCanvas }); + const before = await sample(); + const target = page.locator(targetSel).first(); + const box = await target.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width * 0.3, box.y + box.height * 0.3); + await page.waitForTimeout(150); + await page.mouse.click(box.x + box.width * 0.55, box.y + box.height * 0.55); + await page.waitForTimeout(250); + } + const after = await sample(); + if (before.canvasSample === after.canvasSample && before.html === after.html && before.status === after.status) { + throw new Error('clicking the board does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + } else { + throw new Error('no board found: expected a >=40-cell grid, a , or [data-testid="board"]/#board'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode, contractDir }) { + const contract = readContract(contractDir || taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_001/tests/_shared/static_enhancer.sh b/task_001/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_001/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_001/tests/enhancement_cases.json b/task_001/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..2f1786459a90546d04b58e9a42c6819c9d2895a5 --- /dev/null +++ b/task_001/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","instruction_evidence":"请用 HTML、JavaScript 完成15x15 的五子棋游戏","validator":"validate_enhanced_cases.js","behavior":"渲染可玩的15x15棋盘,共225个逻辑落子位置"}, + {"case_id":"ENHANCED_CASE_2","instruction_evidence":"完成15x15 的五子棋游戏","validator":"validate_enhanced_cases.js","behavior":"连续合法落子会改变棋盘,且双方棋子状态交替"}, + {"case_id":"ENHANCED_CASE_3","instruction_evidence":"游戏胜利后显示赢家并放一个彩蛋","validator":"validate_enhanced_cases.js","behavior":"构造五连后显示赢家,并出现胜利后的可见彩蛋变化"} +] diff --git a/task_001/tests/pixel_changes.js b/task_001/tests/pixel_changes.js new file mode 100644 index 0000000000000000000000000000000000000000..2a24a5d1ae5aa0b906b8ab50a7760db38cfd2259 --- /dev/null +++ b/task_001/tests/pixel_changes.js @@ -0,0 +1,49 @@ +// Locate a rendered transition without prescribing an HTML class, fixed device +// coordinate or even whether it is painted in a canvas. +async function pixelChanges(page, frames) { + return page.evaluate(async encoded => { + const images = await Promise.all(encoded.map(async source => { + const image = new Image(); + image.src = 'data:image/png;base64,' + source; + await image.decode(); + return image; + })); + const {width, height} = images[0]; + const canvas = document.createElement('canvas'); + canvas.width = width; + canvas.height = height; + const context = canvas.getContext('2d', {willReadFrequently: true}); + const pixels = images.map(image => { + context.clearRect(0, 0, width, height); + context.drawImage(image, 0, 0); + return context.getImageData(0, 0, width, height).data; + }); + const different = (a, b, i) => Math.max( + Math.abs(a[i] - b[i]), Math.abs(a[i + 1] - b[i + 1]), Math.abs(a[i + 2] - b[i + 2]), + ) >= 16; + const tile = 8; + const columns = Math.ceil(width / tile); + const points = Array.from({length: columns * Math.ceil(height / tile)}, () => [0, 0, 0]); + let novel = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const i = (y * width + x) * 4; + if (!different(pixels[0], pixels[1], i)) continue; + const bucket = points[Math.floor(y / tile) * columns + Math.floor(x / tile)]; + bucket[0] += 1; + bucket[1] += x; + bucket[2] += y; + if (pixels.length === 4 + && (!different(pixels[2], pixels[3], i) || different(pixels[1], pixels[3], i))) novel += 1; + } + } + return { + points: points.filter(([weight]) => weight > 0) + .sort(([a], [b]) => b - a).slice(0, 56) + .map(([weight, x, y]) => ({x: x / weight, y: y / weight})), + novel, + }; + }, frames.map(frame => frame.toString('base64'))); +} + +module.exports = {pixelChanges}; diff --git a/task_001/tests/task_contract.json b/task_001/tests/task_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..697d9e18b29c944c54aa98a5c83680ad00fe7f26 --- /dev/null +++ b/task_001/tests/task_contract.json @@ -0,0 +1,23 @@ +{ + "task_id": 1, + "semantics": { + "any": ["15", "15x15", "grid-template-columns", "225"], + "all_groups": [ + ["winner", "赢家", "胜利", "赢", "胜"], + ["easter", "彩蛋"], + ["click", "onclick", "addeventlistener", "mousedown", "pointerdown"], + ["board", "棋盘", "grid", "canvas"] + ], + "compat": { + "minSourceBytes": 500 + } + }, + "browser": { + "type": "gomoku", + "selectors": { + "cell": ".cell,[data-r][data-c]", + "status": "#status", + "reset": "#reset" + } + } +} diff --git a/task_001/tests/test.sh b/task_001/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5674a34262d96d70626bf0890258fe737ea95264 --- /dev/null +++ b/task_001/tests/test.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +run validate_lines.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_001/tests/validate_aaav_dynamic.js b/task_001/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..3517d8b5a64867320fc214a049fee6e514cb1c2e --- /dev/null +++ b/task_001/tests/validate_aaav_dynamic.js @@ -0,0 +1,149 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 1; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const launchArgs = (process.env.PLAYWRIGHT_LAUNCH_ARGS || process.env.PW_LAUNCH_ARGS || "--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage").split(/\s+/).filter(Boolean); + const browser = await chromium.launch({ headless: true, args: launchArgs }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_001/tests/validate_browser_smoke.js b/task_001/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..658969881ac5de913eb45fddd8f4e1aae56c7ff5 --- /dev/null +++ b/task_001/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_001/tests/validate_enhanced_cases.js b/task_001/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..6759e50ee555370f95cffbb9cef6515d00a309a7 --- /dev/null +++ b/task_001/tests/validate_enhanced_cases.js @@ -0,0 +1,104 @@ +const fs = require('fs'); +const path = require('path'); +const {pathToFileURL} = require('url'); +const {chromium} = require('playwright'); +const {pixelChanges} = require('./pixel_changes'); +const assert = (value, message) => { if (!value) throw Error(message); }; +const entry = fs.readdirSync(process.cwd()).find(name => name.endsWith('.html')); + +(async () => { + assert(entry, 'missing HTML entry'); + const browser = await chromium.launch({headless: true, args: ['--no-sandbox']}); + try { + const page = await browser.newPage({viewport: {width: 1280, height: 1000}}); + await page.clock.install({time: new Date('2026-01-01T00:00:00Z')}); + await page.clock.pauseAt(new Date('2026-01-01T00:00:01Z')); + await page.goto(pathToFileURL(path.join(process.cwd(), entry)).href); + const image = await browser.newPage(); + const state = () => page.evaluate(() => window.gameTest.state()); + const reset = () => page.evaluate(() => window.gameTest.reset()); + const move = (r, c) => page.evaluate(([row, col]) => window.gameTest.move(row, col), [r, c]); + assert(await page.evaluate(() => !!window.gameTest), 'missing public gameTest API'); + + await reset(); + let initial = await state(); + assert(initial.size === 15 && initial.board.length === 15 && initial.board.every(row => row.length === 15 && row.every(cell => cell === null)), 'reset must create empty 15x15 board'); + assert(!initial.winner && !initial.easterEgg, 'reset must clear winner and easter egg'); + await move(4, 4); + const oneMove = await state(); + assert(oneMove.board[4][4] !== null && !oneMove.winner && !oneMove.easterEgg, 'one stone cannot win'); + for (const invalid of [[4, 4], [-1, 4], [15, 0], [-1, 15], [1, -1], [0, 15]]) { + await move(...invalid); + assert(JSON.stringify(await state()) === JSON.stringify(oneMove), 'occupied or out-of-range move changed state'); + } + + // The test API must operate the visible board, not a hidden parallel + // state machine. Compare two even-move positions: the same player is to + // move and any turn label is unchanged, so new stones must alter pixels. + await reset(); + await move(2, 3); await move(11, 12); + const twoStones = await page.screenshot({animations: 'disabled'}); + await move(4, 5); await move(9, 10); + const fourStones = await page.screenshot({animations: 'disabled'}); + assert(!twoStones.equals(fourStones), 'gameTest moves changed internal state but not the visible board'); + + // Recover the click area from the painted stone itself. This also works + // for canvas boards and does not require a named hook or a fitted grid. + const frame = async () => { + await page.clock.runFor(40); + return page.screenshot({animations: 'disabled'}); + }; + await reset(); + const beforeClick = await frame(); + await move(7, 7); + const {points} = await pixelChanges(image, [beforeClick, await frame()]); + let physicalMove = false; + for (const {x, y} of points) { + await reset(); + await page.mouse.click(x, y); + const board = (await state()).board; + if (board[7][7] !== null && board.flat().filter(cell => cell !== null).length === 1) { + physicalMove = true; + break; + } + } + assert(physicalMove, 'clicking the rendered board must place exactly one stone in its own state'); + await page.mouse.move(0, 0); + + const play = async (moves, winnerLabel) => { + await reset(); + for (let i = 0; i < moves.length; i++) { + await move(...moves[i]); + const snapshot = await state(); + if (i < moves.length - 1) assert(!snapshot.winner && !snapshot.easterEgg, `${winnerLabel} declared victory early`); + } + const finished = await state(); + assert(finished.winner && finished.easterEgg, `${winnerLabel} five-in-a-row not recognized`); + return finished; + }; + const winMoves = [[1,1],[9,0],[2,2],[9,2],[3,3],[9,4],[4,4],[9,6],[5,5]]; + const blackDiagonal = await play(winMoves, 'diagonal'); + const whiteHorizontal = await play([[10,0],[0,0],[11,2],[0,1],[12,4],[0,2],[13,6],[0,3],[14,8],[0,4]], 'white horizontal'); + assert(blackDiagonal.winner !== whiteHorizontal.winner, 'both players reported the same winner'); + assert(blackDiagonal.board[1][1] !== blackDiagonal.board[9][0], 'player stones must have distinct values'); + const trace = async moves => { + await reset(); + for (const position of moves.slice(0, -1)) await move(...position); + const before = await frame(); + await move(...moves.at(-1)); + await page.clock.runFor(750); + return [before, await frame()]; + }; + const winning = await trace(winMoves); + const ordinary = await trace([[1,1],[9,0],[2,2],[9,2],[3,3],[9,4],[4,3],[9,6],[5,5]]); + assert(!(await state()).winner, 'comparison placement unexpectedly won'); + const {novel} = await pixelChanges(image, [...winning, ...ordinary]); + assert(novel >= 12, 'victory must alter visible output beyond an ordinary final stone or turn update'); + await reset(); + initial = await state(); + assert(initial.board.every(row => row.every(cell => cell === null)) && !initial.winner && !initial.easterEgg, 'reset after victory did not clear game'); + console.log('Gomoku reset, illegal move, diagonal and both-player win checks passed'); + } finally { + await browser.close(); + } +})().catch(error => { console.error(error); process.exit(1); }); diff --git a/task_001/tests/validate_lines.js b/task_001/tests/validate_lines.js new file mode 100644 index 0000000000000000000000000000000000000000..78332be9bdf677265adb9cceddf1262c6ddf00e8 --- /dev/null +++ b/task_001/tests/validate_lines.js @@ -0,0 +1,86 @@ +const fs = require('fs'); +const path = require('path'); +const {pathToFileURL} = require('url'); +const {chromium} = require('playwright'); +const assert = (value, message) => { if (!value) throw Error(message); }; +const OUTPUT = '/logs/verifier/visual'; + +function winningMoves(start, direction, secondPlayer) { + // Last stone joins two shorter runs, exercising both sides of the new stone. + const line = [0, 4, 1, 3, 2].map(i => [start[0] + direction[0] * i, start[1] + direction[1] * i]); + const distractors = [[14, 0], [14, 2], [14, 4], [14, 6], [14, 8]]; + return line.flatMap((point, i) => secondPlayer ? [distractors[i], point] + : i === line.length - 1 ? [point] : [point, distractors[i]]); +} + +(async () => { + const entry = path.join(process.cwd(), 'index.html'); + assert(fs.existsSync(entry), 'missing public index.html entry'); + const browser = await chromium.launch({headless: true, args: ['--no-sandbox']}); + try { + fs.mkdirSync(OUTPUT, {recursive: true}); + const page = await browser.newPage({viewport: {width: 1100, height: 900}}); + await page.route(/^https?:/, route => route.abort()); + await page.goto(pathToFileURL(entry).href); + const state = () => page.evaluate(() => window.gameTest.state()); + const reset = () => page.evaluate(() => window.gameTest.reset()); + const move = (r, c) => page.evaluate(([row, col]) => window.gameTest.move(row, col), [r, c]); + const capture = name => page.screenshot({path: path.join(OUTPUT, `${name}.png`), animations: 'disabled'}); + await reset(); + const firstPlayer = (await state()).current; + await capture('01-empty'); + await move(2, 3); await move(11, 12); + await capture('02-two-stones'); + await move(4, 5); await move(9, 10); + await capture('03-four-stones'); + const directions = [ + ['horizontal', [0, 0], [0, 1]], + ['vertical', [0, 14], [1, 0]], + ['diagonal', [0, 0], [1, 1]], + ['anti-diagonal', [0, 14], [1, -1]], + ['interior-horizontal', [7, 5], [0, 1]], + ['interior-vertical', [5, 7], [1, 0]], + ]; + const winners = [null, null]; + for (const [label, start, direction] of directions) { + for (const secondPlayer of [false, true]) { + const moves = winningMoves(start, direction, secondPlayer); + await reset(); + for (let i = 0; i < moves.length; i++) { + await move(...moves[i]); + const snapshot = await state(); + if (i < moves.length - 1) assert(!snapshot.winner && !snapshot.easterEgg, + `${label}/${secondPlayer}: premature victory`); + } + const finished = await state(); + assert(finished.winner && finished.easterEgg, `${label}/${secondPlayer}: missed five-in-a-row`); + const player = Number(secondPlayer); + if (winners[player] !== null) assert(winners[player] === finished.winner, 'winner labels must be consistent'); + winners[player] = finished.winner; + if (label === 'horizontal' && !secondPlayer) await capture('04-first-player-win'); + if (label === 'anti-diagonal' && secondPlayer) await capture('05-second-player-win'); + } + } + assert(winners[0] !== winners[1], 'players reported the same winner'); + for (const points of [ + [[3, 0], [3, 2], [3, 4], [3, 6], [3, 8]], + [[4, 0], [4, 1], [4, 3], [4, 4], [4, 5]], + ]) { + await reset(); + for (let i = 0; i < points.length; i++) { + await move(...points[i]); + const snapshot = await state(); + assert(!snapshot.winner && !snapshot.easterEgg, 'disconnected stones declared a win'); + if (i < points.length - 1) await move(12, i * 2); + } + } + await reset(); + const cleared = await state(); + assert(cleared.current === firstPlayer && !cleared.winner && !cleared.easterEgg + && cleared.board.every(row => row.every(cell => cell === null)), 'reset must restore initial state'); + await capture('06-reset'); + console.log('All win directions, both players, joined runs, gaps and reset passed'); + } finally { + await browser.close(); + } +})().catch(error => { console.error(error); process.exit(1); }); diff --git a/task_001/tests/validate_semantics.js b/task_001/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..d10cc042756f6e9dba39b8f2484d59aaea267cc8 --- /dev/null +++ b/task_001/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_002/acceptance_checklist.json b/task_002/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..561a21f0097659d2bcc970a214b415a47157838d --- /dev/null +++ b/task_002/acceptance_checklist.json @@ -0,0 +1,18 @@ +{ + "task_id": 2, + "category": "frontend_development", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies." + ], + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_002/environment/Dockerfile b/task_002/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_002/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_002/environment/code/.gitkeep b/task_002/environment/code/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/task_002/environment/docker-compose.yaml b/task_002/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_002/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_002/instruction.md b/task_002/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..94ed188f230a8a954a6c1dac499c2ba632fe3c16 --- /dev/null +++ b/task_002/instruction.md @@ -0,0 +1,16 @@ +# Memory matching game + +Build a browser game with a 4×4 grid of cards containing eight pairs. Let the player reveal cards with a flip animation and match pairs. Deliver an offline `index.html` at the project root. + +## Interaction and state interface + +Expose `window.gameTest` with `reset(deck?)`, `flip(index)`, `advance(milliseconds)`, and `state()`. If supplied, use the 16-item deck in its given order. Return `{cards:[{value, faceUp, matched}, ...], moves, matchedPairs}`. The API operates on the same cards and game logic as clicks. Advancing virtual time only advances the mismatch wait and updates the display. + +The first eligible flip reveals a card. A second eligible flip counts one move. Matching cards remain face up; mismatches are visible for 300–2000 ms, then both turn face down. No third flip is allowed while a mismatch is pending, and face-up or matched cards cannot be flipped again. + +## Acceptance Checklist + +- The offline page renders the cards; flipping reveals the selected value on the same board used by the state interface. +- A supplied deck keeps its order. The first flip does not count a move; the second counts exactly one. Duplicate flips and flips during the mismatch wait leave state unchanged. +- A mismatch turns back within the allowed delay without counting another move. All eight pairs can be matched; matched cards stay visible and the counters reflect completed turns and matches. +- Reset hides and unmatches all cards, clears both counters and cancels any pending mismatch, even if a new pair is played immediately afterward. diff --git a/task_002/quality_notes.md b/task_002/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..160c1210219d27d8536b80599a676d09b212afe9 --- /dev/null +++ b/task_002/quality_notes.md @@ -0,0 +1,3 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. \ No newline at end of file diff --git a/task_002/solution/README.md b/task_002/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_002/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_002/solution/code/index.html b/task_002/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..b43d4f1a569e654558021ae5910acfeb15ba788a --- /dev/null +++ b/task_002/solution/code/index.html @@ -0,0 +1,128 @@ + + + + + +4x4 Card Memory Match + + + +

4x4 Card Memory Match

+
Matched 0 / 8 pairs · Moves 0
+
+ + + + + diff --git a/task_002/solution/solve.sh b/task_002/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_002/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_002/task.toml b/task_002/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_002/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_002/task_meta.json b/task_002/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..a72f54f423bf727479d01584c0a939bc75e90c70 --- /dev/null +++ b/task_002/task_meta.json @@ -0,0 +1,18 @@ +{ + "task_id": 2, + "task_category": "frontend_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 4, + "language": "javascript", + "tool_files_from_selected_trace": [ + "memory-game.html" + ], + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "source_row_id": 12, + "repair_revision": "2026-09-29", + "instruction_sha256": "8ab065d0621c58492f4c34d00d09f4777ab4377cc82aaf5bd404085651992fe5" +} diff --git a/task_002/tests/_shared/contract_checker.js b/task_002/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..c4cb421bebaee8ec0da34d465223d8207ac44860 --- /dev/null +++ b/task_002/tests/_shared/contract_checker.js @@ -0,0 +1,577 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + + // Read each card's symbol so we can drive a guaranteed-equal and a + // guaranteed-different pair instead of relying on the (shuffled) order. + const symbolAttr = sel.symbolAttr || 'data-symbol'; + const symbols = await page.evaluate(({ cardSel, symbolAttr }) => { + return Array.from(document.querySelectorAll(cardSel)).map((c) => c.getAttribute(symbolAttr)); + }, { cardSel, symbolAttr }); + + if (symbols.every((s) => s != null && s !== '')) { + // find a matching pair (same symbol) and a mismatching pair (different symbols) + let matchPair = null; + for (let i = 0; i < symbols.length && !matchPair; i++) { + for (let j = i + 1; j < symbols.length; j++) { + if (symbols[i] === symbols[j]) { matchPair = [i, j]; break; } + } + } + let diffPair = null; + for (let i = 0; i < symbols.length && !diffPair; i++) { + for (let j = i + 1; j < symbols.length; j++) { + if (symbols[i] !== symbols[j]) { diffPair = [i, j]; break; } + } + } + if (matchPair) { + await page.locator(cardSel).nth(matchPair[0]).click({ force: true }); + await page.waitForTimeout(120); + await page.locator(cardSel).nth(matchPair[1]).click({ force: true }); + await page.waitForTimeout(900); + const matchedOk = await page.evaluate(({ cardSel, pair }) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return cards[pair[0]].classList.contains('matched') && cards[pair[1]].classList.contains('matched'); + }, { cardSel, pair: matchPair }); + if (!matchedOk) { + throw new Error('two equal-symbol cards should both gain the matched class'); + } + } + // Fresh game for the mismatch trial: reload the page so card state is + // clean regardless of whether (or how) a reset control is implemented + // (the instruction never mandates a reset button or its id). If a reset + // control happens to exist, click it too as a best-effort re-init. + const resetSel = pick([ + sel.reset, + '#reset', + '#restart', + '[data-testid="reset"]', + '[data-testid="restart"]', + ]); + if (await page.locator(resetSel).count()) { + await page.locator(resetSel).first().click({ force: true }).catch(() => {}); + await page.waitForTimeout(150); + } + await page.reload({ waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(350); + const symbols2 = await page.evaluate(({ cardSel, symbolAttr }) => { + return Array.from(document.querySelectorAll(cardSel)).map((c) => c.getAttribute(symbolAttr)); + }, { cardSel, symbolAttr }); + let diffPair2 = null; + for (let i = 0; i < symbols2.length && !diffPair2; i++) { + for (let j = i + 1; j < symbols2.length; j++) { + if (symbols2[i] !== symbols2[j]) { diffPair2 = [i, j]; break; } + } + } + const usePair = diffPair2 || diffPair; + if (usePair) { + await page.locator(cardSel).nth(usePair[0]).click({ force: true }); + await page.waitForTimeout(120); + await page.locator(cardSel).nth(usePair[1]).click({ force: true }); + await page.waitForTimeout(1100); // wait past the mismatch unflip delay + const mismatchOk = await page.evaluate(({ cardSel, pair }) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return !cards[pair[0]].classList.contains('matched') && !cards[pair[1]].classList.contains('matched'); + }, { cardSel, pair: usePair }); + if (!mismatchOk) { + throw new Error('two different-symbol cards should not retain the matched class'); + } + } + await browser.close(); + return; + } + + // Fallback (no per-card symbol attr): generic "interaction changes state". + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode, contractDir }) { + const contract = readContract(contractDir || taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_002/tests/_shared/static_enhancer.sh b/task_002/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_002/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_002/tests/enhancement_cases.json b/task_002/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..b907bc5ce175fe63af6d5b6574113def1355cde9 --- /dev/null +++ b/task_002/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","instruction_evidence":"用4x4的卡牌网格","validator":"validate_enhanced_cases.js","behavior":"页面提供恰好16张可交互卡牌"}, + {"case_id":"ENHANCED_CASE_2","instruction_evidence":"实现卡牌翻转动画","validator":"validate_enhanced_cases.js","behavior":"点击背面卡牌产生可见翻转状态"}, + {"case_id":"ENHANCED_CASE_3","instruction_evidence":"基本匹配逻辑","validator":"validate_enhanced_cases.js","behavior":"两张同面卡牌配对后保持已匹配可见状态"} +] diff --git a/task_002/tests/pixel_changes.js b/task_002/tests/pixel_changes.js new file mode 100644 index 0000000000000000000000000000000000000000..2a24a5d1ae5aa0b906b8ab50a7760db38cfd2259 --- /dev/null +++ b/task_002/tests/pixel_changes.js @@ -0,0 +1,49 @@ +// Locate a rendered transition without prescribing an HTML class, fixed device +// coordinate or even whether it is painted in a canvas. +async function pixelChanges(page, frames) { + return page.evaluate(async encoded => { + const images = await Promise.all(encoded.map(async source => { + const image = new Image(); + image.src = 'data:image/png;base64,' + source; + await image.decode(); + return image; + })); + const {width, height} = images[0]; + const canvas = document.createElement('canvas'); + canvas.width = width; + canvas.height = height; + const context = canvas.getContext('2d', {willReadFrequently: true}); + const pixels = images.map(image => { + context.clearRect(0, 0, width, height); + context.drawImage(image, 0, 0); + return context.getImageData(0, 0, width, height).data; + }); + const different = (a, b, i) => Math.max( + Math.abs(a[i] - b[i]), Math.abs(a[i + 1] - b[i + 1]), Math.abs(a[i + 2] - b[i + 2]), + ) >= 16; + const tile = 8; + const columns = Math.ceil(width / tile); + const points = Array.from({length: columns * Math.ceil(height / tile)}, () => [0, 0, 0]); + let novel = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const i = (y * width + x) * 4; + if (!different(pixels[0], pixels[1], i)) continue; + const bucket = points[Math.floor(y / tile) * columns + Math.floor(x / tile)]; + bucket[0] += 1; + bucket[1] += x; + bucket[2] += y; + if (pixels.length === 4 + && (!different(pixels[2], pixels[3], i) || different(pixels[1], pixels[3], i))) novel += 1; + } + } + return { + points: points.filter(([weight]) => weight > 0) + .sort(([a], [b]) => b - a).slice(0, 56) + .map(([weight, x, y]) => ({x: x / weight, y: y / weight})), + novel, + }; + }, frames.map(frame => frame.toString('base64'))); +} + +module.exports = {pixelChanges}; diff --git a/task_002/tests/task_contract.json b/task_002/tests/task_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..3a2af670e58364d66ead2d58d5768d22f7230c45 --- /dev/null +++ b/task_002/tests/task_contract.json @@ -0,0 +1,21 @@ +{ + "task_id": 2, + "semantics": { + "all": ["flip", "match", "card"], + "any": ["4x4", "16", "grid-template-columns"], + "all_groups": [["match", "flip"], ["card", "cards"], ["button", "addEventListener", "onclick"]], + "min_tokens": { + "card": 1 + }, + "compat": { + "minSourceBytes": 500 + } + }, + "browser": { + "type": "memory_match", + "selectors": { + "card": ".card", + "reset": "#reset" + } + } +} diff --git a/task_002/tests/test.sh b/task_002/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5b93094e3a03087c4e33dbad0e01077a559a54e5 --- /dev/null +++ b/task_002/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_002/tests/validate_aaav_dynamic.js b/task_002/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..96a23568dfce3a6c4520183f9bcea0ec60f91f64 --- /dev/null +++ b/task_002/tests/validate_aaav_dynamic.js @@ -0,0 +1,149 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 2; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const launchArgs = (process.env.PLAYWRIGHT_LAUNCH_ARGS || process.env.PW_LAUNCH_ARGS || "--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage").split(/\s+/).filter(Boolean); + const browser = await chromium.launch({ headless: true, args: launchArgs }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_002/tests/validate_browser_smoke.js b/task_002/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..658969881ac5de913eb45fddd8f4e1aae56c7ff5 --- /dev/null +++ b/task_002/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_002/tests/validate_enhanced_cases.js b/task_002/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..91e70892a69c9a6c6387ef9db1e7b5fa8efdaed0 --- /dev/null +++ b/task_002/tests/validate_enhanced_cases.js @@ -0,0 +1,134 @@ +const fs = require('fs'); +const path = require('path'); +const {pathToFileURL} = require('url'); +const {chromium} = require('playwright'); +const {pixelChanges} = require('./pixel_changes'); +const assert = (value, message) => { if (!value) throw Error(message); }; +const entry = 'index.html'; + +(async () => { + assert(fs.existsSync(entry), 'missing public index.html entry'); + const browser = await chromium.launch({headless: true, args: ['--no-sandbox']}); + try { + const page = await browser.newPage({viewport: {width: 1280, height: 1000}}); + const image = await browser.newPage(); + await page.clock.install({time: new Date('2026-01-01T00:00:00Z')}); + await page.clock.pauseAt(new Date('2026-01-01T00:00:01Z')); + await page.goto(pathToFileURL(path.join(process.cwd(), entry)).href); + const deck = ['A','B','A','B','C','C','D','D','E','E','F','F','G','G','H','H']; + const state = () => page.evaluate(() => gameTest.state()); + const flip = index => page.evaluate(i => gameTest.flip(i), index); + const advance = ms => page.evaluate(t => gameTest.advance(t), ms); + await page.evaluate(d => gameTest.reset(d), deck); + let current = await state(); + assert(current.cards.length === 16 && current.cards.every((card, index) => card.value === deck[index] && !card.faceUp && !card.matched), 'reset must preserve deck order and hide all cards'); + assert(current.moves === 0 && current.matchedPairs === 0, 'reset counters must be zero'); + + // Two one-card states have the same counters and selected position but + // different underlying values. A highlight-only "flip" cannot pass. + const covered = await page.screenshot({animations: 'disabled'}); + await flip(0); await page.waitForTimeout(450); + const firstFace = await page.screenshot({animations: 'disabled'}); + const swapped = [...deck]; [swapped[0], swapped[1]] = [swapped[1], swapped[0]]; + await page.evaluate(d => gameTest.reset(d), swapped); + await flip(0); await page.waitForTimeout(450); + const secondFace = await page.screenshot({animations: 'disabled'}); + assert(!firstFace.equals(secondFace), 'logical card flips did not reveal the card value'); + const {points} = await pixelChanges(image, [covered, firstFace]); + let userFlip = false; + let animated = false; + for (const {x, y} of points) { + await page.evaluate(d => gameTest.reset(d), deck); + await page.mouse.move(x, y); + const clip = {x: Math.max(0, Math.floor(x) - 20), y: Math.max(0, Math.floor(y) - 20), + width: 40, height: 40}; + const beforeMotion = await page.evaluateHandle(({x, y}) => { + const current = new Set(document.getAnimations().filter(animation => { + const bounds = animation.effect?.target?.getBoundingClientRect(); + return animation.playState === 'running' && bounds && x >= bounds.left && x <= bounds.right + && y >= bounds.top && y <= bounds.bottom; + })); + for (const animation of current) animation.pause(); + return current; + }, {x, y}); + const before = await page.screenshot({clip, animations: 'allow'}); + await page.mouse.click(x, y); + const clicked = await state(); + if (!clicked.cards[0].faceUp || clicked.cards.filter(card => card.faceUp).length !== 1) { + await beforeMotion.evaluate(previous => { for (const animation of previous) animation.play(); }); + await beforeMotion.dispose(); + continue; + } + userFlip = true; + animated = await page.evaluate(({x, y, previous}) => document.getAnimations().some(animation => { + const bounds = animation.effect?.target?.getBoundingClientRect(); + return !previous.has(animation) && animation.playState === 'running' && bounds && x >= bounds.left && x <= bounds.right + && y >= bounds.top && y <= bounds.bottom; + }), {x, y, previous: beforeMotion}); + await beforeMotion.dispose(); + if (!animated) { + const during = []; + for (const elapsed of [0, 16, 32, 64, 128, 256, 512]) { + await page.clock.runFor(elapsed); + during.push(await page.screenshot({clip, animations: 'allow'})); + } + const after = during.at(-1); + animated = during.some(frame => !frame.equals(before) && !frame.equals(after)); + } + break; + } + assert(userFlip, 'clicking the rendered card must flip the same card tracked by the game'); + assert(animated, 'user flips must produce an observable card animation'); + await page.evaluate(d => gameTest.reset(d), deck); + + await flip(0); + current = await state(); + assert(current.cards[0].faceUp && current.moves === 0, 'first flip must not count a move'); + await flip(0); + assert(JSON.stringify(await state()) === JSON.stringify(current), 're-flipping same card changed state'); + await flip(1); + current = await state(); + assert(current.cards[0].faceUp && current.cards[1].faceUp && current.moves === 1 && current.matchedPairs === 0, 'mismatch must stay visible and count one move'); + await flip(4); + assert(JSON.stringify(await state()) === JSON.stringify(current), 'third card flipped during mismatch lock'); + await advance(299); + current = await state(); + assert(current.cards[0].faceUp && current.cards[1].faceUp, 'mismatch delay was shorter than 300ms'); + await advance(1701); + current = await state(); + assert(!current.cards[0].faceUp && !current.cards[1].faceUp && current.moves === 1, 'mismatch did not flip back without extra move'); + + await flip(0); + await flip(2); + await advance(1000); + current = await state(); + assert(current.cards[0].matched && current.cards[2].matched && current.cards[0].faceUp && current.cards[2].faceUp, 'match must remain face up'); + assert(current.moves === 2 && current.matchedPairs === 1, 'match counters wrong'); + await flip(0); + assert(JSON.stringify(await state()) === JSON.stringify(current), 'matched card was flipped again'); + await flip(1); + await flip(3); + current = await state(); + assert(current.matchedPairs === 2 && current.moves === 3, 'second pair counters wrong'); + for (let i = 4; i < 16; i += 2) { + await flip(i); await flip(i + 1); + } + current = await state(); + assert(current.matchedPairs === 8 && current.moves === 9 + && current.cards.every(card => card.faceUp && card.matched), 'all eight pairs must be matchable'); + await page.evaluate(d => gameTest.reset(d), deck); + current = await state(); + assert(current.moves === 0 && current.matchedPairs === 0 && current.cards.every(card => !card.faceUp && !card.matched), 'reset after matches did not clear state'); + await flip(0); await flip(1); + await page.evaluate(d => gameTest.reset(d), deck); + await flip(4); await flip(5); + await advance(2500); + current = await state(); + assert(current.moves === 1 && current.matchedPairs === 1 + && current.cards[4].faceUp && current.cards[5].faceUp, + 'stale mismatch state affected the new game'); + console.log('memory-game deck, mismatch lock, time and counter checks passed'); + } finally { + await browser.close(); + } +})().catch(error => { console.error(error); process.exit(1); }); diff --git a/task_002/tests/validate_semantics.js b/task_002/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..d10cc042756f6e9dba39b8f2484d59aaea267cc8 --- /dev/null +++ b/task_002/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_003/acceptance_checklist.json b/task_003/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..ff477fdf39a54ef01338b172dd72284dc8cbfa4e --- /dev/null +++ b/task_003/acceptance_checklist.json @@ -0,0 +1,18 @@ +{ + "task_id": 3, + "category": "frontend_development", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies." + ], + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_003/environment/Dockerfile b/task_003/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_003/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_003/environment/code/.gitkeep b/task_003/environment/code/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/task_003/environment/docker-compose.yaml b/task_003/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_003/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_003/instruction.md b/task_003/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..727ae1f216f8b98115e65fa2d36228552fc0c2fa --- /dev/null +++ b/task_003/instruction.md @@ -0,0 +1,17 @@ +# Browser tower-defense prototype + +Build a simple 2D tower-defense game that runs offline from the root `index.html`. Render a map with a path, enemies that travel along it, and a tower type the player can place. A tower damages enemies within range. An enemy that reaches the end without being defeated costs one life and does not count as a kill. + +## Simulation interface + +Expose `window.gameTest` with `reset()`, `spawnEnemy(options?)`, `placeTower(x, y, options?)`, `step(milliseconds)`, and `state()`. Use the same movement, combat and rendering as the game. After `reset()`, only explicit steps advance the deterministic scenario, and the page reflects those updates. + +Return `{path, enemies, towers, lives, kills}`. The path contains at least two distinct `{x, y}` points in scene pixels. An enemy exposes `{seg, t, hp, speed, position}`; `t` is progress from 0 to 1 along segment `seg`, and `position` is `{x, y}` or `null`. A new enemy starts on segment 0 at progress 0 with 3 HP. `spawnEnemy({speed: 0})` keeps it at the start; no options uses normal speed. A tower exposes `{x, y, range}`. `placeTower(x, y, {range})` uses the supplied finite, nonnegative range; otherwise use the default. + +Advance movement and combat in 16 ms steps, carrying a remainder into the next call. `step(0)` does not advance the simulation. A newly placed tower damages an enemy that remains within range within 2,048 ms; it deals no damage outside range. + +## Acceptance Checklist + +- The offline entry renders the map and spawned enemies. Enemy progress and position stay consistent with the path; an escaped enemy is removed, costs one life and does not award a kill. +- Zero or sub-step time advances do not move an enemy. Accumulated time triggers the next fixed step, and the scene reflects simulation updates. +- A zero-speed enemy stays in place. Towers honor range overrides and damage or defeat continuously in-range enemies within the specified time without damaging out-of-range enemies. diff --git a/task_003/quality_notes.md b/task_003/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..160c1210219d27d8536b80599a676d09b212afe9 --- /dev/null +++ b/task_003/quality_notes.md @@ -0,0 +1,3 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. \ No newline at end of file diff --git a/task_003/solution/README.md b/task_003/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_003/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_003/solution/code/index.html b/task_003/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..1d44b4f0b63a852236fc4a9bc8a82900a3277a06 --- /dev/null +++ b/task_003/solution/code/index.html @@ -0,0 +1,165 @@ + + + + + +2D Tower Defense Framework + + + +

2D Tower Defense Framework

+
Lives: 10 · Kills: 0 · Towers: 0
+ +
+ + +
+

Click an empty area of the map to place a tower (cost: 1). Enemies move along the path from left to right.

+ + + + diff --git a/task_003/solution/solve.sh b/task_003/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_003/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_003/task.toml b/task_003/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_003/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_003/task_meta.json b/task_003/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..e5d817a9ee7c277f36799b541cf678c2a9e6081e --- /dev/null +++ b/task_003/task_meta.json @@ -0,0 +1,19 @@ +{ + "task_id": 3, + "task_category": "frontend_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 4, + "language": "javascript", + "tool_files_from_selected_trace": [ + "game.js", + "index.html" + ], + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "source_row_id": 18, + "repair_revision": "2026-09-29", + "instruction_sha256": "8495cce939909e09799cb5068d4cea483f337092a2b29e9c10b121a08182918f" +} diff --git a/task_003/tests/_shared/contract_checker.js b/task_003/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..bae420b6e2c3b758968b3aa7f227c19aceb2ba3a --- /dev/null +++ b/task_003/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn', '#startBtn', '#startWave', '[data-testid="spawn"]', '[data-testid="start"]']); + const resetSel = pick([sel.reset, '#reset']); + const towerCountSel = sel.towerCount || '#towerCount'; + const killsSel = sel.kills || '#kills'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, towerCountSel, killsSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + const num = (s) => { + const el = document.querySelector(s); + return el ? el.innerText.trim() : null; + }; + return { + towerCount: num(towerCountSel), + kills: num(killsSel), + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { canvasSel, towerCountSel, killsSel }); + if (!before) throw new Error('canvas not found'); + // The instruction never mandates a spawn button or its id. Discover a + // wave/spawn control by a range of common ids/testids, or by button label + // (spawn/start/wave, English or Chinese). If none exists, the game may + // auto-spawn waves over time, so the control is optional. + let spawnLocator = null; + if (await page.locator(spawnSel).count()) { + spawnLocator = page.locator(spawnSel).first(); + } else { + const byText = page.getByRole('button', { name: /spawn|start|wave|生成|开始|波|怪|敌/i }); + if (await byText.count()) spawnLocator = byText.first(); + } + if (spawnLocator) { + await spawnLocator.click({ force: true }).catch(() => {}); + } + await page.waitForTimeout(900); + + // Place a tower on the canvas; the numeric tower-count HUD must increase. + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(400); + } + const afterPlace = await page.evaluate(({ towerCountSel, killsSel }) => { + const num = (s) => { + const el = document.querySelector(s); + return el ? el.innerText.trim() : null; + }; + return { towerCount: num(towerCountSel), kills: num(killsSel) }; + }, { towerCountSel, killsSel }); + + if (before.towerCount != null) { + if (toNumberText(afterPlace.towerCount) <= toNumberText(before.towerCount)) { + throw new Error('placing a tower should increase ' + towerCountSel + ' (' + before.towerCount + ' -> ' + afterPlace.towerCount + ')'); + } + } else { + // No numeric tower HUD: fall back to asserting some observable change. + const afterHud = await page.evaluate(() => (document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '')); + if (before.hud === afterHud) { + throw new Error('placing tower on canvas has no observable effect'); + } + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode, contractDir }) { + const contract = readContract(contractDir || taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_003/tests/_shared/static_enhancer.sh b/task_003/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_003/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_003/tests/enhancement_cases.json b/task_003/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..170eaf84e830b303b639a8792e9d80d683c54334 --- /dev/null +++ b/task_003/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","instruction_evidence":"设计基本游戏地图和路径系统","validator":"validate_enhanced_cases.js","behavior":"实际绘制非空游戏地图与路径"}, + {"case_id":"ENHANCED_CASE_2","instruction_evidence":"实现敌人沿路径移动的功能","validator":"validate_enhanced_cases.js","behavior":"生成敌人后多个时刻的渲染位置持续变化"}, + {"case_id":"ENHANCED_CASE_3","instruction_evidence":"添加一种基本塔类型,可以放置在地图上","validator":"validate_enhanced_cases.js","behavior":"通过可见建塔入口(如存在)并尝试多个地图位置后产生可见放塔变化"} +] diff --git a/task_003/tests/task_contract.json b/task_003/tests/task_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..39a4b220bd3ba4b57abd0bb8418e37a28c7a5da5 --- /dev/null +++ b/task_003/tests/task_contract.json @@ -0,0 +1,23 @@ +{ + "task_id": 3, + "semantics": { + "all": ["enemy", "path", "move", "tower"], + "any": ["canvas", "requestAnimationFrame", "spawn"], + "all_groups": [["canvas", "game"], ["path", "route"], ["tower", "spawn"]], + "min_tokens": { + "enemy": 1, + "tower": 1 + }, + "compat": { + "minSourceBytes": 500 + } + }, + "browser": { + "type": "tower_defense", + "selectors": { + "canvas": "#game", + "spawn": "#spawn", + "reset": "#reset" + } + } +} diff --git a/task_003/tests/test.sh b/task_003/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5b93094e3a03087c4e33dbad0e01077a559a54e5 --- /dev/null +++ b/task_003/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_003/tests/validate_aaav_dynamic.js b/task_003/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..8f65bc45abb85e40462ebbd9629245b16dd134f5 --- /dev/null +++ b/task_003/tests/validate_aaav_dynamic.js @@ -0,0 +1,149 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 3; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const launchArgs = (process.env.PLAYWRIGHT_LAUNCH_ARGS || process.env.PW_LAUNCH_ARGS || "--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage").split(/\s+/).filter(Boolean); + const browser = await chromium.launch({ headless: true, args: launchArgs }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_003/tests/validate_browser_smoke.js b/task_003/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..658969881ac5de913eb45fddd8f4e1aae56c7ff5 --- /dev/null +++ b/task_003/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_003/tests/validate_enhanced_cases.js b/task_003/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..09badf401a820bfb170e0fd1b6f59b0742be0bf4 --- /dev/null +++ b/task_003/tests/validate_enhanced_cases.js @@ -0,0 +1,105 @@ +const fs = require('fs'); +const path = require('path'); +const {pathToFileURL} = require('url'); +const {chromium} = require('playwright'); +const assert = (value, message) => { if (!value) throw Error(message); }; +const entry = path.join(process.cwd(), 'index.html'); + +(async () => { + const browser = await chromium.launch({headless: true, args: ['--no-sandbox']}); + try { + const page = await browser.newPage(); + await page.clock.install(); + await page.goto(pathToFileURL(entry).href); + await page.clock.pauseAt(new Date(Date.now() + 60000)); + const state = () => page.evaluate(() => gameTest.state()); + const step = milliseconds => page.evaluate(ms => gameTest.step(ms), milliseconds); + await page.evaluate(() => gameTest.reset()); + await step(0); // Ask the deterministic update path to repaint the empty map. + const emptyMap = await page.screenshot({animations: 'disabled'}); + await page.evaluate(() => gameTest.spawnEnemy()); + await step(0); // A zero-time update may repaint, but may not move the enemy. + const populatedMap = await page.screenshot({animations: 'disabled'}); + assert(!emptyMap.equals(populatedMap), 'spawned enemy exists in state but is not visible on the map'); + let current = await state(); + assert(current.path.length >= 2 && current.enemies.length === 1, 'path and spawned enemy required'); + assert(current.enemies[0].hp === 3 && current.enemies[0].seg === 0 && current.enemies[0].t === 0, 'spawn initial state wrong'); + const initial = current; + const initialSnapshot = JSON.stringify(initial); + await step(0); + assert(JSON.stringify(await state()) === initialSnapshot, 'zero-duration step changed state'); + await step(15); + assert(JSON.stringify(await state()) === initialSnapshot, 'subframe step advanced simulation early'); + await step(1); + current = await state(); + if (current.enemies.length) { + const moved = current.enemies[0]; + assert(moved.seg > 0 || moved.t > 0, 'accumulated 16ms did not advance enemy'); + const start = current.path[moved.seg], end = current.path[moved.seg + 1]; + assert(start && end && moved.t >= 0 && moved.t <= 1, 'enemy segment/progress invalid'); + assert(Math.hypot(moved.position.x - start.x - (end.x - start.x) * moved.t, + moved.position.y - start.y - (end.y - start.y) * moved.t) < 0.01, 'enemy position left path'); + } + current = await page.evaluate(() => { + const first = gameTest.state(); + const progressed = first.enemies[0]; + if (!progressed) return first; + const lengths = first.path.slice(1).map((end, index) => { + const start = first.path[index]; + return Math.hypot(end.x - start.x, end.y - start.y); + }); + const traveled = lengths.slice(0, progressed.seg).reduce((a, b) => a + b, 0) + + lengths[progressed.seg] * progressed.t; + const totalLength = lengths.reduce((a, b) => a + b, 0); + const byFraction = (first.path.length - 1) / (progressed.seg + progressed.t); + const byDistance = traveled > 0 ? totalLength / traveled : 0; + const remaining = 2 * Math.max(byFraction, byDistance); + // Allow much slower paths and implementations whose speed is in pixels rather + // than normalized segment fractions. Each public call advances one tick. + const limit = Math.min(100000, Math.max(10000, Math.ceil(remaining))); + let snapshot = first; + for (let ticks = 0; ticks < limit && snapshot.enemies.length; ticks += 32) { + gameTest.step(16 * 32); + snapshot = gameTest.state(); + } + return snapshot; + }); + assert(current.enemies.length === 0, 'normal-speed enemy did not reach the path end'); + assert(current.lives === initial.lives - 1 && current.kills === initial.kills, + 'an escaped enemy must cost one life without awarding a kill'); + await step(16); + current = await state(); + assert(current.lives === initial.lives - 1 && current.kills === initial.kills, + 'an escaped enemy must not be counted again on later steps'); + await page.evaluate(() => { gameTest.reset(); gameTest.spawnEnemy({speed: 0}); }); + current = await state(); + const enemy = current.enemies[0]; + assert(enemy?.position && enemy.hp === 3, 'stationary fixture enemy missing'); + const far = [...current.path].sort((a, b) => + Math.hypot(b.x - enemy.position.x, b.y - enemy.position.y) + - Math.hypot(a.x - enemy.position.x, a.y - enemy.position.y))[0]; + const distanceToFar = Math.hypot(far.x - enemy.position.x, far.y - enemy.position.y); + assert(distanceToFar > 0, 'path needs two distinct points'); + const range = distanceToFar / 2; + await page.evaluate(({x, y, range}) => gameTest.placeTower(x, y, {range}), {...far, range}); + const placed = (await state()).towers; + assert(placed.length === 1 && Number.isFinite(placed[0].range) && placed[0].range >= 0, + 'placed tower must expose a finite nonnegative range'); + assert(Math.abs(placed[0].range - range) < 1e-9, 'range override must be honored'); + const hp = enemy.hp; + await step(2048); + current = await state(); + assert(current.enemies[0]?.position, 'enemy disappeared during range check'); + assert(JSON.stringify(current.enemies[0].position) === JSON.stringify(enemy.position), 'speed zero must hold position'); + assert(current.enemies[0].hp === hp, 'far tower attacked out-of-range enemy'); + const near = current.enemies[0].position; + await page.evaluate(({x, y}) => gameTest.placeTower(x, y, {range: 1}), near); + await step(2048); + current = await state(); + assert(current.towers.length === 2, 'placed towers missing'); + assert(current.kills === 1 || (current.enemies.length === 1 && current.enemies[0].hp < hp), 'near tower did not attack'); + console.log('tower-defense fixed-step, path interpolation and range checks passed'); + } finally { + await browser.close(); + } +})().catch(error => { console.error(error); process.exit(1); }); diff --git a/task_003/tests/validate_semantics.js b/task_003/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..d10cc042756f6e9dba39b8f2484d59aaea267cc8 --- /dev/null +++ b/task_003/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_004/acceptance_checklist.json b/task_004/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..a616c6237c0670c5dd0d9818fa6d3f21ca279b51 --- /dev/null +++ b/task_004/acceptance_checklist.json @@ -0,0 +1,18 @@ +{ + "task_id": 4, + "category": "frontend_development", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies." + ], + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_004/environment/Dockerfile b/task_004/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_004/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_004/environment/code/.gitkeep b/task_004/environment/code/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/task_004/environment/docker-compose.yaml b/task_004/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_004/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_004/instruction.md b/task_004/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f06665ada0f37b8d4bed4f5938e53a14755efbcd --- /dev/null +++ b/task_004/instruction.md @@ -0,0 +1,21 @@ +# Four-player Ludo + +Build an offline Ludo game in HTML, CSS and JavaScript. Open the root `index.html` directly in a browser. Show the board, four pieces (in base or on the track), the active player, the latest roll and a victory message. Keep pieces visible even when they share a square. + +## Rules + +- Each player has one piece, a separate base, and a distinct starting square on a circular track of at least four squares. Players take turns rolling a six-sided die. A piece in base enters the track only on a 6, landing on its starting square with zero steps of progress. Other rolls in base leave it in place. +- A piece already on the track moves by the number rolled, wrapping around as needed. A 6 retains the turn; otherwise pass to the next player in order. +- The first player to accumulate at least one lap of steps after leaving base wins, even if the final roll overshoots. End the game with the winner as the current player. There are no captures, skipped squares or exact-roll requirements. After a win, rolls no longer change state. + +## State interface + +Expose `window.gameTest`: `reset()`, `setRolls(numbers)`, `roll()`, and `state()`. `setRolls` supplies the next rolls in order. `roll()` uses the same rules and rendering as the roll button, consuming a queued number if present; normal play uses random rolls. + +Return `{players:[{id, pos, start, steps}, ...], currentPlayer, lastRoll, trackLength}`. `currentPlayer` is a zero-based index cycling through 0–3. `pos` is `-1` in base and the zero-based track position otherwise; `steps` counts actual progress after entering the track. On reset, all pieces return to base, steps and queued rolls clear, `lastRoll` is `null`, the victory message clears, and player 0 starts. + +## Acceptance Checklist + +- The offline page renders, and pieces visibly follow moves made through the state interface. +- All four players start in their bases, enter at distinct starts on a 6, and move by the exact roll after entering. Queued rolls, turn order, extra turns and wraparound follow the rules. +- Each player can win by reaching or overshooting one lap. Rolls after victory leave state unchanged; reset restores all pieces and the initial turn without a stale roll. diff --git a/task_004/quality_notes.md b/task_004/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..160c1210219d27d8536b80599a676d09b212afe9 --- /dev/null +++ b/task_004/quality_notes.md @@ -0,0 +1,3 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. \ No newline at end of file diff --git a/task_004/solution/README.md b/task_004/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_004/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_004/solution/code/index.html b/task_004/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..9b82bf6c7ab88c2c4426b8f0c3c848993d54f51f --- /dev/null +++ b/task_004/solution/code/index.html @@ -0,0 +1,151 @@ + + + + + +Four-Player Aeroplane Chess + + + +

Four-Player Aeroplane Chess

+
Player 1's turn. Roll the dice.
+
+
+
+ + 🎲 +
+ + + + diff --git a/task_004/solution/solve.sh b/task_004/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_004/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_004/task.toml b/task_004/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_004/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_004/task_meta.json b/task_004/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..55d5d59260a4de690b62a0f62f845ea57257d4f1 --- /dev/null +++ b/task_004/task_meta.json @@ -0,0 +1,18 @@ +{ + "task_id": 4, + "task_category": "frontend_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 3, + "language": "javascript", + "tool_files_from_selected_trace": [ + "ludo-game.html" + ], + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "source_row_id": 24, + "repair_revision": "2026-09-29", + "instruction_sha256": "f1da7f2dae323f8e7bcc0d8a58ed3698b3bea23d25f7a9485b3e9003ec9f47bf" +} diff --git a/task_004/tests/_shared/contract_checker.js b/task_004/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1b1383126960c3e9c0625be5522c52e821faa587 --- /dev/null +++ b/task_004/tests/_shared/contract_checker.js @@ -0,0 +1,518 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + // Roll several times, recording the player indicator shown in #status + // after each roll. The current-player indicator must rotate. + const playerIndicator = (status) => { + const m = String(status).match(/玩家\s*(\d+)|player\s*(\d+)/i); + return m ? (m[1] || m[2]) : null; + }; + const indicators = new Set(); + let lastStatus = before.status; + for (let i = 0; i < 8; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + const cur = await page.evaluate((statusSel) => + statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', statusSel); + lastStatus = cur; + const ind = playerIndicator(cur); + if (ind != null) indicators.add(ind); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + // If the status exposes a numeric player indicator, it must rotate across rolls. + const initialInd = playerIndicator(before.status); + if (initialInd != null) { + if (indicators.size < 2) { + throw new Error('#status player indicator does not rotate across rolls (saw only: ' + + Array.from(indicators).join(',') + ', last="' + lastStatus + '")'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode, contractDir }) { + const contract = readContract(contractDir || taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_004/tests/_shared/static_enhancer.sh b/task_004/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_004/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_004/tests/enhancement_cases.json b/task_004/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..dae0743ab7c68175447fe963677413c77d0b44da --- /dev/null +++ b/task_004/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","instruction_evidence":"需要体现轮到哪个玩家(turn)以及四个玩家各自的位置","validator":"validate_enhanced_cases.js","behavior":"多次掷骰的可见状态覆盖四名不同玩家"}, + {"case_id":"ENHANCED_CASE_2","instruction_evidence":"根据点数随机向前移动","validator":"validate_enhanced_cases.js","behavior":"固定随机源后重复掷骰产生多个可复现可见结果状态"}, + {"case_id":"ENHANCED_CASE_3","instruction_evidence":"四名玩家轮流掷骰子;需要体现轮到哪个玩家(turn)","validator":"validate_enhanced_cases.js","behavior":"连续非六点掷骰后可见回合状态遍历四名玩家"} +] diff --git a/task_004/tests/task_contract.json b/task_004/tests/task_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..29a8dc98deaf60465e103b88c2c6d5ea4905b2cb --- /dev/null +++ b/task_004/tests/task_contract.json @@ -0,0 +1,23 @@ +{ + "task_id": 4, + "semantics": { + "all": ["dice", "player", "move"], + "any": ["4", "四", "Math.random", "roll"], + "all_groups": [["turn", "status"], ["board", "cell"], ["roll", "dice"]], + "min_tokens": { + "player": 1 + }, + "compat": { + "minSourceBytes": 500 + } + }, + "browser": { + "type": "ludo", + "selectors": { + "roll": "#roll", + "status": "#status", + "dice": "#dice", + "board": "#board" + } + } +} diff --git a/task_004/tests/test.sh b/task_004/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a7852957829b346b1b6aa415fb9963884bc37030 --- /dev/null +++ b/task_004/tests/test.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +run validate_finish.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_004/tests/validate_aaav_dynamic.js b/task_004/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..faca7a6da66905300643c837b40037bf15b5975f --- /dev/null +++ b/task_004/tests/validate_aaav_dynamic.js @@ -0,0 +1,149 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 4; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const launchArgs = (process.env.PLAYWRIGHT_LAUNCH_ARGS || process.env.PW_LAUNCH_ARGS || "--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage").split(/\s+/).filter(Boolean); + const browser = await chromium.launch({ headless: true, args: launchArgs }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_004/tests/validate_browser_smoke.js b/task_004/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..658969881ac5de913eb45fddd8f4e1aae56c7ff5 --- /dev/null +++ b/task_004/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_004/tests/validate_enhanced_cases.js b/task_004/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..cda12a947ae3ec3ac7add60b2b9588ebcffca794 --- /dev/null +++ b/task_004/tests/validate_enhanced_cases.js @@ -0,0 +1,72 @@ +const fs = require('fs'); +const path = require('path'); +const {pathToFileURL} = require('url'); +const {chromium} = require('playwright'); +const assert = (value, message) => { if (!value) throw Error(message); }; +const entry = path.join(process.cwd(), 'index.html'); + +(async () => { + const browser = await chromium.launch({headless: true, args: ['--no-sandbox']}); + try { + const page = await browser.newPage(); + await page.goto(pathToFileURL(entry).href); + await page.evaluate(() => { gameTest.reset(); gameTest.setRolls([1,2,3,4,6,2,6,3]); }); + const state = () => page.evaluate(() => gameTest.state()); + const roll = () => page.evaluate(() => { gameTest.roll(); return gameTest.state(); }); + let current = await state(); + assert(current.players.length === 4 && current.currentPlayer === 0, 'four-player initial turn wrong'); + assert(new Set(current.players.map(player => player.start)).size === 4, 'players need distinct starting squares'); + assert(current.players.every(player => player.pos === -1 && player.steps === 0), 'all players must begin in base'); + for (let i = 0; i < 4; i++) { + const before = await state(); + const after = await roll(); + assert(after.lastRoll === i + 1, 'reported die differs from injected roll'); + assert(after.currentPlayer === (before.currentPlayer + 1) % 4, 'non-six did not rotate turn'); + assert(after.players.every(player => player.pos === -1 && player.steps === 0), 'non-six moved a base piece or advanced its steps'); + } + current = await roll(); + assert(current.currentPlayer === 0 && current.players[0].pos === current.players[0].start && current.players[0].steps === 0, 'six must enter board without path progress and retain turn'); + current = await roll(); + assert(current.currentPlayer === 1 && current.players[0].pos === (current.players[0].start + 2) % current.trackLength && current.players[0].steps === 2, 'board movement must equal die and rotate'); + current = await roll(); + assert(current.currentPlayer === 1 && current.players[1].pos === current.players[1].start && current.players[1].steps === 0, 'second player six did not leave base'); + current = await roll(); + assert(current.currentPlayer === 2 && current.players[1].pos === (current.players[1].start + 3) % current.trackLength && current.players[1].steps === 3, 'second player movement/turn wrong'); + await page.evaluate(() => { gameTest.reset(); gameTest.setRolls([6]); }); + const rolls = page.getByRole('button', {name: /roll|dice|\bdie\b|掷骰|擲骰/i}); + const buttons = rolls.or(page.getByRole('button')).or(page.getByText(/roll|dice|\bdie\b|掷骰|擲骰/i)); + let rolledWithControl = false; + for (const button of (await buttons.all()).slice(0, 20)) { + await page.evaluate(() => { gameTest.reset(); gameTest.setRolls([6]); }); + if (!await button.isVisible() || !await button.isEnabled()) continue; + try { + await button.click({timeout: 1000}); + } catch { + continue; + } + const clicked = await state(); + if (clicked.lastRoll === 6 && clicked.players[0].pos === clicked.players[0].start + && clicked.players[0].steps === 0 && clicked.currentPlayer === 0) { + rolledWithControl = true; + break; + } + } + const hasNamedRoll = (await Promise.all((await rolls.all()).map(button => button.isVisible()))).some(Boolean); + // A drawn or icon-only control has no prescribed locator. Preserve those + // implementations and require an actual click when a roll control is found. + if (hasNamedRoll) assert(rolledWithControl, 'clicking the visible Roll control must update the real game'); + // With two consecutive sixes the die and turn indicator are unchanged, + // while a real piece must move from its start to a different square. + await page.evaluate(() => { gameTest.reset(); gameTest.setRolls([6, 6]); }); + await roll(); + const onStart = await page.screenshot({animations: 'disabled'}); + await roll(); + const sixAhead = await page.screenshot({animations: 'disabled'}); + if (6 % (await state()).trackLength !== 0) { + assert(!onStart.equals(sixAhead), 'piece moved in state but not on the visible board'); + } + console.log('four-player base, progress, dice and turn checks passed'); + } finally { + await browser.close(); + } +})().catch(error => { console.error(error); process.exit(1); }); diff --git a/task_004/tests/validate_finish.js b/task_004/tests/validate_finish.js new file mode 100644 index 0000000000000000000000000000000000000000..5bc6424c2567edcdcbcf088a419ab0ca47f7e3ca --- /dev/null +++ b/task_004/tests/validate_finish.js @@ -0,0 +1,61 @@ +const fs = require('fs'); +const path = require('path'); +const {pathToFileURL} = require('url'); +const {chromium} = require('playwright'); +const assert = (ok, message) => { if (!ok) throw Error(message); }; + +(async () => { + const browser = await chromium.launch({headless: true, args: ['--no-sandbox']}); + try { + const page = await browser.newPage({viewport: {width: 1100, height: 900}}); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href); + const state = () => page.evaluate(() => gameTest.state()); + const roll = () => page.evaluate(() => { gameTest.roll(); return gameTest.state(); }); + const rolls = values => page.evaluate(values => gameTest.setRolls(values), values); + const reset = () => page.evaluate(() => gameTest.reset()); + const output = '/logs/verifier/visual'; + fs.mkdirSync(output, {recursive: true}); + const frame = name => page.screenshot({path: path.join(output, `${name}.png`), animations: 'disabled'}); + await reset(); + const initial = await state(); + assert(Number.isInteger(initial.trackLength) && initial.trackLength >= 4, 'invalid track length'); + await frame('01-bases'); + await rolls([6, 1, 6, 2, 6, 3, 6, 4]); + for (let player = 0; player < 4; player++) { + let current = await roll(); + assert(current.currentPlayer === player && current.players[player].pos === current.players[player].start + && current.players[player].steps === 0, `player ${player}: failed base exit`); + current = await roll(); + assert(current.players[player].pos === (current.players[player].start + player + 1) % current.trackLength + && current.players[player].steps === player + 1 + && current.currentPlayer === (player + 1 >= current.trackLength ? player : (player + 1) % 4), + `player ${player}: movement or turn wrong`); + } + await frame('02-four-on-track'); + for (let player = 0; player < 4; player++) { + await reset(); + await rolls([...Array(player).fill(1), 6]); + for (let i = 0; i <= player; i++) await roll(); + const length = (await state()).trackLength; + // Six retains the turn, so every player can be tested independently. + const count = Math.ceil(length / 6); + await rolls(Array(count + 2).fill(6)); + for (let i = 1; i <= count; i++) { + const current = await roll(); + const token = current.players[player]; + assert(token.steps === i * 6 && token.pos === (token.start + i * 6) % length, + `player ${player}: wraparound movement is incorrect`); + } + const finished = await state(); + await roll(); await roll(); + assert(JSON.stringify(await state()) === JSON.stringify(finished), 'roll changed state after victory'); + if (player === 0) await frame('03-winner'); + await reset(); + const cleared = await state(); + assert(cleared.currentPlayer === 0 && cleared.lastRoll === null + && cleared.players.every(token => token.pos === -1 && token.steps === 0), 'reset did not clear finished game'); + } + await frame('04-reset'); + console.log('All four players: base exit, movement, wraparound, finish and reset passed'); + } finally { await browser.close(); } +})().catch(error => { console.error(error); process.exit(1); }); diff --git a/task_004/tests/validate_semantics.js b/task_004/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..d10cc042756f6e9dba39b8f2484d59aaea267cc8 --- /dev/null +++ b/task_004/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_005/acceptance_checklist.json b/task_005/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..5f9296e443dcf523119c255f13d5b31c5d21b643 --- /dev/null +++ b/task_005/acceptance_checklist.json @@ -0,0 +1,16 @@ +{ + "task_id": 6, + "category": "frontend_development", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies." + ], + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "risk_notes": [], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_005/environment/Dockerfile b/task_005/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_005/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_005/environment/code/.gitkeep b/task_005/environment/code/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/task_005/environment/docker-compose.yaml b/task_005/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_005/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_005/instruction.md b/task_005/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..10c91393134dfeee91ed63f85bbc956bd231860e --- /dev/null +++ b/task_005/instruction.md @@ -0,0 +1,22 @@ +# Dark-themed Tetris + +Build a playable, dark-themed Tetris game. Deliver a root `index.html` that opens directly in a browser and works offline. Render the falling piece and locked blocks on a board of at least 8 columns and 12 rows, and display the score and cleared-line count. + +## Gameplay + +Use Left and Right to move, Up to rotate, and Down to drop one row. Respect walls and existing blocks. When a piece cannot drop farther, lock it, clear completed rows, shift the remaining rows down, increase the score and line count for cleared rows, and spawn the next piece. If the new piece cannot spawn, end the game and freeze play until reset. + +## State and time interface + +Expose `window.gameTest` with `reset()`, `setBoard(rows)`, `setPiece(piece)`, `move(dx)`, `rotate()`, `drop()`, `step(milliseconds)`, and `state()`. Drive the same state and rendering as the keyboard controls, with changes visible on the page. + +- Return `{rows, cols, board, piece:{shape, x, y, color}, score, lines, gameOver}`. `setBoard` takes a two-dimensional array of the reported dimensions. Cells with `0` or `null` are empty; `1` is occupied and renders visibly. Occupied cells may also be stored as color strings. `setPiece` installs the supplied shape and coordinates, with a default color if omitted. +- `drop()` follows the same single-row or lock-and-spawn behavior as Down. `step(milliseconds)` drops once per accumulated 500 ms, preserving leftover time. Zero or less than 500 ms of accumulated time does not drop a piece. +- `reset()`, `setBoard()` and `setPiece()` clear leftover time. After any of these calls, the deterministic scenario advances only through explicit actions, not the page's live clock. Reset restores an empty playable board, zero score and zero cleared lines. + +## Acceptance Checklist + +- The offline entry renders without browser errors. Movement, rotation and drops affect the real board and respect collisions. Movement and injected occupied cells are visible. +- A full row disappears, the board gains an empty top row, and both line count and score increase. +- Sub-interval time accumulates across calls, and a large step can drop several rows. Board and piece injection and reset clear leftover time; the live clock does not advance an injected state. +- A blocked spawn sets `gameOver`; subsequent move, rotate, drop and step calls leave state unchanged until reset restores play. diff --git a/task_005/quality_notes.md b/task_005/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..125a20b7b283c909235a49e7cd080f13240f2b2a --- /dev/null +++ b/task_005/quality_notes.md @@ -0,0 +1,2 @@ +# Quality Notes + diff --git a/task_005/solution/README.md b/task_005/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_005/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_005/solution/code/index.html b/task_005/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..b73b68405c808f472bf6a7d63ab81d3449d50dba --- /dev/null +++ b/task_005/solution/code/index.html @@ -0,0 +1,188 @@ + + + + + +Dark Tetris + + + +

Dark Tetris

+
Score: 0 · Lines: 0
+ +

← → Move, ↑ Rotate, ↓ Soft drop (dark theme)

+ + + + + diff --git a/task_005/solution/solve.sh b/task_005/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_005/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_005/task.toml b/task_005/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_005/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_005/task_meta.json b/task_005/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..670f10b5d64446115aef829789dd5063137bffd4 --- /dev/null +++ b/task_005/task_meta.json @@ -0,0 +1,18 @@ +{ + "task_id": 6, + "task_category": "frontend_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 1, + "language": "javascript", + "tool_files_from_selected_trace": [ + "tetris.html" + ], + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "source_row_id": 36, + "repair_revision": "2026-09-29", + "instruction_sha256": "d762ac2d9be1650f00d37d33e0bf6e37f28caafe55c54b17a15a1d97ea8603dc" +} diff --git a/task_005/tests/_shared/contract_checker.js b/task_005/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_005/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_005/tests/_shared/static_enhancer.sh b/task_005/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_005/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_005/tests/enhancement_cases.json b/task_005/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..f6bf286a6eab742439589c1b8a0c8fb5eb4abfb1 --- /dev/null +++ b/task_005/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","instruction_evidence":"在网页上做个暗黑炫酷版俄罗斯方块","validator":"validate_enhanced_cases.js","behavior":"实际渲染深色可玩棋盘并显示分数"}, + {"case_id":"ENHANCED_CASE_2","instruction_evidence":"包含或实现需求信号: `rotate|旋转`","validator":"validate_enhanced_cases.js","behavior":"固定非对称方块后按上键产生可见旋转"}, + {"case_id":"ENHANCED_CASE_3","instruction_evidence":"在网页上做个暗黑炫酷版俄罗斯方块","validator":"validate_enhanced_cases.js","behavior":"方向移动与加速下落真实改变当前方块位置"} +] diff --git a/task_005/tests/test.sh b/task_005/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5b93094e3a03087c4e33dbad0e01077a559a54e5 --- /dev/null +++ b/task_005/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_005/tests/validate_aaav_dynamic.js b/task_005/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..06c7b15521c29459923aecc4e3d134be308479fa --- /dev/null +++ b/task_005/tests/validate_aaav_dynamic.js @@ -0,0 +1,148 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 6; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_005/tests/validate_browser_smoke.js b/task_005/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..658969881ac5de913eb45fddd8f4e1aae56c7ff5 --- /dev/null +++ b/task_005/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_005/tests/validate_enhanced_cases.js b/task_005/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..ab26871a0a2d8aaa3f142a2f8c8757952c5cbf75 --- /dev/null +++ b/task_005/tests/validate_enhanced_cases.js @@ -0,0 +1,119 @@ +const fs = require('fs'); +const path = require('path'); +const {pathToFileURL} = require('url'); +const {chromium} = require('playwright'); +const ok = (condition, message) => { if (!condition) throw Error(message); }; +const entry = () => path.join(process.cwd(), 'index.html'); + +(async () => { + const browser = await chromium.launch({headless: true, args: ['--no-sandbox']}); + try { + const page = await browser.newPage(); + await page.clock.install(); + await page.goto(pathToFileURL(entry()).href); + await page.clock.pauseAt(new Date(Date.now() + 60000)); + const dims = await page.evaluate(() => { gameTest.reset(); const s = gameTest.state(); return {rows:s.rows,cols:s.cols}; }); + ok(Number.isInteger(dims.rows) && dims.rows >= 12 && Number.isInteger(dims.cols) && dims.cols >= 8, + 'board must have at least twelve rows and eight columns'); + const x = Math.floor(dims.cols / 2); + const board = Array.from({length:dims.rows}, (_,r) => Array.from({length:dims.cols}, (_,c) => r === dims.rows-1 && c !== x ? 1 : 0)); + await page.evaluate(({board,x,rows}) => { gameTest.setBoard(board); gameTest.setPiece({shape:[[1]],x,y:rows-2}); gameTest.drop(); gameTest.drop(); }, {board,x,rows:dims.rows}); + let state = await page.evaluate(() => gameTest.state()); + ok(state.lines === 1 && state.score > 0, 'completed line must clear and score'); + ok(state.board[0].every(v => !v), 'cleared board must gain an empty top row'); + // The public contract does not prescribe HUD wording or a text-only HUD. + // Counters above are checked semantically; rendered labels are reviewed + // in visual evidence rather than matched to an English singular noun. + + await page.evaluate(() => gameTest.setPiece({shape:[[1,0],[1,1]],x:2,y:2})); + const before = JSON.stringify((await page.evaluate(() => gameTest.state())).piece.shape); + await page.keyboard.press('ArrowUp'); + state = await page.evaluate(() => gameTest.state()); + ok(JSON.stringify(state.piece.shape) !== before, 'up key must rotate the visible game piece'); + const y = state.piece.y; + await page.evaluate(() => { gameTest.step(0); gameTest.step(499); }); + ok((await page.evaluate(() => gameTest.state())).piece.y === y, 'step(0) and sub-frame time must not drop'); + await page.evaluate(() => gameTest.step(1)); + ok((await page.evaluate(() => gameTest.state())).piece.y === y+1, 'accumulated 500ms must drop once'); + await page.evaluate(() => gameTest.step(1000)); + ok((await page.evaluate(() => gameTest.state())).piece.y === y+3, 'large step must drop the right number of rows'); + + for (const operation of ['reset', 'setBoard', 'setPiece']) { + const timed = await page.evaluate((operation) => { + const supplied = {shape: [[1]], x: 0, y: 0}; + gameTest.reset(); + gameTest.setPiece(supplied); + gameTest.step(499); + if (operation === 'reset') gameTest.reset(); + if (operation === 'setBoard') gameTest.setBoard(gameTest.state().board); + if (operation === 'setPiece') gameTest.setPiece(supplied); + const before = gameTest.state().piece.y; + gameTest.step(1); + return [before, gameTest.state().piece.y]; + }, operation); + ok(timed[0] === timed[1], `${operation} must clear time remainder`); + } + await page.evaluate(() => { gameTest.reset(); gameTest.setPiece({shape:[[1]],x:0,y:0}); }); + state = await page.evaluate(() => gameTest.state()); + await page.keyboard.press('ArrowLeft'); + ok((await page.evaluate(() => gameTest.state())).piece.x === 0, 'left wall must stop keyboard movement'); + const visual = '/logs/verifier/visual'; + fs.mkdirSync(visual, {recursive: true}); + const beforeMove = await page.screenshot({path: path.join(visual, '01-left.png'), animations: 'disabled'}); + await page.keyboard.press('ArrowRight'); + ok((await page.evaluate(() => gameTest.state())).piece.x === 1, 'right key must move actual piece'); + const afterMove = await page.screenshot({path: path.join(visual, '02-right.png'), animations: 'disabled'}); + ok(!beforeMove.equals(afterMove), 'piece moved in state but not in rendered output'); + await page.keyboard.press('ArrowDown'); + ok((await page.evaluate(() => gameTest.state())).piece.y === 1, 'down key must drop actual piece'); + await page.screenshot({path: path.join(visual, '03-down.png'), animations: 'disabled'}); + await page.clock.runFor(650); + ok((await page.evaluate(() => gameTest.state())).piece.y === 1, 'deterministic injection must ignore wall-clock rAF'); + const beforeBoardInjection = await page.screenshot({animations: 'disabled'}); + await page.evaluate(() => { + const state = gameTest.state(); + const board = state.board.map(row => [...row]); + board[state.rows - 1] = board[state.rows - 1].map((cell, column) => column % 2 ? 0 : 1); + gameTest.setBoard(board); + }); + const afterBoardInjection = await page.screenshot({path: path.join(visual, '04-occupied-row.png'), animations: 'disabled'}); + ok(!beforeBoardInjection.equals(afterBoardInjection), 'occupied numeric cells affect state but are not visibly rendered'); + const blocked = await page.evaluate(() => { + for (const phase of [0, 1]) { + gameTest.reset(); + const {rows, cols} = gameTest.state(); + // Incomplete, tightly packed rows with alternating edge holes prevent + // entry without prescribing a particular spawn anchor or shape. + const packed = Array.from({length: rows}, (_, row) => Array.from({length: cols}, (_, col) => + row < rows - 2 && col !== ((row + phase) % 2 ? cols - 1 : 0) ? 1 : 0)); + gameTest.setBoard(packed); + gameTest.setPiece({shape: [[1]], x: 0, y: rows - 1}); + for (let i = 0; i <= rows; i++) { + gameTest.drop(); + const next = gameTest.state(); + if (next.gameOver) return {stopped: true}; + const {piece, board} = next; + const overlaps = piece.shape.some((row, dy) => + row.some((cell, dx) => cell && board[piece.y + dy]?.[piece.x + dx])); + if (overlaps) return {stopped: false, overlap: true}; + } + } + return {stopped: false, overlap: false}; + }); + ok(blocked.stopped, blocked.overlap + ? 'a new piece overlapping a locked block must stop play' + : 'a packed board that prevents new pieces from entering must stop play'); + state = await page.evaluate(() => gameTest.state()); + ok(state.gameOver === true, 'blocked spawn must end the game'); + const stopped = JSON.stringify(state); + await page.evaluate(() => { gameTest.move(1); gameTest.rotate(); gameTest.drop(); gameTest.step(1500); }); + ok(JSON.stringify(await page.evaluate(() => gameTest.state())) === stopped, 'game-over state must freeze until reset'); + await page.screenshot({path: path.join(visual, '04-game-over.png'), animations: 'disabled'}); + await page.evaluate(() => gameTest.reset()); + state = await page.evaluate(() => gameTest.state()); + ok(!state.gameOver && state.score === 0 && state.lines === 0 && state.board.every(row => row.every(cell => !cell)), + 'reset must restore a playable empty board'); + await page.screenshot({path: path.join(visual, '05-restarted.png'), animations: 'disabled'}); + console.log('enhanced tetris cases passed'); + } finally { await browser.close(); } +})().catch(error => { console.error(error); process.exit(1); }); diff --git a/task_005/tests/validate_semantics.js b/task_005/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..d10cc042756f6e9dba39b8f2484d59aaea267cc8 --- /dev/null +++ b/task_005/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_006/acceptance_checklist.json b/task_006/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..9a8d7f2de3a5a8aed32555c6e6ac343423e567e2 --- /dev/null +++ b/task_006/acceptance_checklist.json @@ -0,0 +1,18 @@ +{ + "task_id": 7, + "category": "frontend_development", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies." + ], + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_006/environment/Dockerfile b/task_006/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f6bd951d374ffafa80042621453486a5bb18d9f8 --- /dev/null +++ b/task_006/environment/Dockerfile @@ -0,0 +1,9 @@ +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_006/environment/code/.gitkeep b/task_006/environment/code/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/task_006/environment/docker-compose.yaml b/task_006/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_006/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_006/instruction.md b/task_006/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..46601545aba3d24d9721cbf893bd8f7fd1a63f71 --- /dev/null +++ b/task_006/instruction.md @@ -0,0 +1,16 @@ +# Mobile expense ledger + +Build a local expense tracker in HTML and JavaScript. Use a clean, green-led interface with total expenses and balance at the top and an add action at the bottom. No login or backend is needed. Deliver an offline root `index.html`. + +## Requirements + +Use an inline form or a dialog with a numeric amount field (`input[type=number]`) and a text description field. Use an accessible add action such as “Add expense” or “添加支出”; for submission use an Add label or a Chinese label such as “保存” or “确定”. Show each summary label immediately before its amount in reading order: “Total expenses” or “Expense total” (总支出、累计支出、总花费), and “Balance” (余额、结余). Display each saved description. + +Start with zero total expenses and an initial balance of your choice. Save only positive expense amounts, accepting up to two decimal places. Update expenses and balance accurately to the cent. Save valid expenses even when they make the balance negative. Store records locally so they and their summaries survive a reload. Income entry is optional; if implemented, show income amounts in green. + +## Acceptance Checklist + +- The offline page renders and the add form is usable at a 375 px viewport without horizontal overflow. +- Multiple expense entries appear individually and update the total and remaining balance. Decimals and a negative balance are displayed accurately. +- A reload preserves saved records and summary amounts, including a negative balance. +- Zero or negative expenses do not create records or change persisted totals. diff --git a/task_006/quality_notes.md b/task_006/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..160c1210219d27d8536b80599a676d09b212afe9 --- /dev/null +++ b/task_006/quality_notes.md @@ -0,0 +1,3 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. \ No newline at end of file diff --git a/task_006/solution/README.md b/task_006/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_006/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_006/solution/code/index.html b/task_006/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..980429efb480fc0255fb1ebe557fbf8276b53d5a --- /dev/null +++ b/task_006/solution/code/index.html @@ -0,0 +1,115 @@ + + + + + +Simple Expense Tracker + + + +
+

Simple Expense Tracker

+
+
Total Expense¥0.00
+
Balance¥0.00
+
+
+
+
    +
    +
    + + + +
    + + + + diff --git a/task_006/solution/solve.sh b/task_006/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_006/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_006/task.toml b/task_006/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_006/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_006/task_meta.json b/task_006/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..1df868b0e921b3763b99d526d6721863c9235f0e --- /dev/null +++ b/task_006/task_meta.json @@ -0,0 +1,20 @@ +{ + "task_id": 7, + "task_category": "frontend_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 4, + "language": "javascript", + "tool_files_from_selected_trace": [ + "index.html", + "script.js", + "style.css" + ], + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "source_row_id": 42, + "repair_revision": "2026-09-29", + "instruction_sha256": "0c86084c93b09c97e4d2b384eafec176cb829f32560d55abf2fecb878b318c17" +} diff --git a/task_006/tests/_shared/contract_checker.js b/task_006/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_006/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_006/tests/_shared/static_enhancer.sh b/task_006/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_006/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_006/tests/enhancement_cases.json b/task_006/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..1d9d12bd52d1b7467b921a4626e6ad80682a9fc2 --- /dev/null +++ b/task_006/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","instruction_evidence":"底部有添加按钮。不用登录功能,数据存在本地就行。手机上能正常显示。","validator":"validate_enhanced_cases.js","behavior":"360px视口渲染支出、结余和添加控件,并可完成一次新增"}, + {"case_id":"ENHANCED_CASE_2","instruction_evidence":"顶部显示总支出和结余。底部有添加按钮。","validator":"validate_enhanced_cases.js","behavior":"新增整数金额后总支出增加同额且结余减少同额"}, + {"case_id":"ENHANCED_CASE_3","instruction_evidence":"不用登录功能,数据存在本地就行。","validator":"validate_enhanced_cases.js","behavior":"新增记录写入本地存储并在完整刷新后保留"} +] diff --git a/task_006/tests/summary_values.js b/task_006/tests/summary_values.js new file mode 100644 index 0000000000000000000000000000000000000000..7184cc31c0b427a87328cc2cf57e1acb40c44862 --- /dev/null +++ b/task_006/tests/summary_values.js @@ -0,0 +1,31 @@ +// Read displayed monetary values without losing minus signs or binding layout. +function readAmount(text, labels) { + const label = new RegExp(labels, 'i').exec(text); + if (!label) throw Error(`summary label missing: ${labels}`); + const following = text.slice(label.index + label[0].length); + const marker = following.replace(/^\s*[::]?\s*/, ''); + const number = String.raw`\d+(?:[.,]\d+|[\u00a0\u202f ]\d{3})*`; + // Currency codes, symbols and combined forms such as CN¥ are formatting. + const currency = String.raw`(?:[A-Z]{2,3}\s*\p{Sc}|\p{Sc}|[A-Z]{3})`; + const amount = new RegExp(String.raw`^([-−]?)\s*(?:${currency}\s*)?([-−]?)\s*(${number})(?:\s*${currency})?`, 'u'); + const wrapped = /^[((]([^))]+)[))]/.exec(marker); + const match = amount.exec(wrapped ? wrapped[1].trim() : marker); + if (!match) throw Error(`summary value missing: ${labels}`); + const [, leadingSign, embeddedSign, digits] = match; + const negative = Boolean(wrapped || leadingSign || embeddedSign); + const compact = digits.replace(/\s/g, ''); + const decimalMark = /[.,]\d{1,2}$/.exec(compact); + const value = decimalMark + ? Number(compact.slice(0, decimalMark.index).replace(/[,.]/g, '') + '.' + decimalMark[0].slice(1)) + : Number(/^[+-]?\d{1,3}(?:[.,]\d{3})+$/.test(compact) ? compact.replace(/[.,]/g, '') : compact); + return (negative ? -1 : 1) * value; +} + +function readSummary(text) { + return { + expense: readAmount(text, '总支出|累计支出|总花费|Total expenses?|Expense total'), + balance: readAmount(text, '结余|余额|Balance'), + }; +} + +module.exports = {readAmount, readSummary}; diff --git a/task_006/tests/test.sh b/task_006/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5b93094e3a03087c4e33dbad0e01077a559a54e5 --- /dev/null +++ b/task_006/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_006/tests/validate_aaav_dynamic.js b/task_006/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..662a8dc0873cafb925c18131963a24c603ac9d17 --- /dev/null +++ b/task_006/tests/validate_aaav_dynamic.js @@ -0,0 +1,183 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 7; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + // Expense-tracker behavior: adding a record must append a list row AND + // update the total/balance summary text. Gated on the oracle's ids so it + // is a no-op for pages that do not expose this form. + const descInput = page.locator('#desc'); + const amountInput = page.locator('#amount'); + const addBtn = page.locator('#addBtn, #addForm button[type="submit"]'); + const list = page.locator('#list'); + if (await descInput.count() && await amountInput.count() && await addBtn.count() && await list.count()) { + const rowsBefore = await page.locator('#list li').count(); + const summaryBefore = await page.evaluate(() => { + const t = document.querySelector('#totalExpense'); + const b = document.querySelector('#balance'); + return { total: t ? t.innerText.trim() : null, balance: b ? b.innerText.trim() : null }; + }); + await descInput.fill('AAAV lunch'); + await amountInput.fill('12.50'); + await addBtn.first().click(); + await page.waitForTimeout(200); + const rowsAfter = await page.locator('#list li').count(); + assert(rowsAfter > rowsBefore, 'adding an expense should append a new list row'); + const summaryAfter = await page.evaluate(() => { + const t = document.querySelector('#totalExpense'); + const b = document.querySelector('#balance'); + return { total: t ? t.innerText.trim() : null, balance: b ? b.innerText.trim() : null }; + }); + if (summaryBefore.total != null) { + assert(summaryAfter.total !== summaryBefore.total, 'total expense text should update after adding an expense'); + } + if (summaryBefore.balance != null) { + assert(summaryAfter.balance !== summaryBefore.balance, 'balance text should update after adding an expense'); + } + // clean up persisted state so the generic interaction pass starts fresh + await page.evaluate(() => { try { localStorage.clear(); } catch {} }); + } + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_006/tests/validate_browser_smoke.js b/task_006/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..658969881ac5de913eb45fddd8f4e1aae56c7ff5 --- /dev/null +++ b/task_006/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_006/tests/validate_enhanced_cases.js b/task_006/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..efc978b1d621c2311716ba76c8184921d445d7e6 --- /dev/null +++ b/task_006/tests/validate_enhanced_cases.js @@ -0,0 +1,104 @@ +const fs = require('fs'); +const path = require('path'); +const {pathToFileURL} = require('url'); +const {chromium} = require('playwright'); +const {readSummary} = require('./summary_values'); +const ok = (condition, message) => { if (!condition) throw Error(message); }; +const entry = () => path.join(process.cwd(), 'index.html'); + +async function form(page) { + let amount = page.locator('input[type=number]:visible').first(); + if (!await amount.count()) { + const add = page.getByRole('button', {name:/add|添加|新增|记一笔/i}).first(); + ok(await add.count(), 'add action missing'); + await add.click(); + amount = page.locator('input[type=number]:visible').first(); + } + const desc = page.locator('textarea:visible,input:not([type=number]):not([type=hidden]):visible').first(); + const submit = page.getByRole('button', {name:/add|添加|新增|保存|确定/i}).last(); + ok(await amount.count() && await desc.count() && await submit.count(), 'usable add form missing'); + return {amount,desc,submit}; +} + +async function summary(page) { + const text = await page.locator('body').innerText(); + return readSummary(text); +} + +(async () => { + const browser = await chromium.launch({headless:true,args:['--no-sandbox']}); + try { + const page = await browser.newPage({viewport:{width:375,height:740}}); + await page.goto(pathToFileURL(entry()).href); + await page.evaluate(() => localStorage.clear()); + await page.reload(); + ok(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth), 'mobile page must not overflow horizontally'); + const initial = await summary(page); + ok(initial.expense === 0, 'new ledger total expense must start at zero'); + + let controls = await form(page); + await controls.desc.fill('午餐'); + await controls.amount.fill('37'); + await controls.submit.click(); + ok((await page.locator('body').innerText()).includes('午餐'), 'first saved record must be visible'); + let current = await summary(page); + ok(current.expense === 37 && current.balance === initial.balance-37, 'first expense must update both summaries'); + + controls = await form(page); + await controls.desc.fill('车票'); + await controls.amount.fill('13'); + await controls.submit.click(); + current = await summary(page); + ok(current.expense === 50 && current.balance === initial.balance-50, 'multiple expenses must aggregate'); + await page.reload(); + const body = await page.locator('body').innerText(); + ok(body.includes('午餐') && body.includes('车票'), 'both records must persist after reload'); + current = await summary(page); + ok(current.expense === 50 && current.balance === initial.balance-50, 'summaries must persist after reload'); + + controls = await form(page); + await controls.desc.fill('零元'); + await controls.amount.fill('0'); + await controls.submit.click(); + current = await summary(page); + ok(current.expense === 50, 'zero-value expense must not change the ledger'); + await page.reload(); + ok(!(await page.locator('body').innerText()).includes('零元'), + 'zero-value expense must not be stored as a record'); + current = await summary(page); + ok(current.expense === 50 && current.balance === initial.balance-50, + 'invalid expense must not alter persisted summaries'); + let total = 50; + const additions = [['小额甲', 0.1], ['小额乙', 0.2], ['大额支出', Math.abs(initial.balance) + 100.37]]; + for (const [description, amount] of additions) { + controls = await form(page); + await controls.desc.fill(description); + await controls.amount.fill(amount.toFixed(2)); + await controls.submit.click(); + total += amount; + current = await summary(page); + ok(Math.abs(current.expense - total) < 0.005 + && Math.abs(current.balance - (initial.balance - total)) < 0.005, + 'decimal expense and negative balance must be calculated correctly'); + } + await page.reload(); + current = await summary(page); + ok(current.balance < 0 && Math.abs(current.expense - total) < 0.005, 'negative balance did not persist'); + controls = await form(page); + await controls.desc.fill('非法负金额'); + await controls.amount.fill('-5'); + await controls.submit.click(); + current = await summary(page); + ok(Math.abs(current.expense - total) < 0.005 && Math.abs(current.balance - (initial.balance - total)) < 0.005, + 'negative expense altered a summary'); + await page.reload(); + ok(!(await page.locator('body').innerText()).includes('非法负金额'), 'negative expense was stored'); + current = await summary(page); + ok(Math.abs(current.expense - total) < 0.005 && Math.abs(current.balance - (initial.balance - total)) < 0.005, + 'negative expense altered a persisted summary'); + const output = '/logs/verifier/visual'; + fs.mkdirSync(output, {recursive: true}); + await page.screenshot({path: path.join(output, 'mobile-ledger.png'), fullPage: true}); + console.log('enhanced expense ledger cases passed'); + } finally { await browser.close(); } +})().catch(error => { console.error(error); process.exit(1); }); diff --git a/task_006/tests/validate_semantics.js b/task_006/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..d10cc042756f6e9dba39b8f2484d59aaea267cc8 --- /dev/null +++ b/task_006/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_007/acceptance_checklist.json b/task_007/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..78c3c76ce9fd905e938292898f44b35a8d0639c7 --- /dev/null +++ b/task_007/acceptance_checklist.json @@ -0,0 +1,21 @@ +{ + "task_id": 8, + "category": "application_development", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Implements the requested domain workflow end to end.", + "Includes maintainable separation of concerns and meaningful tests when the task asks for them." + ], + "input_assets": [ + "index.html" + ], + "expected_outputs": [], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns.", + "A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_007/environment/Dockerfile b/task_007/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_007/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_007/environment/code/index.html b/task_007/environment/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..b5a16b6ef0f2a513b652c858f2a36ae30404b458 --- /dev/null +++ b/task_007/environment/code/index.html @@ -0,0 +1,22 @@ + + + + +Question System Admin + + +
    +

    刷题系统管理后台

    + + + +

    题库管理

    +

    用户管理

    +

    权限管理

    +
    + + diff --git a/task_007/environment/docker-compose.yaml b/task_007/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_007/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_007/instruction.md b/task_007/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9b52c66d349c7092e4b36ddc80c3f4bf222c8d08 --- /dev/null +++ b/task_007/instruction.md @@ -0,0 +1,25 @@ +# Practice-question administration dashboard + +Extend the supplied `index.html` into a local practice-question dashboard with question, user and permission management. Deliver the root `index.html` for direct, offline browser use. Keep state in memory; do not add login or a backend. + +## Question and role management + +An administrator can add a question from text, edit it, toggle it between published and unpublished, and delete it. Each action affects only its selected question, and status changes are visible. A regular user can browse but cannot change the question bank. Hide, remove or disable management controls in that role; if a control remains in the DOM, programmatic clicks must not allow mutations. Returning to the admin role restores management. + +Edit through the main input, an accessible dialog with a text field and a Save button (保存、确认 or 确定 in Chinese), or a native prompt. Give Edit and Delete buttons recognizable accessible names. Use a native ` + + + +

    Questions: 0

    + + + +
    +

    User Management

    +
    +
    + + +
    +

    Permission Management

    +
    + + + role = admin +
    +

    Admins can manage questions; normal users can only browse, so management controls are hidden.

    +
    + + + + + diff --git a/task_007/solution/solve.sh b/task_007/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_007/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_007/task.toml b/task_007/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_007/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_007/task_meta.json b/task_007/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..a22c48ca5b749f83c1156d94fbaa17ce7075e684 --- /dev/null +++ b/task_007/task_meta.json @@ -0,0 +1,51 @@ +{ + "task_id": 8, + "task_category": "application_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 3, + "language": "javascript", + "tool_files_from_selected_trace": [ + ".env.example", + ".gitignore", + "App.css", + "App.tsx", + "CreateQuestion.tsx", + "Dashboard.tsx", + "Layout.tsx", + "Login.tsx", + "PROJECT_SUMMARY.md", + "Profile.tsx", + "Question.js", + "QuestionList.tsx", + "README.md", + "Submission.js", + "SubmissionList.tsx", + "User.js", + "UserList.tsx", + "api.ts", + "auth.js", + "index.css", + "index.html", + "index.js", + "index.ts", + "initData.js", + "main.tsx", + "package.json", + "questions.js", + "start.sh", + "status-check.sh", + "submissions.js", + "tsconfig.json", + "useAuth.ts", + "users.js", + "vite.config.ts" + ], + "input_assets": [ + "index.html" + ], + "expected_outputs": [], + "source_row_id": 48, + "repair_revision": "2026-09-29", + "instruction_sha256": "27111d9b15723327b00e56f2d174eb897e1fba60a5c66902baa14fe1aa4ae859" +} diff --git a/task_007/tests/_shared/contract_checker.js b/task_007/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_007/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_007/tests/_shared/static_enhancer.sh b/task_007/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_007/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_007/tests/edit_question.js b/task_007/tests/edit_question.js new file mode 100644 index 0000000000000000000000000000000000000000..4606ac2f6058672ff03305ff0783d457c011d51a --- /dev/null +++ b/task_007/tests/edit_question.js @@ -0,0 +1,15 @@ +// Accept inline, accessible HTML-dialog and native prompt editing flows. +async function editQuestion(page, button, text) { + const promptHandler = dialog => dialog.type() === 'prompt' ? dialog.accept(text) : dialog.dismiss(); + page.on('dialog', promptHandler); + try { + await button.click(); + const dialog = page.getByRole('dialog'); + if (await dialog.count() && await dialog.first().isVisible()) { + const field = dialog.first().locator('input,textarea').first(); + if (await field.count()) await field.fill(text); + await dialog.first().getByRole('button', {name: /save|保存|确认|确定/i}).first().click(); + } + } finally { page.off('dialog', promptHandler); } +} +module.exports = {editQuestion}; diff --git a/task_007/tests/enhancement_cases.json b/task_007/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..79d500491c9145971f07b290427f95a2a09bc653 --- /dev/null +++ b/task_007/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","instruction_evidence":"上传问题会加入问题列表","validator":"validate_enhanced_cases.js","behavior":"连续上传两个不同题目后列表逐项增加并保留两项文本"}, + {"case_id":"ENHANCED_CASE_2","instruction_evidence":"题库管理:可以上传、编辑、下架、删除题目","validator":"validate_enhanced_cases.js","behavior":"兼容直接、弹窗或行内编辑流程,编辑目标且保留另一题"}, + {"case_id":"ENHANCED_CASE_3","instruction_evidence":"删除是 admin-only 控件,切换到 normal user 后应隐藏并禁止删除,切回 admin 后恢复","validator":"validate_enhanced_cases.js","behavior":"普通用户看不到删除,切回管理员后可删除且数量减一"} +] diff --git a/task_007/tests/test.sh b/task_007/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ab2150eb79f6f15b53d20b21738b84bbe0d8003 --- /dev/null +++ b/task_007/tests/test.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_ui_behavior.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_007/tests/validate_aaav_dynamic.js b/task_007/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..6df87420ec8e28c226ba8d6070d033b562bce36d --- /dev/null +++ b/task_007/tests/validate_aaav_dynamic.js @@ -0,0 +1,184 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 8; +const KIND = "browser"; +const TESTIDS = [ + "question-input", + "upload-question", + "question-item", + "edit-question", + "offline-question", + "delete-question", + "role-select", + "answer-record", + "admin-dashboard", + "question-bank", + "user-management", + "permission-management" +]; +// Only `question-input`, `upload-question`, `question-item` are disclosed in the +// instruction (with "等"). For the remaining hooks the instruction does not pin an +// exact testid, so accept reasonable aliases instead of forcing the reference's +// literal testid. The reference still uses the canonical testid, so it keeps passing. +const TESTID_SELECTORS = { + "question-input": '[data-testid="question-input"]', + "upload-question": '[data-testid="upload-question"]', + "question-item": '[data-testid="question-item"]', + "edit-question": '[data-testid="edit-question"], [data-testid="edit-btn"], .edit-question', + "offline-question": '[data-testid="offline-question"], [data-testid="toggle-question"], [data-testid="toggle-status"], .offline-question', + "delete-question": '[data-testid="delete-question"], [data-testid="remove-question"], .delete-question', + "role-select": '[data-testid="role-select"], [data-testid="role-selector"], select[name="role"]', + "answer-record": '[data-testid="answer-record"], [data-answer-record], [data-testid="record-answer"]', + "admin-dashboard": '[data-testid="admin-dashboard"], [data-testid="dashboard"]', + "question-bank": '[data-testid="question-bank"], [data-testid="question-management"]', + "user-management": '[data-testid="user-management"], [data-testid="user-admin"]', + "permission-management": '[data-testid="permission-management"], [data-testid="role-management"]' +}; +function selectorFor(id) { return TESTID_SELECTORS[id] || `[data-testid="${id}"]`; } +const HAS_QUESTION_WORKFLOW = true; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + const offlineSel = selectorFor('offline-question'); + const editSel = selectorFor('edit-question'); + const roleSel = selectorFor('role-select'); + const deleteSel = selectorFor('delete-question'); + if (await first.locator(offlineSel).count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator(offlineSel).click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator(editSel).count()) { + await first.locator(editSel).click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator(roleSel).count()) { + await page.locator(roleSel).selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator(deleteSel).first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator(roleSel).selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator(deleteSel).first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(selectorFor(id)).count(); + assert(count > 0, `missing required hook: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_007/tests/validate_browser_smoke.js b/task_007/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_007/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_007/tests/validate_enhanced_cases.js b/task_007/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..d7009a7f52b663e1288614bde1e604e28807f9f6 --- /dev/null +++ b/task_007/tests/validate_enhanced_cases.js @@ -0,0 +1,69 @@ +const fs = require('fs'); +const path = require('path'); +const {pathToFileURL} = require('url'); +const {chromium} = require('playwright'); +const {editQuestion} = require('./edit_question'); +const assert = (value, message) => { if (!value) throw Error(message); }; + +(async () => { + const browser = await chromium.launch({headless: true, args: ['--no-sandbox']}); + try { + const page = await browser.newPage({viewport: {width: 1200, height: 900}}); + await page.route(/^https?:/, route => route.abort()); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href); + const items = page.getByTestId('question-item'); + const input = page.getByTestId('question-input'); + async function upload(text) { + const before = await items.count(); + await input.fill(text); + await page.getByTestId('upload-question').click(); + assert(await items.count() === before + 1 && (await items.last().innerText()).includes(text), + 'upload must append the supplied question text'); + } + await upload('保留题甲'); + await upload('待编辑题乙'); + await input.fill('已编辑题乙'); + await editQuestion(page, items.last().getByRole('button', {name: /edit|编辑|修改/i}).first(), '已编辑题乙'); + assert((await items.nth((await items.count()) - 2).innerText()).includes('保留题甲') + && (await items.last().innerText()).includes('已编辑题乙'), 'editing must update only the selected record'); + + const role = page.getByRole('combobox').first(); + const options = await role.locator('option').evaluateAll(elements => elements.map(e => ({value: e.value, text: e.textContent}))); + const normal = options.find(x => /normal user|普通用户/i.test(x.text + ' ' + x.value)); + const admin = options.find(x => /admin|管理员/i.test(x.text + ' ' + x.value)); + assert(normal && admin, 'roles must distinguish normal user and administrator'); + const output = '/logs/verifier/visual'; + fs.mkdirSync(output, {recursive: true}); + await page.screenshot({path: path.join(output, '01-admin.png'), fullPage: true}); + await role.selectOption(normal.value); + const deleteControl = items.last().getByRole('button', {name: /delete|remove|删除/i}); + if (await deleteControl.count()) { + assert(!await deleteControl.isVisible() || !await deleteControl.isEnabled(), 'normal user has enabled delete control'); + } + await page.screenshot({path: path.join(output, '02-normal.png'), fullPage: true}); + await role.selectOption(admin.value); + const before = await items.count(); + await items.last().getByRole('button', {name: /delete|remove|删除/i}).click(); + assert(await items.count() === before - 1, 'admin deletion did not remove exactly one record'); + assert((await items.last().innerText()).includes('保留题甲'), 'deletion removed the wrong record'); + await page.screenshot({path: path.join(output, '03-delete.png'), fullPage: true}); + const users = [ + {id: 'review-a', name: '甲用户', email: 'a@fixture.invalid', records: ['甲-微积分-正确', '甲-几何-错误']}, + {id: 'review-b', name: '乙用户', email: 'b@fixture.invalid', records: ['乙-代数-正确']}, + {id: 'review-empty', name: '新用户', email: 'empty@fixture.invalid', records: []}, + ]; + await page.evaluate(users => window.__setUsers(users), users); + assert(await page.getByTestId('user-card').count() === users.length, 'user injection must replace the user list'); + for (const user of users) { + const card = page.locator(`[data-testid="user-card"][data-user-id="${user.id}"]`); + assert(await card.isVisible(), `missing user card ${user.id}`); + const text = await card.innerText(); + assert(text.includes(user.name) && text.includes(user.email), 'user basic info is not associated with the card'); + const records = await card.getByTestId('answer-record').allInnerTexts(); + assert(records.length === user.records.length && user.records.every(record => records.some(text => text.includes(record))), + `answer records associated with wrong user: ${user.id}`); + } + await page.screenshot({path: path.join(output, '04-user-record-association.png'), fullPage: true}); + console.log('Question CRUD, record independence and role restoration passed'); + } finally { await browser.close(); } +})().catch(error => { console.error(error); process.exit(1); }); diff --git a/task_007/tests/validate_semantics.js b/task_007/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_007/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_007/tests/validate_ui_behavior.js b/task_007/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..d1fecd4bc6ecdb6ba1bbaeecc1557853e02e4e46 --- /dev/null +++ b/task_007/tests/validate_ui_behavior.js @@ -0,0 +1,158 @@ +const assert = require('node:assert/strict'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +const { editQuestion } = require('./edit_question'); +const sel = id => `[data-testid="${id}"]`; + +async function questionStates(rows) { + return rows.evaluateAll(elements => elements.map(row => ({ + text: row.innerText.trim(), + states: [row, ...row.querySelectorAll('[aria-pressed], [aria-checked], [aria-label], [title]')] + .map(element => ['aria-pressed', 'aria-checked', 'aria-label', 'title'] + .map(attribute => element.getAttribute(attribute))), + }))); +} + +function publicationLabel([row]) { + const text = [row.text, ...row.states.flat()].join(' '); + const published = /\bpublished\b|已发布|已上线/i.test(text); + const unpublished = /\bunpublished\b|未发布|已下线/i.test(text); + return published === unpublished ? null : published; +} + +async function quietPointer(page) { + await page.mouse.move(0, 0); + await page.evaluate(() => document.activeElement?.blur()); +} + +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1200, height: 900 } }); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + + // --- Sections must exist --- + for (const id of ['admin-dashboard', 'question-bank', 'user-management', 'permission-management']) { + if (!(await page.locator(sel(id)).first().isVisible())) throw new Error(`missing section ${id}`); + } + + const items = page.locator('[data-testid="question-item"]'); + const input = page.locator('[data-testid="question-input"]'); + const uploadBtn = page.locator('[data-testid="upload-question"]'); + + // --- 1. Upload/add: adding a question grows the list and shows the text --- + const before = await items.count(); + await input.fill('集合论入门题'); + await uploadBtn.click(); + if ((await items.count()) !== before + 1) throw new Error('uploading a question should add it to the question bank'); + const added = items.last(); + if (!((await added.textContent()) || '').includes('集合论入门题')) { + throw new Error('the newly added question text should be rendered'); + } + + // Use two independently identifiable records. Check visible status and capture + // snapshots so an icon or other painted change need not alter the row text. + await input.fill('对照题目'); + await uploadBtn.click(); + const target = items.filter({hasText: '集合论入门题'}); + const peer = items.filter({hasText: '对照题目'}); + const active = await questionStates(target); + const other = await questionStates(peer); + await quietPointer(page); + const targetFrame = await target.screenshot({animations: 'disabled'}); + const peerFrame = await peer.screenshot({animations: 'disabled'}); + const peerBox = await peer.boundingBox(); + await target.locator(sel('offline-question')).click(); + await quietPointer(page); + const updated = await questionStates(target); + const updatedFrame = await target.screenshot({animations: 'disabled'}); + assert(!targetFrame.equals(updatedFrame), 'changing publication state must visibly update the selected question'); + assert.deepEqual(await questionStates(peer), other, 'changing publication affected another question'); + const updatedPeerBox = await peer.boundingBox(); + if (JSON.stringify(peerBox) === JSON.stringify(updatedPeerBox)) { + assert(peerFrame.equals(await peer.screenshot({animations: 'disabled'})), + 'changing publication changed another question’s status indicators'); + } + await target.locator(sel('offline-question')).click(); + await quietPointer(page); + const restored = await questionStates(target); + const restoredFrame = await target.screenshot({animations: 'disabled'}); + assert(JSON.stringify(restored) !== JSON.stringify(updated) || !restoredFrame.equals(updatedFrame), + 'republishing the question must visibly reverse the status change'); + const statuses = [active, updated, restored].map(publicationLabel); + if (statuses.every(status => status !== null)) { + assert(statuses[0] !== statuses[1] && statuses[0] === statuses[2], + 'visible publication labels do not follow the toggle'); + } + assert.deepEqual(await questionStates(peer), other, 'republishing affected another question'); + + // --- 3. Edit: editing marks/changes the question --- + const peerBeforeEdit = await questionStates(peer); + const countBeforeEdit = await items.count(); + await input.fill('集合论进阶题'); + await editQuestion(page, target.locator(sel('edit-question')), '集合论进阶题'); + const editedItem = items.filter({hasText: '集合论进阶题'}); + if (!((await editedItem.textContent()) || '').includes('集合论进阶题')) { + throw new Error('editing a question should update its content'); + } + + assert.equal(await items.count(), countBeforeEdit, 'editing changed the number of questions'); + assert.equal(await target.count(), 0, 'editing must replace the previous question text'); + assert.deepEqual(await questionStates(peer), peerBeforeEdit, 'editing changed another question'); + + // --- 4. Permission: as normal user, the admin-only delete control is hidden --- + const roleSelect = page.locator(sel('role-select')).first(); + const options = await roleSelect.locator('option').evaluateAll(es => es.map(e => ({value:e.value,text:e.textContent||''}))); + const normal = options.find(x => /normal user|普通用户/i.test(x.value+' '+x.text)); + const admin = options.find(x => /admin|管理员/i.test(x.value+' '+x.text)); + if (!normal || !admin) throw new Error('role selector should distinguish administrator and normal user'); + await roleSelect.selectOption(normal.value); + const actions = ['edit-question', 'offline-question', 'delete-question', 'upload-question']; + const contentAsNormal = await questionStates(items); + page.on('dialog', dialog => dialog.type() === 'prompt' ? dialog.accept('权限绕过题') : dialog.dismiss()); + for (const id of actions) { + if (id === 'upload-question') { + await input.evaluateAll(controls => controls.forEach(control => { + control.value = '权限绕过题'; + control.dispatchEvent(new Event('input', {bubbles: true})); + control.dispatchEvent(new Event('change', {bubbles: true})); + })); + } + for (const control of await page.locator(sel(id)).all()) { + assert(!await control.isVisible() || !await control.isEnabled(), + `normal user has an active ${id} control`); + const visibleRows = await page.locator('[data-testid="question-item"]:visible').all(); + const beforeClick = await Promise.all(visibleRows.map(row => row.screenshot({animations: 'disabled'}))); + await control.evaluate(element => element.click()); + assert.deepEqual(await questionStates(items), contentAsNormal, + `normal user changed the question bank via ${id}`); + const afterClick = await Promise.all(visibleRows.map(row => row.screenshot({animations: 'disabled'}))); + assert(afterClick.every((frame, index) => frame.equals(beforeClick[index])), + `normal user changed the painted question state via ${id}`); + } + } + + await roleSelect.selectOption(admin.value); + const beforeDelete = await items.count(); + await editedItem.locator(sel('delete-question')).click(); + assert.equal(await items.count(), beforeDelete - 1, 'admin must be able to delete a question'); + assert.equal(await editedItem.count(), 0, 'deletion must remove the requested question'); + assert.equal(await peer.count(), 1, 'deletion removed another question'); + + // --- 6. User management exposes answer records --- + if ((await page.locator(sel('answer-record')).count()) < 1) { + throw new Error('user management should expose answer records'); + } + const records = await page.locator(sel('answer-record')).allTextContents(); + if (records.some(text => !text.trim())) throw new Error('answer records must contain actual visible record text'); + const userText = (await page.locator(sel('user-management')).first().textContent()) || ''; + if (!userText.trim()) throw new Error('user management should show basic information'); + + // --- 7. Permission management distinguishes admin and normal user roles --- + const roleText = ((await page.locator(sel('permission-management')).first().textContent()) || '').toLowerCase(); + if (!(/admin|管理员/.test(roleText)) || !(/normal user|普通用户/.test(roleText))) { + throw new Error('permission management must distinguish admin and normal user roles'); + } + + await browser.close(); +})().catch(err => { console.error(err && err.stack || err); process.exit(1); }); diff --git a/task_008/acceptance_checklist.json b/task_008/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..f9b151ccf1ec80d02194410ebcb7de06b79bac84 --- /dev/null +++ b/task_008/acceptance_checklist.json @@ -0,0 +1,22 @@ +{ + "task_id": 9, + "category": "application_development", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Implements the requested domain workflow end to end.", + "Includes maintainable separation of concerns and meaningful tests when the task asks for them." + ], + "input_assets": [ + "convert.js", + "samples/" + ], + "expected_outputs": [], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns.", + "A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_008/environment/Dockerfile b/task_008/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5a67a7282ce857cf240bd806309b53b894a33a37 --- /dev/null +++ b/task_008/environment/Dockerfile @@ -0,0 +1,11 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends poppler-utils fonts-noto-cjk && rm -rf /var/lib/apt/lists/* +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_008/environment/code/convert.js b/task_008/environment/code/convert.js new file mode 100644 index 0000000000000000000000000000000000000000..cd0a1bd095196b4c71e015f298c621a1efe253d0 --- /dev/null +++ b/task_008/environment/code/convert.js @@ -0,0 +1,24 @@ +const fs = require('fs'); +const path = require('path'); + +function convertMarkdownToPdf(inputPath, outputPath) { + const markdown = fs.readFileSync(inputPath, 'utf8'); + // TODO: render inline math such as \(\sqrt{2}\) as normal math. + fs.writeFileSync(outputPath, '%PDF-1.4\n' + markdown + '\n%%EOF\n', 'utf8'); +} + +function convertBatch(inputDir, outputDir) { + fs.mkdirSync(outputDir, { recursive: true }); + for (const file of fs.readdirSync(inputDir)) { + if (file.endsWith('.md')) { + convertMarkdownToPdf(path.join(inputDir, file), path.join(outputDir, file.replace(/\.md$/, '.pdf'))); + } + } +} + +if (require.main === module) { + const [inputDir = 'samples', outputDir = 'out'] = process.argv.slice(2); + convertBatch(inputDir, outputDir); +} + +module.exports = { convertMarkdownToPdf, convertBatch }; diff --git a/task_008/environment/code/out/math.pdf b/task_008/environment/code/out/math.pdf new file mode 100644 index 0000000000000000000000000000000000000000..6bb58b72d35f4f376e19943ec40b0de6526e893b --- /dev/null +++ b/task_008/environment/code/out/math.pdf @@ -0,0 +1,4 @@ +%PDF-1.4 +\(\sqrt{2}\) + +%%EOF diff --git a/task_008/environment/code/samples/math.md b/task_008/environment/code/samples/math.md new file mode 100644 index 0000000000000000000000000000000000000000..a6a6731a3d76ddff72ebc4abb863b4358052063e --- /dev/null +++ b/task_008/environment/code/samples/math.md @@ -0,0 +1 @@ +\(\sqrt{2}\) diff --git a/task_008/environment/docker-compose.yaml b/task_008/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_008/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_008/instruction.md b/task_008/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e30ed9ee2ce02ba18bc3011b1c6a3642e7f8024f --- /dev/null +++ b/task_008/instruction.md @@ -0,0 +1,17 @@ +# Offline Markdown-to-PDF batch converter + +Complete the supplied Node.js converter in `convert.js`. Keep the bundled `samples/` directory. Convert local Markdown to readable PDFs without network access. + +## Interface and output + +Run `node convert.js ` or import the exported `convertBatch(inputDir, outputDir)`. The export may finish synchronously or return a Promise that resolves once conversion is complete. + +Convert every top-level `.md` input to a separate `.pdf` with the same base name, including names containing Chinese characters. Generate genuine PDFs with extractable text; any valid internal PDF representation is acceptable. Render level-one headings, bold and inline code without the raw Markdown delimiters. Render inline `\(\sqrt{2}\)` as a readable square-root expression such as √2 or `sqrt(2)`, retaining the surrounding text without raw LaTeX markers. + +Preserve both Chinese and English glyphs and text. Wrap long lines, paginate long documents and keep text within the page. The environment includes Playwright/Chromium, Poppler and Noto CJK fonts; other offline implementations are allowed. + +## Acceptance Checklist + +- The CLI and exported function produce parseable PDFs. Each input has a correctly named output with its own content and no text belonging to another input. +- Text extraction preserves Chinese and English content, heading/bold/code text and the rendered inline square root without raw syntax. +- Long documents retain their content through the end; wrapped and paginated text lies inside the visible page boundaries. diff --git a/task_008/quality_notes.md b/task_008/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..8da9186e00ac25a6fdb20000e9bb7861ad049825 --- /dev/null +++ b/task_008/quality_notes.md @@ -0,0 +1,4 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. \ No newline at end of file diff --git a/task_008/solution/README.md b/task_008/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_008/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_008/solution/code/convert.js b/task_008/solution/code/convert.js new file mode 100644 index 0000000000000000000000000000000000000000..00021ba8f7f612e2df7dc27324dd90e441dfca5f --- /dev/null +++ b/task_008/solution/code/convert.js @@ -0,0 +1,74 @@ +const fs = require('node:fs/promises'); +const path = require('node:path'); +const {chromium} = require('playwright'); + +function escapeHtml(text) { + return text.replace(/[&<>"']/g, ch => ({'&':'&', '<':'<', '>':'>', '"':'"', "'":'''}[ch])); +} + +function renderInlineMath(text) { + return text.replace(/\\\(\s*\\sqrt\{([^}]+)\}\s*\\\)/g, 'sqrt($1)'); +} + +function inline(text) { + // Code spans are escaped, but not interpreted as Markdown or math. + return text.split(/(`[^`]*`)/g).map(part => { + if (part.startsWith('`') && part.endsWith('`')) return `${escapeHtml(part.slice(1, -1))}`; + return escapeHtml(renderInlineMath(part)).replace(/\*\*([^*]+)\*\*/g, '$1'); + }).join(''); +} + +function renderMarkdown(markdown) { + return markdown.replace(/\r\n/g, '\n').split('\n').map(line => { + const heading = line.match(/^\s{0,3}(#{1,6})\s+(.+)$/); + if (heading) return `${inline(heading[2])}`; + return line.trim() ? `

    ${inline(line)}

    ` : '
    '; + }).join('\n'); +} + +async function writePdf(browser, inputPath, outputPath) { + const markdown = await fs.readFile(inputPath, 'utf8'); + const page = await browser.newPage(); + try { + await page.route(/^https?:/, route => route.abort()); + await page.setContent(` + ${renderMarkdown(markdown)}`); + await page.evaluate(() => document.fonts.ready); + await fs.mkdir(path.dirname(outputPath), {recursive: true}); + await page.pdf({path: outputPath, format: 'A4', printBackground: true, + margin: {top: '18mm', bottom: '18mm', left: '18mm', right: '18mm'}}); + } finally { await page.close(); } +} + +async function withBrowser(action) { + const browser = await chromium.launch({headless: true, args: ['--no-sandbox']}); + try { return await action(browser); } finally { await browser.close(); } +} + +async function convertMarkdownToPdf(inputPath, outputPath) { + return withBrowser(browser => writePdf(browser, inputPath, outputPath)); +} + +async function convertBatch(inputDir, outputDir) { + await fs.mkdir(outputDir, {recursive: true}); + const entries = await fs.readdir(inputDir, {withFileTypes: true}); + await withBrowser(async browser => { + for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) { + if (!entry.isFile() || !entry.name.endsWith('.md')) continue; + await writePdf(browser, path.join(inputDir, entry.name), path.join(outputDir, entry.name.slice(0, -3) + '.pdf')); + } + }); +} + +if (require.main === module) { + const [inputDir = 'samples', outputDir = 'out'] = process.argv.slice(2); + convertBatch(inputDir, outputDir).catch(error => { console.error(error); process.exitCode = 1; }); +} + +module.exports = {convertBatch, convertMarkdownToPdf, renderInlineMath, renderMarkdown}; diff --git a/task_008/solution/code/index.html b/task_008/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..fde704e1da5388d805d96537ab28763a95a58633 --- /dev/null +++ b/task_008/solution/code/index.html @@ -0,0 +1,71 @@ + + + + + +Markdown Batch Converter + + + +

    Markdown Batch Converter (PDF Export)

    +
    +

    Enter Markdown on the left and convert it to see a preview. For command-line batch conversion, use node convert.js samples out.

    +
    +
    + + +
    +
    + +
    The preview will appear here.
    +
    +
    +
    + + +
    +

    Ready.

    +
    + + + + diff --git a/task_008/solution/code/out/math.pdf b/task_008/solution/code/out/math.pdf new file mode 100644 index 0000000000000000000000000000000000000000..20dd2cbe0013de604ef6899224c0bc6b7b310ffa --- /dev/null +++ b/task_008/solution/code/out/math.pdf @@ -0,0 +1,45 @@ +%PDF-1.4 +1 0 obj +<< /Type /Catalog /Pages 2 0 R >> +endobj +2 0 obj +<< /Type /Pages /Kids [3 0 R] /Count 1 >> +endobj +3 0 obj +<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 4 0 R /Sym 5 0 R >> >> /Contents 6 0 R >> +endobj +4 0 obj +<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> +endobj +5 0 obj +<< /Type /Font /Subtype /Type1 /BaseFont /Symbol >> +endobj +6 0 obj +<< /Length 76 >> +stream +BT +/F1 12 Tf +16 TL +72 720 Td +/Sym 12 Tf (\326) Tj +/F1 12 Tf +(2) Tj +T* +T* +ET +endstream +endobj +xref +0 7 +0000000000 65535 f +0000000009 00000 n +0000000058 00000 n +0000000115 00000 n +0000000252 00000 n +0000000349 00000 n +0000000416 00000 n +trailer +<< /Size 7 /Root 1 0 R >> +startxref +541 +%%EOF diff --git a/task_008/solution/solve.sh b/task_008/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_008/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_008/task.toml b/task_008/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_008/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_008/task_meta.json b/task_008/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..da1d0ed49d5512e2717d5cb08563ffe29af9e4d4 --- /dev/null +++ b/task_008/task_meta.json @@ -0,0 +1,32 @@ +{ + "task_id": 9, + "task_category": "application_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 4, + "language": "javascript", + "tool_files_from_selected_trace": [ + "README.md", + "batch-processor.js", + "converter.js", + "index.js", + "math-css.css", + "math-example.md", + "mdconvert.js", + "package.json", + "pdf-generator.js", + "sample.md", + "simple-math-test.html", + "simple-math.md", + "sqrt-formula.md", + "中文文档.md" + ], + "input_assets": [ + "convert.js", + "samples/" + ], + "expected_outputs": [], + "source_row_id": 54, + "repair_revision": "2026-09-29", + "instruction_sha256": "c11e3fdc333e15065703e6cecc4cb9ef0464e1576cc1f154b70ff2dc248b0b3b" +} diff --git a/task_008/tests/_shared/contract_checker.js b/task_008/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_008/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_008/tests/_shared/static_enhancer.sh b/task_008/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_008/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_008/tests/enhancement_cases.json b/task_008/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..745df9fc058bfbbcf4266906f881f4f7ae8896ec --- /dev/null +++ b/task_008/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","instruction_evidence":"做一个 Markdown 批量转换工具,支持 pdf 导出","validator":"validate_enhanced_cases.js","behavior":"临时目录中两个不同Markdown一次转换为两个不同PDF,不限定输出文件名"}, + {"case_id":"ENHANCED_CASE_2","instruction_evidence":"输出必须是结构有效、可被 viewer 打开的 PDF:包含 `%PDF-` 头、body objects、`xref` 表、正确的 `startxref` 偏移、`trailer` 和 `%%EOF`","validator":"validate_enhanced_cases.js","behavior":"三文件输入的每个PDF均检查完整结构与真实xref偏移"}, + {"case_id":"ENHANCED_CASE_3","instruction_evidence":"行内 LaTeX `\\(\\sqrt{2}\\)` 必须渲染为普通平方根表达式(例如 √2 或 `sqrt(2)`),不能残留原始 LaTeX 标记","validator":"validate_enhanced_cases.js","behavior":"在新的上下文文本中验证题面指定sqrt(2)被渲染且无原始LaTeX残留"} +] diff --git a/task_008/tests/test.sh b/task_008/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c0b18f8677b92686183f200208e4457c4d652ce0 --- /dev/null +++ b/task_008/tests/test.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_ui_behavior.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +run validate_readability.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_008/tests/validate_aaav_dynamic.js b/task_008/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..7a0c1d79ee5910def85007bdb41a154f16087f39 --- /dev/null +++ b/task_008/tests/validate_aaav_dynamic.js @@ -0,0 +1,155 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 9; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + // This is a Markdown -> PDF batch CLI task; the instruction never requires a web UI. + // The dynamic browser check only applies when the solution ships an HTML/SVG entrypoint. + // If none exists, treat this check as not-applicable and pass (PDF structure checks + // are enforced in validate_ui_behavior.js). + if (!entry) { + console.log(`AAAV dynamic test skipped for task ${TASK_ID}: no browser-openable entrypoint (CLI-only solution)`); + return; + } + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_008/tests/validate_browser_smoke.js b/task_008/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..0103ad86d2ad291d45022fb577b31dc8b9049f51 --- /dev/null +++ b/task_008/tests/validate_browser_smoke.js @@ -0,0 +1,119 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +const mode = "frontend"; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +const files = walk(process.cwd()); +const html = files.find(f => f.toLowerCase().endsWith('.html')); +const svg = files.find(f => f.toLowerCase().endsWith('.svg')); +const target = mode === 'svg' ? svg : (html || svg); +// This is a Markdown -> PDF batch CLI task; the instruction never requires a web UI. +// The browser smoke check is only applicable when the solution ships an HTML/SVG +// entrypoint. If none exists in cwd, treat the browser smoke as not-applicable and +// pass (the instruction-required PDF structure checks live in validate_ui_behavior.js). +if (!target) { + console.log('browser smoke skipped for task 9: no browser-openable entrypoint (CLI-only solution)'); + process.exit(0); +} + +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 960, height: 720 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileURL(target).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(600); + if (errors.length) throw new Error('browser errors: ' + errors.join(' | ')); + + const stats = await page.evaluate((mode) => { + const visible = Array.from(document.querySelectorAll('body *')).filter(el => { + const rect = el.getBoundingClientRect(); + const style = window.getComputedStyle(el); + return rect.width > 0 && rect.height > 0 && style.visibility !== 'hidden' && style.display !== 'none'; + }); + const buttons = document.querySelectorAll('button, [role="button"], input, select, textarea').length; + const canvasInfo = Array.from(document.querySelectorAll('canvas')).map(c => { + let nonBlank = false; + try { + const ctx = c.getContext('2d'); + if (ctx && c.width && c.height) { + const data = ctx.getImageData(0, 0, Math.min(c.width, 32), Math.min(c.height, 32)).data; + nonBlank = Array.from(data).some((v, i) => i % 4 !== 3 && v !== 0); + } + } catch (e) {} + return { width: c.width, height: c.height, nonBlank }; + }); + const svgElements = document.querySelectorAll('svg *').length; + return { + bodyTextLength: (document.body && document.body.innerText || '').trim().length, + visibleCount: visible.length, + buttons, + canvasInfo, + svgElements, + localStorageLength: window.localStorage ? window.localStorage.length : 0, + mode, + }; + }, mode); + + if (stats.visibleCount < (mode === 'svg' ? 3 : 5)) { + throw new Error('too few visible browser elements: ' + stats.visibleCount); + } + if (mode === 'svg' && stats.svgElements < 2) { + throw new Error('too few rendered svg elements: ' + stats.svgElements); + } + if (stats.canvasInfo.length) { + const validCanvas = stats.canvasInfo.some(c => c.width >= 100 && c.height >= 100); + if (!validCanvas) throw new Error('canvas exists but has invalid dimensions'); + } + + const before = await page.evaluate(() => { + const canvases = Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL(); } catch (e) { return ''; } + }); + return JSON.stringify({ + text: document.body.innerText, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: canvases, + }); + }); + const clickable = await page.$('button, [role="button"], input[type="button"], input[type="submit"], canvas, svg, body'); + if (clickable) await clickable.click({ position: { x: 20, y: 20 } }).catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.keyboard.press('ArrowDown').catch(() => {}); + await page.keyboard.press('Enter').catch(() => {}); + await page.waitForTimeout(300); + const after = await page.evaluate(() => { + const canvases = Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL(); } catch (e) { return ''; } + }); + return JSON.stringify({ + text: document.body.innerText, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: canvases, + }); + }); + if (mode === 'frontend' && stats.buttons === 0 && stats.canvasInfo.length === 0 && stats.bodyTextLength < 20) { + throw new Error('frontend has no meaningful controls, canvas, or text content'); + } + if (errors.length) throw new Error('browser errors after interaction: ' + errors.join(' | ')); + console.log('browser smoke passed for task 9; interaction_changed=' + (before !== after)); + await browser.close(); +})().catch(async err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_008/tests/validate_enhanced_cases.js b/task_008/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..f715762b211f81d33f9267e1b26c0ad7e9543534 --- /dev/null +++ b/task_008/tests/validate_enhanced_cases.js @@ -0,0 +1,11 @@ +const fs=require('fs'),os=require('os'),path=require('path'),cp=require('child_process');function assert(x,m){if(!x)throw new Error(m)}const converter=path.join(process.cwd(),'convert.js');function run(files){const root=fs.mkdtempSync(path.join(os.tmpdir(),'task009-enhanced-')),input=path.join(root,'samples'),out=path.join(root,'out');fs.mkdirSync(input);for(const [n,t] of Object.entries(files))fs.writeFileSync(path.join(input,n),t);const r=cp.spawnSync(process.execPath,[converter,input,out],{cwd:process.cwd(),timeout:15000,env:{...process.env,NO_PROXY:'*',HTTP_PROXY:'',HTTPS_PROXY:''},encoding:'utf8'});assert(r.status===0,`conversion failed: ${r.stderr||r.stdout}`);return{root,out,pdfs:fs.readdirSync(out).filter(n=>/\.pdf$/i.test(n)).map(n=>path.join(out,n))}}function valid(p){const info=cp.spawnSync('pdfinfo',[p],{encoding:'utf8'});assert(info.status===0,`pdfinfo rejected ${p}: ${info.stderr}`);const text=cp.spawnSync('pdftotext',[p,'-'],{encoding:'utf8'});assert(text.status===0,`pdftotext rejected ${p}: ${text.stderr}`);return text.stdout} +try{ + // ENHANCED_CASE_1: two different Markdown inputs are converted as a batch into two different PDFs. + {const x=run({'alpha.md':'# Alpha\nfirst document','beta.md':'# Beta\nsecond document'});assert(x.pdfs.length===2,'batch conversion must emit one PDF for each Markdown input');const texts=x.pdfs.map(valid);assert(texts.some(t=>/Alpha/.test(t))&&texts.some(t=>/Beta/.test(t)),'different inputs must produce PDFs containing their own text');fs.rmSync(x.root,{recursive:true,force:true})} + // ENHANCED_CASE_2: every PDF from a three-file batch has the required viewer-readable structure. + {const x=run({'one.md':'one','two.md':'two','three.md':'three'});assert(x.pdfs.length===3,'three Markdown inputs must produce three PDFs');x.pdfs.forEach(valid);fs.rmSync(x.root,{recursive:true,force:true})} + // ENHANCED_CASE_3: the specified sqrt(2) fixture embedded in new surrounding text renders without raw LaTeX. + {const x=run({'math.md':'Unique prefix 731: \\(\\sqrt{2}\\) unique suffix'});assert(x.pdfs.length===1,'math input must produce a PDF');const text=valid(x.pdfs[0]),compact=text.replace(/\s/g,'');assert(/731/.test(text)&&/(√2|sqrt\(?2\)?)/i.test(compact),'parsed PDF should preserve surrounding text and rendered sqrt(2)');assert(!/\\sqrt|\\\(|\\\)/.test(text),'raw LaTeX must not remain visible');fs.rmSync(x.root,{recursive:true,force:true})} + // ENHANCED_CASE_4: common Markdown syntax must become rendered text, not leak literal markup. + {const x=run({'format.md':'# Overview\nThis is **bold** and `code`.'});const t=valid(x.pdfs[0]);assert(/Overview/.test(t)&&/bold/.test(t)&&/code/.test(t),'Markdown content missing');assert(!/# Overview|\*\*bold\*\*|`code`/.test(t),'raw Markdown markers leaked into PDF text');fs.rmSync(x.root,{recursive:true,force:true})} + console.log('enhanced cases passed for task 9')}catch(e){console.error(e.stack||e);process.exit(1)} diff --git a/task_008/tests/validate_readability.js b/task_008/tests/validate_readability.js new file mode 100644 index 0000000000000000000000000000000000000000..2235c648d3a86e490f241bb767efdaab7ac9cdb8 --- /dev/null +++ b/task_008/tests/validate_readability.js @@ -0,0 +1,100 @@ +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const cp = require('child_process'); +const assert = (ok, message) => { if (!ok) throw Error(message); }; + +function run(command, args) { + const result = cp.spawnSync(command, args, {encoding: 'utf8', timeout: 45000}); + assert(result.status === 0, `${command} failed: ${result.stderr || result.stdout}`); + return result.stdout; +} + +function readPages(pdf) { + const xml = run('pdftotext', ['-bbox', '-cropbox', pdf, '-']); + return Array.from(xml.matchAll(/([\s\S]*?)<\/page>/g), ([, width, height, content]) => { + const words = Array.from( + content.matchAll(/([^<]*)<\/word>/g), + ([, left, top, right, bottom, text]) => ({ + left: Number(left), top: Number(top), right: Number(right), bottom: Number(bottom), text + }) + ); + return {width: Number(width), height: Number(height), words}; + }); +} + +function checkWordBounds({width, height, words}) { + for (const {left, top, right, bottom} of words) { + assert(left >= -1 && top >= -1 && right <= width + 1 && bottom <= height + 1, + 'text extends beyond the visible PDF page'); + } +} + +function checkEnglishBodyOverlap({words}, pageNumber) { + // Compare ordinary multi-character English word boxes. This avoids applying + // Latin font metrics to CJK punctuation and ignores small glyph overshoots. + const body = words.filter(word => /[A-Za-z]{4}/.test(word.text) + && word.right > word.left && word.bottom > word.top).sort((a, b) => a.top - b.top); + for (const [index, word] of body.entries()) { + for (let next = index + 1; next < body.length && body[next].top < word.bottom; next++) { + const other = body[next]; + const sharedWidth = Math.min(word.right, other.right) - Math.max(word.left, other.left); + const sharedHeight = Math.min(word.bottom, other.bottom) - other.top; + const widthThreshold = 0.7 * Math.min(word.right - word.left, other.right - other.left); + const heightThreshold = 0.7 * Math.min(word.bottom - word.top, other.bottom - other.top); + assert(sharedWidth <= widthThreshold || sharedHeight <= heightThreshold, + `overlapping body words on page ${pageNumber}: ${word.text} / ${other.text}`); + } + } +} + +function normalizeEnglishText(text) { + return text.replace(/\u00ad|-(?=[\r\n])|\s/g, ''); +} + +const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'ux008-readable-')); +try { + const input = path.join(scratch, 'input'); + const output = path.join(scratch, 'output'); + const evidence = '/logs/verifier/pdf-audit'; + fs.mkdirSync(input); + fs.mkdirSync(evidence, {recursive: true}); + const markers = Array.from({length: 144}, (_, i) => `AUDITROW_${String(i).padStart(3, '0')}`); + const repeats = 90; + fs.writeFileSync(path.join(input, '中文报告.md'), '# 中文报告\n你好,离线批量转换。\n**完整内容**和`代码`必须保留。\n\\(\\sqrt{2}\\)\nUNIQUE_CHINESE_DOC'); + fs.writeFileSync(path.join(input, 'long.md'), '# Long document\n\n' + + markers.map(marker => `${marker} visible text must survive page breaks.`).join('\n\n') + + '\n\n' + 'LongLineContent '.repeat(repeats) + 'UNIQUE_LONG_END'); + run(process.execPath, [path.join(process.cwd(), 'convert.js'), input, output]); + const chinese = path.join(output, '中文报告.pdf'); + const long = path.join(output, 'long.pdf'); + const chineseText = run('pdftotext', [chinese, '-']).replace(/\s/g, ''); + assert(chineseText.includes('中文报告') && chineseText.includes('你好,离线批量转换。') + && chineseText.includes('完整内容') && chineseText.includes('代码'), 'CJK text lost or replaced by missing glyphs'); + assert(!chineseText.includes('AUDITROW_'), 'another document leaked into the Chinese PDF'); + const longText = normalizeEnglishText(run('pdftotext', [long, '-'])); + assert(markers.every(marker => longText.includes(marker)) && longText.includes('UNIQUE_LONG_END'), + 'long document or wrapped-line content is missing'); + assert(!longText.includes('UNIQUE_CHINESE_DOC'), 'batch documents were mixed together'); + assert(longText.split('LongLineContent').length - 1 === repeats, + 'long wrapped paragraph must retain every repeated word exactly once'); + for (const pdf of [chinese, long]) { + const pages = readPages(pdf); + assert(pages.some(page => page.words.length), 'PDF has no extractable positioned text'); + if (pdf === long) { + const bodyPages = pages.filter(page => /AUDITROW_|LongLineContent/.test(page.words.map(word => word.text).join(''))); + assert(bodyPages.length > 1, 'long document body must span multiple pages'); + const visibleText = normalizeEnglishText(pages.flatMap(page => page.words.map(word => word.text)).join('\n')); + assert(markers.every(marker => visibleText.includes(marker)) && visibleText.includes('UNIQUE_LONG_END'), + 'long body must retain all paragraphs inside the visible pages'); + assert(visibleText.split('LongLineContent').length - 1 === repeats, + 'long wrapped paragraph must retain all repeated words inside the visible pages'); + pages.forEach((page, index) => checkEnglishBodyOverlap(page, index + 1)); + } + pages.forEach(checkWordBounds); + const name = path.basename(pdf, '.pdf'); + fs.copyFileSync(pdf, path.join(evidence, name + '.pdf')); + run('pdftoppm', ['-r', '80', '-png', pdf, path.join(evidence, name)]); + } + console.log('CJK, long-line wrapping, pagination, visible bounds and independent batch documents passed'); +} finally { fs.rmSync(scratch, {recursive: true, force: true}); } diff --git a/task_008/tests/validate_semantics.js b/task_008/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_008/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_008/tests/validate_ui_behavior.js b/task_008/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..e4b587e5b65084b0bfef75e8c64e4f365e87a000 --- /dev/null +++ b/task_008/tests/validate_ui_behavior.js @@ -0,0 +1,26 @@ +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const cp = require('child_process'); + +(async () => { + const converter = path.join(process.cwd(), 'convert.js'); + const samples = path.join(process.cwd(), 'samples'); + if (!fs.existsSync(converter) || !fs.existsSync(samples)) throw Error('convert.js and samples are required'); + const output = fs.mkdtempSync(path.join(os.tmpdir(), 'ux009-api-')); + try { + const mod = require(converter); + if (typeof mod.convertBatch !== 'function') throw Error('convert.js must export convertBatch'); + await mod.convertBatch(samples, output); + const pdf = path.join(output, 'math.pdf'); + for (const [command, args] of [['pdfinfo', [pdf]], ['pdftotext', [pdf, '-']]]) { + const result = cp.spawnSync(command, args, {encoding: 'utf8', timeout: 15000}); + if (result.status !== 0) throw Error(`${command} rejected PDF: ${result.stderr}`); + if (command === 'pdftotext') { + if (!/(√2|sqrt\(?2\)?)/i.test(result.stdout.replace(/\s/g, ''))) throw Error('rendered sqrt(2) is missing'); + if (/\\sqrt|\\\(|\\\)/.test(result.stdout)) throw Error('raw LaTeX is visible'); + } + } + console.log('Parsed batch PDF export passed'); + } finally { fs.rmSync(output, {recursive: true, force: true}); } +})().catch(error => { console.error(error); process.exit(1); }); diff --git a/task_009/acceptance_checklist.json b/task_009/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..eeaf7592f06877c56c8f2c418641748938166247 --- /dev/null +++ b/task_009/acceptance_checklist.json @@ -0,0 +1,21 @@ +{ + "task_id": 10, + "category": "application_development", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Implements the requested domain workflow end to end.", + "Includes maintainable separation of concerns and meaningful tests when the task asks for them." + ], + "input_assets": [ + "index.html" + ], + "expected_outputs": [], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns.", + "A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_009/environment/Dockerfile b/task_009/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_009/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_009/environment/code/index.html b/task_009/environment/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..457867aeb68978286175a26357225fa77b3b8ac4 --- /dev/null +++ b/task_009/environment/code/index.html @@ -0,0 +1,44 @@ + + + + + Multi Block Prompt Fixture + + + +
    + +
    +
    +
    + + + not sent +
    +
    + +
    +
    + + + diff --git a/task_009/environment/docker-compose.yaml b/task_009/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_009/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_009/instruction.md b/task_009/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..858b95236f027a2e78e5c1039492d5972fae9a48 --- /dev/null +++ b/task_009/instruction.md @@ -0,0 +1,22 @@ +# Concurrent prompt and response blocks + +Extend the supplied single-block page into a workspace for independent prompt requests. Keep the root `index.html` directly openable offline, using local mock generation rather than an external AI service. + +## Interaction + +Start with one draft block. Ignore empty sends. Sending puts that block into a visible loading state immediately. Draft text alone must not reveal the add-block control. Show exactly one add-block placeholder whenever all existing blocks have been submitted, including pending, completed and failed requests. Clicking it adds a draft, focuses the new input and hides the placeholder until the new draft is submitted. + +Let multiple blocks generate concurrently. Results and failures belong only to their originating block, even when requests finish out of order. Keep the response area visible while pending and show loading text such as “Generating” or “生成中”, or a visible indicator with `aria-busy="true"`. Show failure in that block's response area (for example, “Error” or “失败”). A completed or failed request stops loading, and the block can be edited and submitted again. Updates in another block must not steal focus or discard edits. + +## Integration and layout + +Use centralized lifecycle state (a block manager with app-level state and change notifications); keep each block's state independent and update it through the manager rather than mutating rendered components independently. Expose `window.__setMockGenerate(fn)`, where `fn(prompt, blockId)` returns a Promise of response text. Use distinct, stable IDs for blocks. Preserve `data-testid` hooks `sidebar`, `content`, `prompt-response-block`, `prompt-input`, `send-button`, `response`, and `new-block-placeholder`. + +The sidebar displays the status of each block. At 1200 px viewport width, use a 240 px sidebar, 32 px spacing, and a fluid centered content area with a 900 px maximum and 16 px side padding. Keep the page scrollable with a Raycast-style custom scrollbar; define shared dimensions as CSS variables and adapt the layout on narrow screens. + +## Acceptance Checklist + +- Offline rendering preserves the sidebar and responsive content dimensions; at phone width the page does not scroll horizontally. +- Blank sends and unsent drafts do not unlock the placeholder. Submitting each draft enables one placeholder, and adding a block focuses its input. +- Concurrent blocks show loading independently, have distinct IDs and retain their own out-of-order results. The sidebar tracks statuses and completion does not steal focus. +- Resubmitting a completed or failed block updates that block without creating a duplicate. A local failure leaves other results intact and does not block adding another block. diff --git a/task_009/quality_notes.md b/task_009/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..8da9186e00ac25a6fdb20000e9bb7861ad049825 --- /dev/null +++ b/task_009/quality_notes.md @@ -0,0 +1,4 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. \ No newline at end of file diff --git a/task_009/solution/README.md b/task_009/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_009/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_009/solution/code/index.html b/task_009/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..ed5e24336d29499279f8e286fc783f60536e6f24 --- /dev/null +++ b/task_009/solution/code/index.html @@ -0,0 +1,119 @@ + + + + + Multi Block Prompt Solution + + + +
    + +
    +
    + +
    +
    + + + diff --git a/task_009/solution/solve.sh b/task_009/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_009/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_009/task.toml b/task_009/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_009/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_009/task_meta.json b/task_009/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..a3868fc34b10cef71376abef2380344cc705d95d --- /dev/null +++ b/task_009/task_meta.json @@ -0,0 +1,27 @@ +{ + "task_id": 10, + "task_category": "application_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 2, + "language": "javascript", + "tool_files_from_selected_trace": [ + "AIContentArea.tsx", + "LayoutWindow.tsx", + "MainContentArea.tsx", + "NavigationSidebar.tsx", + "PlaceholderBlock.tsx", + "PromptResponseBlock.tsx", + "ai-state-machine.ts", + "globals.css", + "page.tsx", + "tailwind.config.ts" + ], + "input_assets": [ + "index.html" + ], + "expected_outputs": [], + "source_row_id": 60, + "repair_revision": "2026-09-29", + "instruction_sha256": "82e193df2e47188980021bc662e853eb123722b472e76fd96bbf069b495dc39f" +} diff --git a/task_009/tests/_shared/contract_checker.js b/task_009/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_009/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_009/tests/_shared/static_enhancer.sh b/task_009/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_009/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_009/tests/enhancement_cases.json b/task_009/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..4dabb33cf0a63628596e22f2a3ba134e10b890fc --- /dev/null +++ b/task_009/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","instruction_evidence":"只有当所有现有块都已发送或有内容时才显示新块占位符;确保同时只有一个 \"添加新块\" 占位符","validator":"validate_enhanced_cases.js","behavior":"初始隐藏,发送现有块后仅显示一个新增块入口"}, + {"case_id":"ENHANCED_CASE_2","instruction_evidence":"用户可以通过点击占位符添加新的提示块;要求为新块提供自动聚焦","validator":"validate_enhanced_cases.js","behavior":"点击占位符恰好增加一个块并聚焦新输入框"}, + {"case_id":"ENHANCED_CASE_3","instruction_evidence":"每个块拥有独立的状态机,互不干扰;多个块可以同时进行 AI 生成,不相互阻塞","validator":"validate_enhanced_cases.js","behavior":"两个不同输入保留各自不同的响应与状态"} +] diff --git a/task_009/tests/test.sh b/task_009/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ab2150eb79f6f15b53d20b21738b84bbe0d8003 --- /dev/null +++ b/task_009/tests/test.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_ui_behavior.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_009/tests/validate_aaav_dynamic.js b/task_009/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..9c180db66306c2d22ce080818565943e88131377 --- /dev/null +++ b/task_009/tests/validate_aaav_dynamic.js @@ -0,0 +1,148 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 10; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_009/tests/validate_browser_smoke.js b/task_009/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_009/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_009/tests/validate_enhanced_cases.js b/task_009/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..fdd11bec526b9e4530604b5fceedfc4534fbcd48 --- /dev/null +++ b/task_009/tests/validate_enhanced_cases.js @@ -0,0 +1,195 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { pathToFileURL } = require('node:url'); +const { chromium } = require('playwright'); + +const auditDir = '/logs/verifier/visual'; +const locator = (page, name) => page.getByTestId(name); + +async function open(browser) { + const page = await browser.newPage({ viewport: { width: 1200, height: 800 } }); + await page.route(/^https?:/, route => route.abort()); + await page.goto(pathToFileURL(path.resolve('index.html')).href); + await page.evaluate(() => { + window.__requests = []; + window.__setMockGenerate((prompt, id) => new Promise((resolve, reject) => { + window.__requests.push({ prompt, id, resolve, reject }); + })); + }); + return page; +} + +async function send(page, index, prompt) { + await locator(page, 'prompt-input').nth(index).fill(prompt); + await locator(page, 'send-button').nth(index).click(); + await page.waitForFunction(value => window.__requests.some(r => r.prompt === value), prompt); +} + +async function settle(page, prompt, text, reject = false) { + await page.evaluate(({ prompt, text, reject }) => { + const request = window.__requests.find(r => r.prompt === prompt); + if (!request) throw new Error(`missing request: ${prompt}`); + if (reject) request.reject(new Error(text)); + else request.resolve(text); + }, { prompt, text, reject }); +} + +async function pending(page, index) { + const block = locator(page, 'prompt-response-block').nth(index); + const response = locator(page, 'response').nth(index); + assert(await response.isVisible(), 'pending response area must be visible'); + const text = await response.innerText(); + const busy = await block.evaluate(el => el.getAttribute('aria-busy') === 'true' || + [...el.querySelectorAll('[aria-busy="true"]')].some(node => { + const box = node.getBoundingClientRect(); + const style = getComputedStyle(node); + return box.width > 0 && box.height > 0 && style.visibility !== 'hidden'; + })); + assert(busy || /loading|generating|pending|加载|生成中|处理中/i.test(text), + 'pending request needs a visible loading indicator (localized text or aria-busy)'); +} + +async function responseIs(page, index, expected) { + await page.waitForFunction(({ index, expected }) => + document.querySelectorAll('[data-testid="response"]')[index]?.textContent.trim() === expected, + { index, expected }); +} + +async function assertSameBlockId(page, initialPrompt, laterPrompt) { + const stable = await page.evaluate(([first, later]) => { + const initial = window.__requests.find(request => request.prompt === first); + const current = window.__requests.find(request => request.prompt === later); + return initial?.id != null && current?.id === initial.id; + }, [initialPrompt, laterPrompt]); + assert(stable, 'resubmission must retain the original block ID passed to the generator'); +} + +async function sidebarFrame(page) { + return locator(page, 'sidebar').screenshot({animations: 'disabled', caret: 'hide'}); +} + +async function waitForSidebarChange(page, previous) { + const deadline = Date.now() + 3000; + do { + const frame = await sidebarFrame(page); + if (!frame.equals(previous)) return frame; + await page.waitForTimeout(40); + } while (Date.now() < deadline); + assert.fail('sidebar must visibly indicate the block status change'); +} + +async function completeFirstBlockSidebar(browser) { + const page = await open(browser); + try { + const initial = await sidebarFrame(page); + await send(page, 0, 'alpha pending'); + const firstPending = await waitForSidebarChange(page, initial); + await locator(page, 'new-block-placeholder').click(); + const newDraft = await waitForSidebarChange(page, firstPending); + await send(page, 1, 'beta pending'); + const bothPending = await waitForSidebarChange(page, newDraft); + await settle(page, 'alpha pending', 'first isolated result'); + await responseIs(page, 0, 'first isolated result'); + await pending(page, 1); + return await waitForSidebarChange(page, bothPending); + } finally { + await page.close(); + } +} + +async function capture(page, name) { + fs.mkdirSync(auditDir, { recursive: true }); + await page.screenshot({ path: path.join(auditDir, `${name}.png`), fullPage: true }); +} + +(async () => { + const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] }); + try { + const page = await open(browser); + const placeholder = locator(page, 'new-block-placeholder'); + assert.equal(await locator(page, 'prompt-input').count(), 1); + assert.equal(await placeholder.isVisible(), false, 'initial placeholder must be hidden'); + await locator(page, 'send-button').first().click(); + assert.equal(await page.evaluate(() => window.__requests.length), 0, 'empty send must be ignored'); + await locator(page, 'prompt-input').first().fill('draft only'); + assert.equal(await placeholder.isVisible(), false, 'draft alone must not unlock a block'); + await capture(page, '01-draft'); + + const initialSidebar = await sidebarFrame(page); + await send(page, 0, 'alpha pending'); + await pending(page, 0); + const firstPending = await waitForSidebarChange(page, initialSidebar); + assert.equal(await placeholder.filter({ visible: true }).count(), 1); + await placeholder.click(); + const newDraft = await waitForSidebarChange(page, firstPending); + assert.equal(await locator(page, 'prompt-input').count(), 2); + assert(await locator(page, 'prompt-input').nth(1).evaluate(el => el === document.activeElement)); + await locator(page, 'prompt-input').nth(1).fill('beta draft'); + assert.equal(await placeholder.isVisible(), false, 'a new draft blocks the next placeholder'); + await send(page, 1, 'beta pending'); + await pending(page, 0); + await pending(page, 1); + assert.equal(await placeholder.filter({ visible: true }).count(), 1); + assert.equal(await page.evaluate(() => new Set(window.__requests.map(r => r.id)).size), 2, + 'concurrent blocks must have distinct IDs'); + await capture(page, '02-concurrent'); + + const bothPending = await waitForSidebarChange(page, newDraft); + await settle(page, 'beta pending', 'second isolated result'); + await responseIs(page, 1, 'second isolated result'); + await pending(page, 0); + const secondComplete = await waitForSidebarChange(page, bothPending); + const firstComplete = await completeFirstBlockSidebar(browser); + // Both states have one result and one pending request. A sidebar showing + // only totals would look the same without distinguishing the two blocks. + assert(!firstComplete.equals(secondComplete) && !firstComplete.equals(bothPending), + 'sidebar must distinguish which of the two blocks completed'); + await placeholder.click(); + const draft = locator(page, 'prompt-input').nth(2); + await draft.fill('third block: edited but unsent'); + await settle(page, 'alpha pending', 'first isolated result'); + await responseIs(page, 0, 'first isolated result'); + await responseIs(page, 1, 'second isolated result'); + assert(await draft.evaluate(el => el === document.activeElement), + 'completion in another block must not steal focus'); + assert.equal(await draft.inputValue(), 'third block: edited but unsent', + 'completion in another block must preserve the unsent draft'); + assert.equal(await page.evaluate(() => window.__requests.length), 2, + 'completion in another block must not submit the draft'); + assert.equal(await placeholder.isVisible(), false, 'unsent draft must still block the new-block control'); + await capture(page, '03-out-of-order-completion'); + + await send(page, 2, 'gamma pending'); + await settle(page, 'gamma pending', 'third isolated result'); + await responseIs(page, 2, 'third isolated result'); + await send(page, 0, 'request that fails'); + await assertSameBlockId(page, 'alpha pending', 'request that fails'); + await pending(page, 0); + await settle(page, 'request that fails', 'offline failure', true); + await page.waitForFunction(() => /fail|error|失败|错误/i.test( + document.querySelector('[data-testid="response"]').textContent)); + await responseIs(page, 1, 'second isolated result'); + assert(await placeholder.isVisible(), 'failure must not permanently block creation'); + await capture(page, '04-local-failure'); + + await send(page, 0, 'retry in original block'); + await assertSameBlockId(page, 'alpha pending', 'retry in original block'); + await pending(page, 0); + await settle(page, 'retry in original block', 'recovered result'); + await responseIs(page, 1, 'second isolated result'); + assert.equal(await locator(page, 'prompt-response-block').count(), 3, 'retry must reuse the block'); + await responseIs(page, 0, 'recovered result'); + await placeholder.click(); + assert.equal(await locator(page, 'prompt-response-block').count(), 4); + assert.equal(await placeholder.isVisible(), false); + await page.setViewportSize({ width: 375, height: 812 }); + assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), + 'narrow viewport must not overflow horizontally'); + await capture(page, '05-mobile-retry-and-new-block'); + await page.close(); + console.log('independent lifecycle, stable IDs, draft retention, per-block sidebar status, and responsive cases passed'); + } finally { + await browser.close(); + } +})().catch(error => { console.error(error); process.exit(1); }); diff --git a/task_009/tests/validate_semantics.js b/task_009/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_009/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_009/tests/validate_ui_behavior.js b/task_009/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..131ef4a43d68ac8656620862949c71102c22388a --- /dev/null +++ b/task_009/tests/validate_ui_behavior.js @@ -0,0 +1,88 @@ +const assert = require('node:assert/strict'); +const path = require('node:path'); +const { pathToFileURL } = require('node:url'); +const { chromium } = require('playwright'); + +async function findScrollHost(page) { + return page.evaluateHandle(() => { + const blocks = document.querySelectorAll('[data-testid="prompt-response-block"]'); + for (let parent = blocks[blocks.length - 1].parentElement; parent; parent = parent.parentElement) { + if (parent.scrollHeight - parent.clientHeight <= 4) continue; + const overflow = getComputedStyle(parent).overflowY; + if (parent === document.scrollingElement || overflow !== 'visible') return parent; + } + return null; + }); +} + +async function checkOverflowScrolling(page) { + await page.setViewportSize({width: 1200, height: 420}); + await page.evaluate(() => window.__setMockGenerate(prompt => Promise.resolve('result: ' + prompt))); + const placeholder = page.getByTestId('new-block-placeholder'); + for (let index = 0; index < 20; index++) { + await page.getByTestId('prompt-input').nth(index).fill('scroll request ' + index); + await page.getByTestId('send-button').nth(index).click(); + await placeholder.click(); + await page.getByTestId('prompt-response-block').nth(index + 1).waitFor({state: 'attached'}); + const candidate = await findScrollHost(page); + try { + const host = candidate.asElement(); + if (!host) continue; + const start = await host.evaluate(element => { + const root = element === document.scrollingElement; + const rect = (root ? document.querySelector('[data-testid="content"]') : element).getBoundingClientRect(); + return { + x: (Math.max(0, rect.left) + Math.min(innerWidth, rect.right)) / 2, + y: (Math.max(0, rect.top) + Math.min(innerHeight, rect.bottom)) / 2, + scrollTop: element.scrollTop, + }; + }); + await page.mouse.move(start.x, start.y); + await page.mouse.wheel(0, start.scrollTop > 2 ? -1000 : 1000); + await page.waitForFunction(({element, initial}) => Math.abs(element.scrollTop - initial) > 1, + {element: host, initial: start.scrollTop}, {timeout: 5000}); + return true; + } finally { + await candidate.dispose(); + } + } + return false; +} + +(async () => { + const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] }); + try { + const page = await browser.newPage({ viewport: { width: 1200, height: 800 } }); + await page.route(/^https?:/, route => route.abort()); + await page.goto(pathToFileURL(path.resolve('index.html')).href); + const dimensions = await page.evaluate(() => { + const sidebar = document.querySelector('[data-testid="sidebar"]'); + const content = document.querySelector('[data-testid="content"]'); + const styles = getComputedStyle(content); + const sidebarBox = sidebar.getBoundingClientRect(); + const contentBox = content.getBoundingClientRect(); + return { + sidebar: sidebarBox.width, + content: contentBox.width, + gap: contentBox.left - sidebarBox.right, + extraRight: document.documentElement.clientWidth - contentBox.right - sidebarBox.left, + padding: [parseFloat(styles.paddingLeft), parseFloat(styles.paddingRight)], + }; + }); + assert(Math.abs(dimensions.sidebar - 240) <= 5, 'desktop sidebar must be about 240px'); + assert(dimensions.content > 0 && dimensions.content <= 905, 'content must render within max 900px'); + assert(dimensions.padding.every(value => value >= 15), 'content needs horizontal padding'); + // When a max-width panel is centered in the remaining space, the extra + // margin on its left is balanced by the equivalent right margin. + const nearGutter = gap => Math.abs(gap - 32) <= 2; + assert(nearGutter(dimensions.gap) || + dimensions.extraRight > 0 && nearGutter(dimensions.gap - dimensions.extraRight), + 'desktop layout needs a 32px sidebar gutter outside any centered surplus margin'); + + const overflowTested = await checkOverflowScrolling(page); + console.log('desktop layout and sidebar gutter passed'); + console.log(overflowTested ? 'wheel scrolled the overflowing workspace' : 'generated blocks fit without vertical overflow'); + } finally { + await browser.close(); + } +})().catch(error => { console.error(error); process.exit(1); }); diff --git a/task_010/acceptance_checklist.json b/task_010/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..a78119c89a884975820c871539c42ae6e51467bc --- /dev/null +++ b/task_010/acceptance_checklist.json @@ -0,0 +1,28 @@ +{ + "task_id": 11, + "category": "application_development", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Implements the requested domain workflow end to end.", + "Includes maintainable separation of concerns and meaningful tests when the task asks for them.", + "Configurable offline mock LLM request uses API_KEY/BASE_URL/MODEL_NAME settings without external network.", + "Normal generation removes old fake title/content and streams prompt-relevant output.", + "Malformed `0:\"...\"` chunk frames are parsed into readable content instead of leaking raw prefixes.", + "Timeout/no-response paths end in a visible failure state and do not stay loading." + ], + "input_assets": [ + "index.html", + ".env.example", + "config.js" + ], + "expected_outputs": [], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns.", + "A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "v2_notes": "Strengthened using sampled non-from-scratch/multi-turn trajectory signals.", + "repair_revision": "2026-09-29" +} diff --git a/task_010/environment/Dockerfile b/task_010/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_010/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_010/environment/code/.env.example b/task_010/environment/code/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..7f8a679dcc381ac5e040ba437e675025d3a3612d --- /dev/null +++ b/task_010/environment/code/.env.example @@ -0,0 +1,3 @@ +API_KEY=mock-key +BASE_URL=http://local-mock +MODEL_NAME=mock-model diff --git a/task_010/environment/code/config.js b/task_010/environment/code/config.js new file mode 100644 index 0000000000000000000000000000000000000000..36ca282119c4f2a28503bee49a1489023126547b --- /dev/null +++ b/task_010/environment/code/config.js @@ -0,0 +1,5 @@ +window.aiConfig = { + key: "", + baseurl: "", + modelname: "" +}; diff --git a/task_010/environment/code/index.html b/task_010/environment/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..f3016e252f48f3ccb2643e2ed462e49468cbbf9d --- /dev/null +++ b/task_010/environment/code/index.html @@ -0,0 +1,29 @@ + + + + + Prompt Response API Fixture + + + + +
    + + +

    Build a todo app

    + Develop a cross-platform mobile app with fake content. +

    idle

    +
    + + + diff --git a/task_010/environment/docker-compose.yaml b/task_010/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_010/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_010/instruction.md b/task_010/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7619cde4a61c37e2edd868ba7c3e3a31746e5891 --- /dev/null +++ b/task_010/instruction.md @@ -0,0 +1,22 @@ +# Configurable offline title and response streaming + +Extend the supplied `index.html` and `config.js` to generate a title and streamed response based on the current prompt. Replace the hardcoded sample title and response. The page must open directly from the project root and use a local request layer, with no real API call or extra package installation. + +## Configuration and request lifecycle + +Keep a placeholder-only `.env.example` with `API_KEY`, `BASE_URL`, and `MODEL_NAME`. The local request layer reads their counterparts `key`, `baseurl`, and `modelname` on `window.aiConfig`. Reject a missing or whitespace-only value in any field with a visible failure state. Restoring the value allows a new request. Never display a configured key or include it in errors. + +On Send, show loading text in the title area (“Loading” or “加载中”) and text or a visible loading indicator with `aria-busy="true"` in the response area. Generate a single title for this prompt, then show meaningful partial response text before the complete response. Both outputs must depend on the input rather than reuse fixed text or merely echo the prompt. Within five seconds, show “Complete” or “完成” on success and a clear error or timeout on failure (for example “Error” / “错误” or “Timeout” / “超时”). + +## Local stream interface + +- Preserve `data-testid` values `prompt-input`, `send-button`, `generated-title`, `generated-content` and `generation-status`. Use clear English or Chinese statuses for loading, completion and failure. +- `window.__setMockMode(mode)` accepts `'normal'`, `'timeout'` and `'malformed'`. Timeout ends in a visible failure; normal mode supports recovery. In malformed mode, still decode valid frames such as `0:"text"` and complete successfully. +- `window.__setMockChunks(chunks)` replaces the mock input with an array of complete frame strings or plain text; `null` restores the default. Decode a framed JSON string with its quotes, backslashes and newlines and concatenate text in arrival order without frame prefixes. An invalid frame can produce a clear error or be skipped while valid text is processed. Reassembly of arbitrary network splits is not required. + +## Acceptance Checklist + +- The offline output no longer contains the old canned content. Different prompts produce different, relevant titles and responses. +- Both output areas show loading; visible content grows through an intermediate state before completion. +- Each configuration field is required independently. Restoring a missing value or switching back from timeout permits a new successful request within the time bound without exposing keys. +- Complete frames and plain fragments combine in arrival order, preserving escaped characters and removing wrapper markup. diff --git a/task_010/provenance/restoration_notes.md b/task_010/provenance/restoration_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..5b5b6397bdd44ead44185fd76ec7817892a58e47 --- /dev/null +++ b/task_010/provenance/restoration_notes.md @@ -0,0 +1,11 @@ +# Restoration Notes for task_011 + +- 官方轨迹形态:existing prompt app; replace fake title/content with configurable LLM request flow +- v1 主要损失:v1 压缩为单轮 mock 请求,未覆盖 timeout、异常 chunk 格式和无响应恢复。 +- v2 改动:保留 closed mock,新增 timeout/malformed stream/no response 恢复契约和测试。 + +## 代表性用户轮次 + +1. 开始做新需求:prompt 发送后 title/content 不再是假数据,配置 key/baseurl/modelname,经 Vercel AI SDK 请求并流式展示。 +2. .env.local/API 配置补充。 +3. Next/font 缺 autoprefixer、API timeout、streaming 格式错误、屏幕无输出等多轮反馈。 diff --git a/task_010/provenance/user_turns.json b/task_010/provenance/user_turns.json new file mode 100644 index 0000000000000000000000000000000000000000..f55a80c12c925334fdacc1d3c653be7324c14ab1 --- /dev/null +++ b/task_010/provenance/user_turns.json @@ -0,0 +1,16 @@ +{ + "task_id": 11, + "source": "HF CC-Bench-trajectories sampled metadata; public Dataset Server may differ from local GLM-4.6 source table", + "trajectory_type": "multi-turn", + "data": { + "category": "application_development", + "official_task_shape": "existing prompt app; replace fake title/content with configurable LLM request flow", + "representative_user_turns": [ + "开始做新需求:prompt 发送后 title/content 不再是假数据,配置 key/baseurl/modelname,经 Vercel AI SDK 请求并流式展示。", + ".env.local/API 配置补充。", + "Next/font 缺 autoprefixer、API timeout、streaming 格式错误、屏幕无输出等多轮反馈。" + ], + "loss_in_v1": "v1 压缩为单轮 mock 请求,未覆盖 timeout、异常 chunk 格式和无响应恢复。", + "v2_change": "保留 closed mock,新增 timeout/malformed stream/no response 恢复契约和测试。" + } +} diff --git a/task_010/quality_notes.md b/task_010/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..8da9186e00ac25a6fdb20000e9bb7861ad049825 --- /dev/null +++ b/task_010/quality_notes.md @@ -0,0 +1,4 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. \ No newline at end of file diff --git a/task_010/solution/README.md b/task_010/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_010/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_010/solution/code/.env.example b/task_010/solution/code/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..7f8a679dcc381ac5e040ba437e675025d3a3612d --- /dev/null +++ b/task_010/solution/code/.env.example @@ -0,0 +1,3 @@ +API_KEY=mock-key +BASE_URL=http://local-mock +MODEL_NAME=mock-model diff --git a/task_010/solution/code/config.js b/task_010/solution/code/config.js new file mode 100644 index 0000000000000000000000000000000000000000..c5b34b7d322689b9a1d8ffe29605f4898889079c --- /dev/null +++ b/task_010/solution/code/config.js @@ -0,0 +1,5 @@ +window.aiConfig = { + key: "mock-key", + baseurl: "http://local-mock", + modelname: "mock-model" +}; diff --git a/task_010/solution/code/index.html b/task_010/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..9d00281bee31ea5f6ba427a1e4c998415382649b --- /dev/null +++ b/task_010/solution/code/index.html @@ -0,0 +1,104 @@ + + + + + Prompt Response API Solution v2 + + + + +
    + + +

    + +

    idle

    +
    + + + diff --git a/task_010/solution/solve.sh b/task_010/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_010/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_010/task.toml b/task_010/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_010/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_010/task_meta.json b/task_010/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..e4406d7e72ba2c4ae18835f10d254310bf1d481c --- /dev/null +++ b/task_010/task_meta.json @@ -0,0 +1,33 @@ +{ + "task_id": 11, + "task_category": "application_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 10, + "language": "javascript", + "tool_files_from_selected_trace": [ + ".env.example", + ".env.local", + "AIContentArea.tsx", + "IMPLEMENTATION.md", + "LayoutWindow.tsx", + "MainContentArea.tsx", + "PromptResponseBlock.tsx", + "SETUP.md", + "ai-state-machine.ts", + "package.json", + "page-5-generating.json", + "page.tsx", + "route.ts", + "test-api.sh" + ], + "input_assets": [ + "index.html", + ".env.example", + "config.js" + ], + "expected_outputs": [], + "source_row_id": 66, + "repair_revision": "2026-09-29", + "instruction_sha256": "3ed9f82a4457330973d575a32fc64629132e111fff0da196ddfd632679b7e7fb" +} diff --git a/task_010/tests/_shared/contract_checker.js b/task_010/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_010/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_010/tests/_shared/static_enhancer.sh b/task_010/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_010/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_010/tests/enhancement_cases.json b/task_010/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..d79d72283f4390af5fbdaeec4302a94cc88e8433 --- /dev/null +++ b/task_010/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","instruction_evidence":"设计一个 prompt,产生对话的标题,填充在 title 里;content 变成真的","validator":"validate_enhanced_cases.js","behavior":"两个不同提示产生不同完成态,且旧假数据不再出现"}, + {"case_id":"ENHANCED_CASE_2","instruction_evidence":"发送、看到 UI变化、title 和 content 区域加载中状态、title 变成真的、content 变成真的(流式加载中)","validator":"validate_enhanced_cases.js","behavior":"按顺序观察加载状态、部分内容增长和最终完成"}, + {"case_id":"ENHANCED_CASE_3","instruction_evidence":"v2 通过 `window.__setMockMode(mode)` 增加确定性封闭测试,覆盖 API timeout 恢复","validator":"validate_enhanced_cases.js","behavior":"超时后退出loading并允许后续正常请求成功完成"} +] diff --git a/task_010/tests/test.sh b/task_010/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ab2150eb79f6f15b53d20b21738b84bbe0d8003 --- /dev/null +++ b/task_010/tests/test.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_ui_behavior.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_010/tests/validate_aaav_dynamic.js b/task_010/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..10901eb46811a33017975008f81dffe421b5acaf --- /dev/null +++ b/task_010/tests/validate_aaav_dynamic.js @@ -0,0 +1,148 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 11; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_010/tests/validate_browser_smoke.js b/task_010/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_010/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_010/tests/validate_enhanced_cases.js b/task_010/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..ca0671cb51fa9b90b1444c1e298905fec21a4269 --- /dev/null +++ b/task_010/tests/validate_enhanced_cases.js @@ -0,0 +1,149 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { pathToFileURL } = require('node:url'); +const { chromium } = require('playwright'); +const complete = /complete|done|finished|完成/i; +const failed = /fail|error|timeout|失败|错误|超时/i; +const loading = /\bloading\b|加载中/i; + +function withoutEcho(text, prompt) { + return text.toLowerCase().replaceAll(prompt.toLowerCase(), '') + .replace(/\b(?:request|reply|response|result|title)\s*#?\s*\d+\b/gi, ' ') + .replace(/\b[a-z]\b/gi, ' ') + .replace(/[^\p{L}\p{M}\p{N}]+/gu, ' ').trim(); +} + +async function state(page) { + const result = await page.evaluate(() => { + const node = name => document.querySelector(`[data-testid="${name}"]`); + const title = node('generated-title'), reply = node('generated-content'), status = node('generation-status'); + const busy = [reply, ...reply.querySelectorAll('[aria-busy="true"]')].some(element => + element.getAttribute('aria-busy') === 'true' && element.getClientRects().length); + return {title: title.innerText.trim(), content: reply.textContent.trim(), visibleContent: reply.innerText.trim(), status: status.innerText.trim(), busy, + leak: document.body.innerText.includes('ux-audit-private-48cf83')}; + }); + assert(!result.leak, 'configuration key must not be rendered, including in error states'); + return result; +} + +async function submit(page, prompt) { + await page.getByTestId('prompt-input').fill(prompt); + await page.getByTestId('send-button').click(); +} + +async function untilTerminal(page) { + // Time is controlled, but the implementation chooses its own chunk intervals. + for (let elapsed = 0; elapsed <= 5000; elapsed += 10) { + const current = await state(page); + if (complete.test(current.status) || failed.test(current.status)) return current; + await page.clock.runFor(10); + } + throw new Error('request did not reach a terminal state within the public 5s bound'); +} + +async function capture(page, name) { + const dir = '/logs/verifier/visual'; + fs.mkdirSync(dir, { recursive: true }); + await page.screenshot({ path: path.join(dir, `${name}.png`), fullPage: true }); +} + +(async () => { + const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] }); + try { + const page = await browser.newPage({ viewport: { width: 1000, height: 700 } }); + await page.route(/^https?:/, route => route.abort()); + await page.clock.install({ time: new Date('2026-01-01T00:00:00Z') }); + await page.goto(pathToFileURL(path.resolve('index.html')).href); + await page.clock.pauseAt(new Date('2026-01-01T00:01:00Z')); + await page.evaluate(() => { window.aiConfig.key = 'ux-audit-private-48cf83'; }); + const firstPrompt = 'Amber lighthouse restoration: recommend practical next steps'; + const secondPrompt = 'Violet submarine inspection: recommend practical next steps'; + await submit(page, firstPrompt); + let initial; + let elapsed = 0; + for (; elapsed <= 5000; elapsed += 10) { + const current = await state(page); + if (loading.test(current.title) && (loading.test(current.content) || current.busy)) { + initial = current; + break; + } + if (complete.test(current.status) || failed.test(current.status)) break; + await page.clock.runFor(10); + } + assert(initial, 'both output areas need a visible loading state'); + await capture(page, '01-loading'); + const contents = new Set(); + let first; + for (; elapsed <= 5000; elapsed += 10) { + const current = await state(page); + if (complete.test(current.status)) { first = current; break; } + assert(!failed.test(current.status), 'normal stream must not fail'); + if (current.visibleContent && current.visibleContent !== initial.visibleContent) { + if (!contents.size) await capture(page, '02-intermediate'); + contents.add(current.visibleContent); + } + await page.clock.runFor(10); + } + assert(first, 'normal stream must complete within 5s'); + assert(first.title && first.content, 'both generated outputs must be non-empty'); + assert([...contents].some(content => content !== first.visibleContent && first.visibleContent.includes(content)), + 'content must visibly grow through an intermediate state before completion'); + await capture(page, '03-complete'); + await submit(page, secondPrompt); + const second = await untilTerminal(page); + assert(complete.test(second.status)); + for (const field of ['title', 'content']) { + const original = withoutEcho(first[field], firstPrompt); + const changed = withoutEcho(second[field], secondPrompt); + assert(original && changed && original !== changed, + `${field} must adapt to the prompt beyond quoting it or changing a counter`); + } + + const thirdPrompt = 'Amber lighthouse restoration: draft a risk register and mitigations'; + await submit(page, thirdPrompt); + const third = await untilTerminal(page); + assert(complete.test(third.status), 'follow-up request on the same subject must complete'); + assert.notEqual(withoutEcho(third.content, thirdPrompt), withoutEcho(first.content, firstPrompt), + 'different requests about the same subject need different response content'); + + for (const field of ['key', 'baseurl', 'modelname']) { + await page.evaluate(field => { window.__savedConfig = {...window.aiConfig}; window.aiConfig[field] = ' '; }, field); + await submit(page, `missing ${field}`); + assert(failed.test((await untilTerminal(page)).status), `missing ${field} must fail`); + await page.evaluate(() => Object.assign(window.aiConfig, window.__savedConfig)); + await submit(page, `recovered ${field}`); + assert(complete.test((await untilTerminal(page)).status), `${field} recovery must succeed`); + } + await page.evaluate(() => window.__setMockMode('timeout')); + await submit(page, 'timeout case'); + assert(failed.test((await untilTerminal(page)).status)); + await capture(page, '04-timeout'); + await page.evaluate(() => window.__setMockMode('normal')); + await submit(page, 'recovered after timeout'); + assert(complete.test((await untilTerminal(page)).status)); + + const text = '中文 "quoted"\nnew line \\ path'; + await page.evaluate(text => window.__setMockChunks(['0:' + JSON.stringify(text), ' and plain tail']), text); + await submit(page, 'frame parsing'); + const parsed = await untilTerminal(page); + assert(complete.test(parsed.status)); + assert([parsed.content, parsed.visibleContent].includes(text + ' and plain tail'), + 'frame escaping and concatenation must preserve text'); + await capture(page, '05-decoded-frames'); + const valid = 'Recovered text after an invalid frame'; + await page.evaluate(text => window.__setMockChunks(['0:"unterminated', '0:' + JSON.stringify(text)]), valid); + await submit(page, 'test mixed valid and invalid frames'); + const mixed = await untilTerminal(page); + if (complete.test(mixed.status)) { + assert.equal(mixed.content, valid, 'skipping an invalid frame must preserve only the valid response'); + } else { + assert(failed.test(mixed.status), 'an invalid frame must be skipped or terminate with a visible error'); + } + const key = await page.evaluate(() => window.aiConfig.key); + assert(!(await page.locator('body').innerText()).includes(key), 'configuration key must not be rendered'); + console.log('variable timing, real intermediate content, all config fields, timeout recovery and frame parsing passed'); + } finally { + await browser.close(); + } +})().catch(error => { console.error(error); process.exit(1); }); diff --git a/task_010/tests/validate_semantics.js b/task_010/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_010/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_010/tests/validate_ui_behavior.js b/task_010/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..7044318704ce385790b614c80ca0c7b2fbcc73c8 --- /dev/null +++ b/task_010/tests/validate_ui_behavior.js @@ -0,0 +1,42 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +(async () => { + const root = process.cwd(); + for (const rel of ['.env.example', 'config.js']) if (!fs.existsSync(path.join(root, rel))) throw new Error(`missing ${rel}`); + const example = fs.readFileSync(path.join(root, '.env.example'), 'utf8'); + for (const setting of ['API_KEY', 'BASE_URL', 'MODEL_NAME']) { + if (!new RegExp(`^\\s*(?:export\\s+)?${setting}\\s*=`, 'm').test(example)) { + throw new Error(`missing setting ${setting} in .env.example`); + } + } + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage(); + await page.goto(pathToFileURL(path.join(root, 'index.html')).href, { waitUntil: 'domcontentloaded' }); + if (await page.evaluate(() => typeof window.__setMockMode) !== 'function') throw new Error('window.__setMockMode must be a function for deterministic failure tests'); + await page.locator('[data-testid="prompt-input"]').fill('Design a concise note taking app'); + await page.locator('[data-testid="send-button"]').click(); + await page.waitForFunction(() => /complete|done|finished|完成|已完成/i.test(document.querySelector('[data-testid="generation-status"]')?.textContent || ''), null, { timeout: 5000 }); + const title = (await page.locator('[data-testid="generated-title"]').textContent()) || ''; + const content = (await page.locator('[data-testid="generated-content"]').textContent()) || ''; + if (!title.trim() || !content.trim()) throw new Error('the normal request must display both outputs'); + if (/Build a todo app|Develop a cross-platform mobile app/i.test(title + ' ' + content)) { + throw new Error('rendered output still contains the old fixed sample text'); + } + await page.evaluate(() => window.__setMockMode('malformed')); + await page.locator('[data-testid="prompt-input"]').fill('parse chunked stream'); + await page.locator('[data-testid="send-button"]').click(); + await page.waitForFunction(() => /complete|完成|已完成/i.test(document.querySelector('[data-testid="generation-status"]')?.textContent || ''), null, { timeout: 5000 }); + const parsed = (await page.locator('[data-testid="generated-content"]').textContent()) || ''; + // The specific literal (你好世界) is not disclosed in the instruction or fixture, so only + // require that malformed 0:"..." frames are parsed into NON-EMPTY readable content, and + // that the raw frame prefixes do not leak into the UI. + if (parsed.replace(/\s/g, '').length === 0) throw new Error('malformed 0:"..." chunks should be parsed into non-empty readable content'); + if (/\d+:"/.test(parsed)) throw new Error('raw stream frame prefixes should not leak to UI'); + await page.evaluate(() => window.__setMockMode('timeout')); + await page.locator('[data-testid="prompt-input"]').fill('trigger timeout'); + await page.locator('[data-testid="send-button"]').click(); + await page.waitForFunction(() => /timeout|failed|error|超时|失败|错误|异常/i.test(document.querySelector('[data-testid="generation-status"]')?.textContent || ''), null, { timeout: 5000 }); + await browser.close(); +})().catch(err => { console.error(err && err.stack || err); process.exit(1); }); diff --git a/task_011/acceptance_checklist.json b/task_011/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..ba44b7cd16bebc9184089fb85c1ca2394ce46c68 --- /dev/null +++ b/task_011/acceptance_checklist.json @@ -0,0 +1,26 @@ +{ + "task_id": 12, + "category": "application_development", + "language": "javascript", + "acceptance_items": [ + "空 prompt 不创建请求", + "真实观察 loading、非空中间 chunk 和 complete", + "两次请求透传不同配置且旧记录不可变", + "历史可见、密钥不明文显示、清空后记录和列表一致", + "浏览器直接打开且不发外部请求" + ], + "input_assets": [ + "index.html", + "config.js", + ".env.example" + ], + "expected_outputs": [ + "index.html", + "app.js" + ], + "risk_notes": [ + "离线请求审计台:配置快照、流式 chunks、独立历史与清空,不再重复 Task 11 的标题和超时题。" + ], + "verifier_style": "deterministic browser behavior", + "repair_revision": "2026-09-30" +} diff --git a/task_011/environment/Dockerfile b/task_011/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_011/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_011/environment/code/.env.example b/task_011/environment/code/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..7f8a679dcc381ac5e040ba437e675025d3a3612d --- /dev/null +++ b/task_011/environment/code/.env.example @@ -0,0 +1,3 @@ +API_KEY=mock-key +BASE_URL=http://local-mock +MODEL_NAME=mock-model diff --git a/task_011/environment/code/config.js b/task_011/environment/code/config.js new file mode 100644 index 0000000000000000000000000000000000000000..36ca282119c4f2a28503bee49a1489023126547b --- /dev/null +++ b/task_011/environment/code/config.js @@ -0,0 +1,5 @@ +window.aiConfig = { + key: "", + baseurl: "", + modelname: "" +}; diff --git a/task_011/environment/code/index.html b/task_011/environment/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..f3016e252f48f3ccb2643e2ed462e49468cbbf9d --- /dev/null +++ b/task_011/environment/code/index.html @@ -0,0 +1,29 @@ + + + + + Prompt Response API Fixture + + + + +
    + + +

    Build a todo app

    + Develop a cross-platform mobile app with fake content. +

    idle

    +
    + + + diff --git a/task_011/environment/docker-compose.yaml b/task_011/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_011/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_011/instruction.md b/task_011/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1fbd341ad6c112522dae4f1cdf6c7e3b05c6793f --- /dev/null +++ b/task_011/instruction.md @@ -0,0 +1,19 @@ +# Offline request audit console + +Replace the fixed response in `/app/index.html` with a request audit console that records configuration snapshots, streaming output and request history. The page opens directly using `file://` and needs no network or new packages. Title generation, timeouts and malformed-frame handling are out of scope. + +## Request lifecycle + +Provide a prompt field and editable key, base URL and model settings. Initial values may come from `window.aiConfig` in `/app/config.js`; include only placeholders in `.env.example`. Sending a nonblank prompt starts a local mock request using a snapshot of the current values. Blank prompts do not create a request. + +Append each request to `window.__mockRequests` as `{id, key, baseURL, model, prompt, chunks, status}`. IDs are increasing integers unique within the page, including after clearing history. Transition from `loading` to `complete`. Deliver at least two nonempty text fragments asynchronously so loading and intermediate content are visible; store fragments in arrival order and display their concatenation. Completed content varies with the prompt. + +Show the first partial response within three seconds of sending; complete the local stream promptly (within four seconds of the partial response, or within four seconds of sending for subsequent requests). Keep each request's prompt, model, status and completion content visible in its own history item, ordered oldest first. Earlier records must not change when settings or the prompt are edited. Never display the key in the history. A Clear History button removes all visible items and their underlying records. + +Preserve `data-testid` hooks `prompt-input`, `config-key`, `config-baseurl`, `config-modelname`, `send-button`, `clear-button`, `request-status`, `active-content`, and `request-history`; use `request-item` for each entry. + +## Acceptance Checklist + +- Blank sends do nothing. Valid sends show visible loading, intermediate streamed content and a completed concatenated response without making network requests. +- Sending with changed settings keeps two independent, correctly ordered request snapshots and visible history items without key leakage. +- Clearing history empties the UI and records. A later request starts a new history without reusing an ID or restoring cleared entries. diff --git a/task_011/quality_notes.md b/task_011/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..79bc7d5745268818f3e6243fec4ef037134aca12 --- /dev/null +++ b/task_011/quality_notes.md @@ -0,0 +1,3 @@ +# Quality Notes + +- 离线请求审计台:配置快照、流式 chunks、独立历史与清空,不再重复 Task 11 的标题和超时题。 diff --git a/task_011/solution/README.md b/task_011/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..05588aa324b74145241922b6c87fc0770bcd1edc --- /dev/null +++ b/task_011/solution/README.md @@ -0,0 +1,3 @@ +# Reference solution + +The oracle copies `solution/code/` into `/app`. It was checked against the task-specific verifier; the starter scores zero. diff --git a/task_011/solution/code/.env.example b/task_011/solution/code/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..7f8a679dcc381ac5e040ba437e675025d3a3612d --- /dev/null +++ b/task_011/solution/code/.env.example @@ -0,0 +1,3 @@ +API_KEY=mock-key +BASE_URL=http://local-mock +MODEL_NAME=mock-model diff --git a/task_011/solution/code/app.js b/task_011/solution/code/app.js new file mode 100644 index 0000000000000000000000000000000000000000..c9f2b6f9f4f61566f03716a581c0f38395b378ac --- /dev/null +++ b/task_011/solution/code/app.js @@ -0,0 +1,80 @@ +(() => { + const pick = name => document.querySelector(`[data-testid="${name}"]`); + const promptInput = pick('prompt-input'); + const keyInput = pick('config-key'); + const baseInput = pick('config-baseurl'); + const modelInput = pick('config-modelname'); + const sendButton = pick('send-button'); + const clearButton = pick('clear-button'); + const status = pick('request-status'); + const content = pick('active-content'); + const history = pick('request-history'); + const config = window.aiConfig || {}; + keyInput.value = config.key || config.API_KEY || ''; + baseInput.value = config.baseurl || config.BASE_URL || ''; + modelInput.value = config.modelname || config.MODEL_NAME || ''; + + const requests = []; + window.__mockRequests = requests; + let nextId = 1; + let busy = false; + const pause = ms => new Promise(resolve => setTimeout(resolve, ms)); + + function renderHistory() { + history.replaceChildren(); + for (const request of requests) { + const item = document.createElement('li'); + item.dataset.testid = 'request-item'; + const meta = document.createElement('div'); + meta.className = 'meta'; + meta.textContent = `#${request.id} · ${request.model} · ${request.status} · ${request.baseURL}`; + const prompt = document.createElement('div'); + prompt.textContent = `Prompt: ${request.prompt}`; + const body = document.createElement('div'); + body.textContent = request.chunks.join(''); + item.append(meta, prompt, body); + history.append(item); + } + } + + sendButton.addEventListener('click', async () => { + const prompt = promptInput.value.trim(); + if (!prompt || busy) return; + busy = true; + sendButton.disabled = true; + clearButton.disabled = true; + const request = { + id: nextId++, key: keyInput.value, baseURL: baseInput.value, + model: modelInput.value, prompt, chunks: [], status: 'loading' + }; + requests.push(request); + status.textContent = 'loading'; + content.textContent = ''; + renderHistory(); + const chunks = [ + `Request ${request.id}: ${prompt}.`, + `Model ${request.model} generated an offline response.`, + `Endpoint used: ${request.baseURL}.` + ]; + for (const chunk of chunks) { + await pause(100); + request.chunks.push(chunk); + content.textContent = request.chunks.join(''); + renderHistory(); + } + request.status = 'complete'; + status.textContent = 'complete'; + renderHistory(); + busy = false; + sendButton.disabled = false; + clearButton.disabled = false; + }); + + clearButton.addEventListener('click', () => { + if (busy) return; + requests.length = 0; + history.replaceChildren(); + content.textContent = ''; + status.textContent = 'idle'; + }); +})(); diff --git a/task_011/solution/code/config.js b/task_011/solution/code/config.js new file mode 100644 index 0000000000000000000000000000000000000000..3d1dafac1a02a5e83cfb3959f97def2ea71f1490 --- /dev/null +++ b/task_011/solution/code/config.js @@ -0,0 +1,8 @@ +window.aiConfig = { + API_KEY: "mock-key", + BASE_URL: "http://local-mock", + MODEL_NAME: "mock-model", + key: "mock-key", + baseurl: "http://local-mock", + modelname: "mock-model" +}; diff --git a/task_011/solution/code/index.html b/task_011/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..22f29e0b0679e5b102c330626965592f8c4caadd --- /dev/null +++ b/task_011/solution/code/index.html @@ -0,0 +1,35 @@ + + + + + + Offline Model Request Audit + + + + +
    +

    Offline Model Request Audit

    + + + + + + +

    idle

    + +

    Request History

    +
      +
      + + + diff --git a/task_011/solution/solve.sh b/task_011/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_011/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_011/task.toml b/task_011/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_011/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_011/task_meta.json b/task_011/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..7a8f7a12f8c10b565139132cd350bcdc4c2ce50c --- /dev/null +++ b/task_011/task_meta.json @@ -0,0 +1,39 @@ +{ + "task_id": 12, + "task_category": "application_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 7, + "language": "javascript", + "tool_files_from_selected_trace": [ + ".env.local", + ".env.template", + "IMPLEMENTATION-SUMMARY.md", + "MOONSHOT-SETUP-COMPLETE.md", + "PromptResponseBlock.tsx", + "README-AI-SETUP.md", + "ai-state-machine.ts", + "ai-utils.ts", + "package.json", + "postcss.config.js", + "route.ts", + "tailwind.config.ts", + "test-app-api.js", + "test-full-system.js", + "test-moonshot.js", + "test-title-api.js" + ], + "input_assets": [ + "index.html", + "config.js", + ".env.example" + ], + "expected_outputs": [ + "index.html", + "app.js" + ], + "source_row_id": 72, + "repair_revision": "2026-09-30", + "instruction_sha256": "540ba5c25a3abe63758cbf0eebad374bc29e5d6c6073109015edb1d6abb718b8", + "revision_note": "离线请求审计台:配置快照、流式 chunks、独立历史与清空,不再重复 Task 11 的标题和超时题。" +} diff --git a/task_011/tests/enhancement_cases.json b/task_011/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..d573a9c903ce6990df882c73b15c90a6751a435d --- /dev/null +++ b/task_011/tests/enhancement_cases.json @@ -0,0 +1,32 @@ +[ + { + "case_id": "blank_prompt", + "instruction_evidence": "空 prompt 不创建请求", + "validator": "validate_request_audit.js", + "behavior": "空 prompt 不创建请求" + }, + { + "case_id": "streaming", + "instruction_evidence": "真实观察 loading、非空中间 chunk 和 complete", + "validator": "validate_request_audit.js", + "behavior": "真实观察 loading、非空中间 chunk 和 complete" + }, + { + "case_id": "config_snapshot", + "instruction_evidence": "两次请求透传不同配置且旧记录不可变", + "validator": "validate_request_audit.js", + "behavior": "两次请求透传不同配置且旧记录不可变" + }, + { + "case_id": "history_clear", + "instruction_evidence": "历史可见、密钥不明文显示、清空后记录和列表一致", + "validator": "validate_request_audit.js", + "behavior": "历史可见、密钥不明文显示、清空后记录和列表一致" + }, + { + "case_id": "offline", + "instruction_evidence": "浏览器直接打开且不发外部请求", + "validator": "validate_request_audit.js", + "behavior": "浏览器直接打开且不发外部请求" + } +] diff --git a/task_011/tests/test.sh b/task_011/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a6fb772a99b51ed76f33b4965718778c52c2b16c --- /dev/null +++ b/task_011/tests/test.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -uo pipefail +mkdir -p /logs/verifier +echo 0 > /logs/verifier/reward.txt +cd /app || exit 1 +if timeout 90s node /tests/validate_request_audit.js; then + echo 1 > /logs/verifier/reward.txt +fi diff --git a/task_011/tests/validate_request_audit.js b/task_011/tests/validate_request_audit.js new file mode 100644 index 0000000000000000000000000000000000000000..8708743a0d53a7d2b4e8f1cba863dd48e5f00393 --- /dev/null +++ b/task_011/tests/validate_request_audit.js @@ -0,0 +1,104 @@ +const assert = require('node:assert/strict'); +const path = require('node:path'); +const {pathToFileURL} = require('node:url'); +const {chromium} = require('playwright'); +const fs = require('node:fs'); + +(async () => { + const browser = await chromium.launch({headless: true, args: ['--no-sandbox']}); + try { + const page = await browser.newPage(); + fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + const capture = name => page.screenshot({path: `/logs/verifier/visual-audit/${name}.png`, fullPage: true}); + const network = []; + await page.route(/^https?:/, route => {network.push(route.request().url()); return route.abort()}); + await page.goto(pathToFileURL(path.join('/app', 'index.html')).href); + const get = id => page.locator(`[data-testid="${id}"]`); + assert(await page.evaluate(() => Array.isArray(window.__mockRequests)), 'request audit array missing'); + await get('prompt-input').fill(' '); + await get('send-button').click(); + assert.equal(await page.evaluate(() => window.__mockRequests.length), 0, 'blank prompt created a request'); + + await get('config-key').fill('private-key-A'); + await get('config-baseurl').fill('https://offline-a.invalid/v1'); + await get('config-modelname').fill('model-A'); + await get('prompt-input').fill('first calendar brief'); + await get('send-button').click(); + await page.waitForFunction(() => { + const r = window.__mockRequests[0]; + return r && r.status === 'loading' && r.chunks.length > 0; + }, null, {timeout: 3000}); + const partial = await get('active-content').innerText(); + assert(partial.length > 0, 'no intermediate streamed content'); + assert(await get('request-status').isVisible(), 'request status is not visible'); + const loadingLabel = await get('request-status').innerText(); + assert(loadingLabel.trim(), 'loading state has no visible label'); + await capture('01-streaming'); + await page.waitForFunction(() => window.__mockRequests[0]?.status === 'complete', null, {timeout: 4000}); + const first = await page.evaluate(() => structuredClone(window.__mockRequests[0])); + assert(Number.isInteger(first.id), 'request id must be an integer'); + assert.deepEqual([first.key, first.baseURL, first.model, first.prompt], + ['private-key-A', 'https://offline-a.invalid/v1', 'model-A', 'first calendar brief']); + assert(first.chunks.length >= 2 && first.chunks.every(chunk => typeof chunk === 'string' && chunk.length > 0)); + assert.equal(await get('active-content').innerText(), first.chunks.join('')); + assert.notEqual(await get('request-status').innerText(), loadingLabel, 'visible status did not change on completion'); + const completionLabel = (await get('request-status').innerText()).trim().toLowerCase(); + assert.equal(await get('request-item').count(), 1); + assert(!(await get('request-history').innerText()).includes('private-key-A'), 'history leaks key'); + + await get('config-key').fill('private-key-B'); + await get('config-baseurl').fill('https://offline-b.invalid/v2'); + await get('config-modelname').fill('model-B'); + await get('prompt-input').fill('second recipe brief'); + await get('send-button').click(); + await page.waitForFunction(() => window.__mockRequests[1]?.status === 'complete', null, {timeout: 4000}); + const records = await page.evaluate(() => structuredClone(window.__mockRequests)); + assert.equal(records.length, 2); + assert.deepEqual(records[0], first, 'editing configuration mutated an older request'); + assert(Number.isInteger(records[1].id) && records[1].id > first.id, + 'request ids must increase without reuse'); + assert.deepEqual([records[1].key, records[1].baseURL, records[1].model, records[1].prompt], + ['private-key-B', 'https://offline-b.invalid/v2', 'model-B', 'second recipe brief']); + assert(records[1].chunks.length >= 2 && records[1].chunks.every(chunk => typeof chunk === 'string' && chunk.length > 0)); + assert.notEqual(records[1].chunks.join(''), first.chunks.join('')); + assert.equal(await get('request-item').count(), 2); + const visible = await get('request-history').innerText(); + for (const value of ['first calendar brief', 'second recipe brief', 'model-A', 'model-B', first.chunks.join(''), records[1].chunks.join('')]) + assert(visible.includes(value), `history missing ${value}`); + assert(!visible.includes('private-key-A') && !visible.includes('private-key-B'), 'history leaks key'); + for (let index = 0; index < records.length; index++) { + const item = get('request-item').nth(index); + assert(await item.isVisible(), `history item ${index} is hidden`); + const text = await item.innerText(); + for (const value of [records[index].prompt, records[index].model, records[index].chunks.join('')]) + assert(text.includes(value), `history item ${index} lost its own ${value}`); + const withoutPayload = [records[index].prompt, records[index].model, records[index].baseURL, + records[index].chunks.join('')].reduce((remaining, value) => remaining.replace(value, ''), text); + const visibleLabels = await item.locator('[aria-label]:visible, [title]:visible').evaluateAll( + elements => elements.flatMap(element => [element.getAttribute('aria-label'), element.getAttribute('title')].filter(Boolean)), + ); + const accessibleLabel = [await item.getAttribute('aria-label'), await item.getAttribute('title')]; + const status = [withoutPayload, ...accessibleLabel, ...visibleLabels].filter(Boolean).join(' ').toLowerCase(); + assert((completionLabel && status.includes(completionLabel)) + || /\b(?:complete(?:d)?|done|finished|succeeded|success)\b|完成|成功|[✓✔✅]/.test(status), + `history item ${index} does not display its completed status`); + } + await capture('02-two-requests'); + assert.equal(network.length, 0, `unexpected network requests: ${network.join(', ')}`); + + await get('clear-button').click(); + assert.equal(await get('request-item').count(), 0); + assert.equal(await page.evaluate(() => window.__mockRequests.length), 0); + await capture('03-cleared'); + await get('prompt-input').fill('fresh request after clearing'); + await get('send-button').click(); + await page.waitForFunction(() => window.__mockRequests[0]?.status === 'complete', null, {timeout: 4000}); + const fresh = await page.evaluate(() => structuredClone(window.__mockRequests[0])); + assert(fresh.id > records[1].id, 'clearing history reused an earlier id'); + assert.equal(await get('request-item').count(), 1, 'cleared history reappeared'); + await capture('04-after-clear'); + console.log('request audit behavior passed'); + } finally { + await browser.close(); + } +})().catch(error => {console.error(error); process.exit(1)}); diff --git a/task_012/acceptance_checklist.json b/task_012/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..d540389d8d5b4c2caa7e200e762d0822a84e7e9e --- /dev/null +++ b/task_012/acceptance_checklist.json @@ -0,0 +1,27 @@ +{ + "task_id": 13, + "category": "application_development", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Implements the requested domain workflow end to end.", + "Includes maintainable separation of concerns and meaningful tests when the task asks for them.", + "Enter sends the current prompt.", + "Shift+Enter inserts a newline and does not submit.", + "The input grows or remains usable for multiline text.", + "Timeout/no-response paths show visible feedback in the response area." + ], + "input_assets": [ + "index.html", + "config.js" + ], + "expected_outputs": [], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns.", + "A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "v2_notes": "Strengthened using sampled non-from-scratch/multi-turn trajectory signals.", + "repair_revision": "2026-09-29" +} diff --git a/task_012/environment/Dockerfile b/task_012/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_012/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_012/environment/code/config.js b/task_012/environment/code/config.js new file mode 100644 index 0000000000000000000000000000000000000000..fa88ff7624b49748d47d11f48c31ccf897930fde --- /dev/null +++ b/task_012/environment/code/config.js @@ -0,0 +1 @@ +window.aiConfig = { key: '', baseurl: '', modelname: '' }; diff --git a/task_012/environment/code/index.html b/task_012/environment/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..1863decd7b3bf269ed0da66bdd6bb62ab11e5fa8 --- /dev/null +++ b/task_012/environment/code/index.html @@ -0,0 +1,29 @@ + + + + + Fast Chat Fixture + + + + +
      + + +

      好的,这里有几个不同风格的标题

      + AI is generating response... +

      idle

      +
      + + + diff --git a/task_012/environment/docker-compose.yaml b/task_012/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_012/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_012/instruction.md b/task_012/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4d8829632a7b0a9ba2954ef389d7227d07435ba1 --- /dev/null +++ b/task_012/instruction.md @@ -0,0 +1,15 @@ +# Keyboard-first prompt composer + +Extend the local chat page at `/app/index.html` to support keyboard submission and an observable offline response. Keep the send button working and preserve `data-testid` hooks `chat-input`, `send-button`, `title`, `response`, and `status`. + +## Composer and reply behavior + +- Plain Enter submits the current nonblank prompt without adding a newline. Shift+Enter inserts a newline without submitting; let the textarea grow when multiline text exceeds its starting height. Ignore whitespace-only submissions. +- On send, show that generation is in progress. Use the local mock to produce a single direct, prompt-specific title and readable response text. No suggestion-style introduction or fixed titles/responses. The visible reply first contains partial text, then grows to the final text and leaves loading within five seconds. +- Expose `window.__setMockMode('timeout'|'normal')`. In timeout mode, end loading within five seconds, show “Timeout” or “超时” in the status, and keep the reply area visible with timeout or retry feedback. Returning to normal mode permits a successful new submission. Use “Loading” or “生成中” when generating and “Complete” or “完成” on success, or include those terms in a longer status message. No external network is required. + +## Acceptance Checklist + +- Enter submits promptly without inserting a newline; blank drafts are ignored. Shift+Enter leaves the draft unsent and grows the input for longer multiline content. +- Two different prompts produce distinct titles and readable responses in the visible reply. The loading state gives way to a partial reply and a longer completed reply. +- Timeout leaves a visible feedback region and a terminal status; after restoring normal mode, a subsequent request completes offline. diff --git a/task_012/provenance/restoration_notes.md b/task_012/provenance/restoration_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..013c95849d7f35643b75bcb4c114e531a581d2bf --- /dev/null +++ b/task_012/provenance/restoration_notes.md @@ -0,0 +1,12 @@ +# Restoration Notes for task_013 + +- 官方轨迹形态:existing website input behavior optimization +- v1 主要损失:v1 只覆盖 Enter 发送和基本 mock 输出,丢失后续键盘/失败路径需求。 +- v2 改动:新增 Shift+Enter 换行、textarea 自增高、timeout feedback、回复框存在测试。 + +## 代表性用户轮次 + +1. 输入框只能点击按钮发送,要求 Enter 发送。 +2. 编译报错:缺 autoprefixer。 +3. 追加 shift+enter 换行、真实 AI API、超时反馈、模型回复框。 +4. shift+enter 换行时输入框应变高。 diff --git a/task_012/provenance/user_turns.json b/task_012/provenance/user_turns.json new file mode 100644 index 0000000000000000000000000000000000000000..25cb169c69c4ea8ecd79d18e3fc403264ef63ec8 --- /dev/null +++ b/task_012/provenance/user_turns.json @@ -0,0 +1,17 @@ +{ + "task_id": 13, + "source": "HF CC-Bench-trajectories sampled metadata; public Dataset Server may differ from local GLM-4.6 source table", + "trajectory_type": "multi-turn", + "data": { + "category": "application_development", + "official_task_shape": "existing website input behavior optimization", + "representative_user_turns": [ + "输入框只能点击按钮发送,要求 Enter 发送。", + "编译报错:缺 autoprefixer。", + "追加 shift+enter 换行、真实 AI API、超时反馈、模型回复框。", + "shift+enter 换行时输入框应变高。" + ], + "loss_in_v1": "v1 只覆盖 Enter 发送和基本 mock 输出,丢失后续键盘/失败路径需求。", + "v2_change": "新增 Shift+Enter 换行、textarea 自增高、timeout feedback、回复框存在测试。" + } +} diff --git a/task_012/quality_notes.md b/task_012/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..8da9186e00ac25a6fdb20000e9bb7861ad049825 --- /dev/null +++ b/task_012/quality_notes.md @@ -0,0 +1,4 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. \ No newline at end of file diff --git a/task_012/solution/README.md b/task_012/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_012/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_012/solution/code/config.js b/task_012/solution/code/config.js new file mode 100644 index 0000000000000000000000000000000000000000..61e8f9b4516d561a7bd0cd51c5a76a809627c04d --- /dev/null +++ b/task_012/solution/code/config.js @@ -0,0 +1 @@ +window.aiConfig = { API_KEY: 'mock-key', BASE_URL: 'http://local-mock', MODEL_NAME: 'mock-model' }; diff --git a/task_012/solution/code/index.html b/task_012/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..74c738a1edf92ccef355baa96a11a9f29ef9ca79 --- /dev/null +++ b/task_012/solution/code/index.html @@ -0,0 +1,69 @@ + + + + + Fast Chat Solution v2 + + + + +

      Fast Chat

      Press Enter to send and Shift+Enter for a new line.

      +
      + + + +

      + +

      idle

      +
      + + + diff --git a/task_012/solution/solve.sh b/task_012/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_012/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_012/task.toml b/task_012/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_012/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_012/task_meta.json b/task_012/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..432c68f18e4d8cd02d5f4780d6fdd3607074ddea --- /dev/null +++ b/task_012/task_meta.json @@ -0,0 +1,27 @@ +{ + "task_id": 13, + "task_category": "application_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 15, + "language": "javascript", + "tool_files_from_selected_trace": [ + ".env.example", + ".env.local", + "AIContentArea.tsx", + "LayoutWindow.tsx", + "MainContentArea.tsx", + "PromptResponseBlock.tsx", + "ai-integration.ts", + "page.tsx", + "route.ts" + ], + "input_assets": [ + "index.html", + "config.js" + ], + "expected_outputs": [], + "source_row_id": 78, + "repair_revision": "2026-09-29", + "instruction_sha256": "67c3566c49839e5a6c5865eb79b24e596e7f9b8682a65877fad2c4628632b398" +} diff --git a/task_012/tests/_shared/contract_checker.js b/task_012/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_012/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_012/tests/_shared/static_enhancer.sh b/task_012/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_012/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_012/tests/enhancement_cases.json b/task_012/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..95ab29b7dd417b33377797f4ca30661da76d4e5a --- /dev/null +++ b/task_012/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "现在输入框无法使用回车触发发送,只能点击按钮。你优化,回车发送", + "validator": "tests/validate_enhanced_cases.js", + "behavior": "A plain Enter submits the current prompt, yields a non-empty completed response, and does not insert a newline." + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "v2 增加 `Shift+Enter` 换行、textarea 高度增长、timeout 反馈,以及回复框可见性的要求。", + "validator": "tests/validate_enhanced_cases.js", + "behavior": "Shift+Enter inserts a newline without submitting and the multiline editor grows in height." + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "需要实现 Enter 发送、快速 mock AI 响应处理、相关且非乱码的 streaming 输出、直接生成单个 title(不要出现建议式前缀),并在完成后不应停留在 `AI is generating response...`。", + "validator": "tests/validate_enhanced_cases.js", + "behavior": "The mock reply completes promptly in a visible reply region with readable text and no stuck generating message." + } +] diff --git a/task_012/tests/test.sh b/task_012/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ab2150eb79f6f15b53d20b21738b84bbe0d8003 --- /dev/null +++ b/task_012/tests/test.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_ui_behavior.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_012/tests/validate_aaav_dynamic.js b/task_012/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..0889f1a6a50a9e2a61b0f9702ac9df1a3c67ce2d --- /dev/null +++ b/task_012/tests/validate_aaav_dynamic.js @@ -0,0 +1,149 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 13; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + await page.route(/^https?:\/\//, route => route.abort('blockedbyclient')); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_012/tests/validate_browser_smoke.js b/task_012/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_012/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_012/tests/validate_enhanced_cases.js b/task_012/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..9123361c0ddfe8b2c5c5cc0dfec2d84ee34d1d76 --- /dev/null +++ b/task_012/tests/validate_enhanced_cases.js @@ -0,0 +1,155 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function findHtml(dir) { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (['tests', 'logs', 'node_modules', '.git'].includes(entry.name)) continue; + const file = path.join(dir, entry.name); + if (entry.isDirectory()) { + const nested = findHtml(file); + if (nested) return nested; + } else if (entry.name.toLowerCase().endsWith('.html')) { + return file; + } + } + return null; +} + +async function openFixture(browser, target) { + const page = await browser.newPage({ viewport: { width: 900, height: 700 } }); + const attemptedNetwork = []; + await page.route(/^https?:\/\//, route => { + attemptedNetwork.push(route.request().url()); + return route.abort('blockedbyclient'); + }); + await page.goto(pathToFileURL(target).href, { waitUntil: 'domcontentloaded' }); + const input = page.locator('textarea:visible, [contenteditable="true"]:visible, input:not([type="button"]):not([type="submit"]):visible').first(); + assert(await input.count(), 'chat page must expose a visible editable input'); + return { page, input, attemptedNetwork }; +} + +async function outputText(page) { + return page.locator('[data-testid="response"]:visible, [data-testid="title"]:visible, [data-testid="status"]:visible, output:visible, [aria-live]:visible, [role="status"]:visible') + .allTextContents().then(parts => parts.join(' ').trim()); +} + +async function inputValue(input) { + return input.evaluate(el => 'value' in el ? el.value : (el.textContent || '')); +} + +async function waitForCompletedOutput(page, timeout) { + await page.waitForFunction(() => /complete|done|finished|完成|已发送/i.test( + document.querySelector('[data-testid="status"]')?.textContent || ''), null, { timeout }); +} + +(async () => { + const target = path.join(process.cwd(), 'index.html'); + assert(target, 'no HTML entrypoint found'); + const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] }); + try { + // ENHANCED_CASE_1: pressing Enter submits the current prompt and produces a completed response. + { + const { page, input, attemptedNetwork } = await openFixture(browser, target); + await input.fill('enhanced enter submission'); + await input.press('Enter'); + await waitForCompletedOutput(page, 5000); + const response = await outputText(page); + assert(response.length > 0, 'Enter must produce a non-empty response'); + assert(!/AI is generating response\.\.\./i.test(response), 'completed response must not remain stuck in loading state'); + assert(!(await inputValue(input)).includes('\n'), 'plain Enter should submit rather than insert a newline'); + assert(attemptedNetwork.length === 0, 'enhanced case must run without network access'); + await page.close(); + } + + // ENHANCED_CASE_2: Shift+Enter inserts a newline, does not submit, and preserves/grows input height. + { + const { page, input, attemptedNetwork } = await openFixture(browser, target); + const beforeOutput = await outputText(page); + await input.fill(''); + await page.waitForTimeout(50); + const beforeBox = await input.boundingBox(); + for(let i=0;i<12;i++){await input.type(`line ${i}`);if(i<11)await input.press('Shift+Enter')} + await page.waitForTimeout(180); + const value = await inputValue(input); + const afterBox = await input.boundingBox(); + assert(value.split('\n').length >= 12, 'Shift+Enter must create content beyond the initial textarea capacity'); + assert(await outputText(page) === beforeOutput, 'Shift+Enter must not submit the prompt'); + assert(beforeBox && afterBox && afterBox.height > beforeBox.height, 'multiline input must grow above its empty initial height'); + assert(attemptedNetwork.length === 0, 'enhanced case must run without network access'); + await page.close(); + } + + // ENHANCED_CASE_3: the visible Send button still submits a readable reply. + { + const { page, input, attemptedNetwork } = await openFixture(browser, target); + await input.fill('give a concise productivity answer'); + await page.getByTestId('send-button').click(); + await waitForCompletedOutput(page, 5000); + const reply = page.getByTestId('response'); + const response = await reply.innerText(); + assert(await reply.isVisible(), 'Send button reply must be visible'); + assert(/[a-z\u3400-\u9fff]/i.test(response) && !response.includes('\uFFFD'), 'response must contain readable text'); + assert(response.trim().length > 0, 'completed response must remain visible through a public response hook'); + assert(!/AI is generating response\.\.\./i.test(await page.locator('body').innerText()), 'page must leave the generating state after completion'); + assert(attemptedNetwork.length === 0, 'enhanced case must run without network access'); + await page.close(); + } + + // ENHANCED_CASE_4: title and response must belong to the latest prompt, not a fixed fixture. + { + const {page, input} = await openFixture(browser, target); + await input.fill('calendar planning'); + await input.press('Enter'); + await waitForCompletedOutput(page, 5000); + const firstTitle = await page.locator('[data-testid="title"]').innerText(); + const firstResponse = await page.locator('[data-testid="response"]').innerText(); + await input.fill('recipe shopping'); + await input.press('Enter'); + await waitForCompletedOutput(page, 5000); + const secondTitle = await page.locator('[data-testid="title"]').innerText(); + const secondResponse = await page.locator('[data-testid="response"]').innerText(); + assert(firstTitle && secondTitle && firstTitle !== secondTitle, 'different prompts need different direct titles'); + assert(firstResponse && secondResponse && firstResponse !== secondResponse, 'responses must depend on the submitted prompt'); + await page.close(); + } + + // ENHANCED_CASE_5: the response box must show an intermediate chunk before completion. + { + const page = await browser.newPage(); + await page.route(/^https?:\/\//, route => route.abort('blockedbyclient')); + await page.clock.install(); + await page.goto(pathToFileURL(target).href); + await page.clock.pauseAt(new Date(Date.now() + 60000)); + await page.locator('[data-testid="chat-input"]').fill('streaming chronology'); + await page.locator('[data-testid="chat-input"]').press('Enter'); + assert(/generating|loading|生成中/i.test(await page.locator('[data-testid="status"]').innerText()), 'send must show loading'); + // The contract gives a 5-second budget, not the oracle's private 60/70 ms timing. + let partial = ''; + let complete = ''; + for (let elapsed = 0; elapsed < 5000; elapsed += 10) { + await page.clock.runFor(10); + const text = await page.locator('[data-testid="response"]').innerText(); + const status = await page.locator('[data-testid="status"]').innerText(); + if (/complete|done|完成/i.test(status)) { complete = text; break; } + if (text.trim()) partial = text; + } + assert(partial.trim(), 'a readable streamed chunk must precede completion'); + assert(complete.length > partial.length, 'completion must extend the streamed content within 5 seconds'); + fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + await page.screenshot({path: '/logs/verifier/visual-audit/stream-complete.png', fullPage: true}); + await page.close(); + } + } finally { + await browser.close(); + } + console.log('enhanced cases passed for task 13'); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_012/tests/validate_semantics.js b/task_012/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_012/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_012/tests/validate_ui_behavior.js b/task_012/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..4a849b686e53554e6e0f6156f9644f792f5fea0f --- /dev/null +++ b/task_012/tests/validate_ui_behavior.js @@ -0,0 +1,53 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage(); + await page.route(/^https?:\/\//, route => route.abort('blockedbyclient')); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + const input = page.locator('[data-testid="chat-input"]'); + await input.fill(' '); + const blankBefore = await page.locator('[data-testid="status"]').textContent(); + await input.press('Enter'); + await page.waitForTimeout(100); + if (await page.locator('[data-testid="status"]').textContent() !== blankBefore) throw new Error('blank prompt must not create a request'); + const before = await input.boundingBox(); + await input.fill('第一行'); + await page.keyboard.press('Shift+Enter'); + await page.keyboard.type('第二行'); + const value = await input.inputValue(); + if (!value.includes('\n')) throw new Error('Shift+Enter should insert a newline instead of sending'); + const after = await input.boundingBox(); + if (!after || !before || after.height < before.height) throw new Error('input should keep or increase height after multiline input'); + const statusBeforeSend = (await page.locator('[data-testid="status"]').textContent()) || ''; + if (/complete|sent/i.test(statusBeforeSend)) throw new Error('Shift+Enter must not submit the message'); + await page.keyboard.press('Enter'); + await page.waitForFunction(() => /complete|done|sent|完成|已发送/i.test(document.querySelector('[data-testid="status"]')?.textContent || ''), null, { timeout: 5000 }); + const title = (await page.locator('[data-testid="title"]').textContent()) || ''; + const response = (await page.locator('[data-testid="response"]').textContent()) || ''; + if (/好的,这里有几个|不同风格|AI is generating response/.test(title + response)) throw new Error('title/content should not keep suggestion preambles or stuck loading text'); + // The hidden topic (番茄/工作法) is never disclosed in the instruction; the verifier types + // 第一行/第二行. Only require that the Enter-submit produced a non-empty, generated + // title/response (i.e. the typed message was actually sent and answered). + if ((title + response).trim().length === 0) throw new Error('Enter should send the typed message and produce a non-empty generated response'); + await page.evaluate(() => window.__setMockMode && window.__setMockMode('timeout')); + await input.fill('超时测试'); + await page.keyboard.press('Enter'); + await page.waitForFunction(() => /timeout|failed|error|超时|失败|错误/i.test(document.querySelector('[data-testid="status"]')?.textContent || ''), null, { timeout: 5000 }); + const timeoutBox = page.locator('[data-testid="response"]'); + const timeoutResponse = (await timeoutBox.innerText()) || ''; + if (!(await timeoutBox.isVisible()) || !/超时|重试|timeout|timed[\s-]*out|retry|try\s+again/i.test(timeoutResponse)) { + throw new Error('timeout should leave a visible model response/feedback box'); + } + const fs = require('node:fs'); + fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + await page.screenshot({path: '/logs/verifier/visual-audit/timeout-feedback.png', fullPage: true}); + await page.evaluate(() => window.__setMockMode('normal')); + await input.fill('恢复后的新问题'); + await input.press('Enter'); + await page.waitForFunction(() => /complete|done|sent|完成|已发送/i.test(document.querySelector('[data-testid="status"]')?.textContent || ''), null, {timeout: 5000}); + if (!(await page.locator('[data-testid="response"]').innerText()).trim()) throw new Error('normal mode must recover after timeout'); + await page.screenshot({path: '/logs/verifier/visual-audit/timeout-recovered.png', fullPage: true}); + await browser.close(); +})().catch(err => { console.error(err && err.stack || err); process.exit(1); }); diff --git a/task_013/acceptance_checklist.json b/task_013/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..246a3e4256f03b3af7604f2811ebb355e5fadd6d --- /dev/null +++ b/task_013/acceptance_checklist.json @@ -0,0 +1,21 @@ +{ + "task_id": 18, + "category": "application_development", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Implements the requested domain workflow end to end.", + "Includes maintainable separation of concerns and meaningful tests when the task asks for them." + ], + "input_assets": [ + "index.html" + ], + "expected_outputs": [], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns.", + "A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_013/environment/Dockerfile b/task_013/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_013/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_013/environment/code/index.html b/task_013/environment/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..7d46aa76c28fb9bf21461b414996873cb03ae958 --- /dev/null +++ b/task_013/environment/code/index.html @@ -0,0 +1,23 @@ + + + + + demo-1001 Follow-up Fixture + + + +
      + +
      +
      + + + diff --git a/task_013/environment/docker-compose.yaml b/task_013/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_013/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_013/instruction.md b/task_013/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7eef8ce140d25c3adce9ae7fc972824ed0fab271 --- /dev/null +++ b/task_013/instruction.md @@ -0,0 +1,15 @@ +# Continuous keyboard follow-ups + +Fix the supplied demo-1001 prompt page in `/app/index.html`. Clicking “Write, press ..” opens the first composer. After sending the first question, the new follow-up input must receive focus automatically so the user can type and submit immediately. Keep focus on an editable follow-up after subsequent submissions. The page runs offline. + +## Interaction contract + +Plain Enter in the follow-up input submits exactly once. Shift+Enter and Enter during IME composition do not submit. Display each submitted question as plain text in the prompt area, preserving literal HTML characters rather than interpreting them as markup. There is no requirement to repeat the question in the reply. + +Preserve the starter hooks, including `write-trigger`, `prompt-input`, `send-button`, `prompt-area` and `followup-input`. Expose `window.__getSubmissions()`, returning a copy of the submitted texts in order for both button and keyboard submissions. Mutating the returned array must not affect stored submissions. + +## Acceptance Checklist + +- The first send creates and focuses the visible follow-up. Typing immediately goes into it without another click. +- Across at least five consecutive follow-ups, a plain Enter submits the exact input once, preserves focus and updates the ordered submission history. Shift+Enter and IME Enter do not submit. +- First and later submissions remain visible as literal text, and changing a returned history array cannot alter the page's history. diff --git a/task_013/provenance/restoration_notes.md b/task_013/provenance/restoration_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..db7d3c61303a890133a1b7c118b68ee0f95ece9c --- /dev/null +++ b/task_013/provenance/restoration_notes.md @@ -0,0 +1,10 @@ +# Restoration Notes for task_018 + +- 官方轨迹形态:docs/demo-1001 follow-up input autofocus bug +- v1 主要损失:核心 autofocus 还原较好,但未保留“只测试不改代码”的验收轮。 +- v2 改动:仅补 provenance;现有行为测试已经覆盖核心缺陷。 + +## 代表性用户轮次 + +1. 发送首个问题后新 follow-up 输入框没有自动聚焦。 +2. 后续要求不改代码测试多个功能点并返回通过比例。 diff --git a/task_013/provenance/user_turns.json b/task_013/provenance/user_turns.json new file mode 100644 index 0000000000000000000000000000000000000000..4dbce07b027671830b2dc39ab89f0cc31e57f243 --- /dev/null +++ b/task_013/provenance/user_turns.json @@ -0,0 +1,15 @@ +{ + "task_id": 18, + "source": "HF CC-Bench-trajectories sampled metadata; public Dataset Server may differ from local GLM-4.6 source table", + "trajectory_type": "multi-turn", + "data": { + "category": "application_development", + "official_task_shape": "docs/demo-1001 follow-up input autofocus bug", + "representative_user_turns": [ + "发送首个问题后新 follow-up 输入框没有自动聚焦。", + "后续要求不改代码测试多个功能点并返回通过比例。" + ], + "loss_in_v1": "核心 autofocus 还原较好,但未保留“只测试不改代码”的验收轮。", + "v2_change": "仅补 provenance;现有行为测试已经覆盖核心缺陷。" + } +} diff --git a/task_013/quality_notes.md b/task_013/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..8da9186e00ac25a6fdb20000e9bb7861ad049825 --- /dev/null +++ b/task_013/quality_notes.md @@ -0,0 +1,4 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. \ No newline at end of file diff --git a/task_013/solution/README.md b/task_013/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_013/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_013/solution/code/index.html b/task_013/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..45a9c12dd120bd66d76d0ba41028244225fdbb58 --- /dev/null +++ b/task_013/solution/code/index.html @@ -0,0 +1,40 @@ + +Follow Up Prompt + +
      +

      Demo 1001

      +

      Click the button below to start a question. After sending, a follow-up input will appear and receive focus automatically.

      +
      +
      +

      Write and press the button to continue with follow-up questions.

      + +
      +
      + + diff --git a/task_013/solution/solve.sh b/task_013/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_013/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_013/task.toml b/task_013/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_013/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_013/task_meta.json b/task_013/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..f7f30c86a644a68dbacfdeaece96bc460e0c8ac0 --- /dev/null +++ b/task_013/task_meta.json @@ -0,0 +1,28 @@ +{ + "task_id": 18, + "task_category": "application_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 28, + "language": "javascript", + "tool_files_from_selected_trace": [ + ".env.example", + ".env.local", + "AIContentArea.tsx", + "LayoutWindow.tsx", + "MainContentArea.tsx", + "PromptResponseBlock.tsx", + "agent-config.ts", + "agent-integration.ts", + "client.ts", + "page.tsx", + "route.ts" + ], + "input_assets": [ + "index.html" + ], + "expected_outputs": [], + "source_row_id": 108, + "repair_revision": "2026-09-29", + "instruction_sha256": "3422b2c7b94b07e8fcd3772d96cdd54f653107342e618eb1de78c7c9ca5f99ad" +} diff --git a/task_013/tests/_shared/contract_checker.js b/task_013/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_013/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_013/tests/_shared/static_enhancer.sh b/task_013/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_013/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_013/tests/enhancement_cases.json b/task_013/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..6ab1c457bf730d99b84a9178cc5a3f9ff38c50dd --- /dev/null +++ b/task_013/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "用户发送第一个问题后,新创建的 follow-up input 必须自动获得焦点,使用户能立刻键入并用键盘提交追问。", + "validator": "tests/validate_enhanced_cases.js", + "behavior": "After the first question is sent, the newly visible follow-up input is the active element." + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "此时新出现的输入框没有自动聚焦,我无法立刻输入追问。我希望可以能够直接打字提交追问问题。", + "validator": "tests/validate_enhanced_cases.js", + "behavior": "Typing immediately, without another click, places the exact keystrokes in the focused follow-up input." + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "用户发送第一个问题后,新创建的 follow-up input 必须自动获得焦点,使用户能立刻键入并用键盘提交追问。", + "validator": "tests/validate_enhanced_cases.js", + "behavior": "Pressing Enter from the focused follow-up input submits or records the typed follow-up question." + } +] diff --git a/task_013/tests/review_hard.js b/task_013/tests/review_hard.js new file mode 100644 index 0000000000000000000000000000000000000000..b38dda6042a73a2d04c4dcd9a839e8dc1f39808e --- /dev/null +++ b/task_013/tests/review_hard.js @@ -0,0 +1,48 @@ +const {chromium} = require('playwright'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const {pathToFileURL} = require('node:url'); + +(async () => { + const browser = await chromium.launch({headless: true, args: ['--no-sandbox']}); + try { + const page = await browser.newPage(); + await page.route(/^https?:/, route => route.abort()); + await page.goto(pathToFileURL(path.join(process.argv[2], 'index.html')).href); + const get = id => page.locator(`[data-testid="${id}"]`); + await get('write-trigger').click(); + const first = 'first literal'; + await get('prompt-input').fill(first); + await get('send-button').click(); + assert.deepEqual(await page.evaluate(() => window.__getSubmissions()), [first]); + assert((await get('prompt-area').textContent()).includes(first), 'first submitted text must be visible'); + assert.equal(await get('prompt-area').locator('b').count(), 0, 'first prompt must remain plain text'); + await page.evaluate(() => window.__getSubmissions().push('external tamper')); + assert.deepEqual(await page.evaluate(() => window.__getSubmissions()), [first], 'getter must return a copy'); + const input = get('followup-input'); + assert(await input.evaluate(element => document.activeElement === element)); + for (let index = 0; index < 5; index++) { + await input.fill(`follow ${index} literal`); + const before = await page.evaluate(() => window.__getSubmissions().length); + await input.press('Shift+Enter'); + await input.evaluate(element => element.dispatchEvent(new KeyboardEvent('keydown', { + key: 'Enter', isComposing: true, bubbles: true + }))); + assert.equal(await page.evaluate(() => window.__getSubmissions().length), before); + // Shift+Enter may legitimately insert a newline in a textarea. + const submittedText = await input.inputValue(); + await input.press('Enter'); + const submissions = await page.evaluate(() => window.__getSubmissions()); + assert.equal(submissions.length, before + 1, 'one Enter must submit exactly once'); + assert.equal(submissions.at(-1), submittedText); + assert((await get('prompt-area').textContent()).includes(submittedText), 'submitted text must remain in the page'); + assert.equal(await get('prompt-area').locator('b').count(), 0, 'HTML input must remain plain text'); + assert(await input.evaluate(element => document.activeElement === element), 'follow-up input lost focus'); + } + fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + await page.screenshot({path: '/logs/verifier/visual-audit/five-followups.png', fullPage: true}); + } finally { + await browser.close(); + } +})().catch(error => {console.error(error); process.exit(1)}); diff --git a/task_013/tests/review_legacy.sh b/task_013/tests/review_legacy.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ab2150eb79f6f15b53d20b21738b84bbe0d8003 --- /dev/null +++ b/task_013/tests/review_legacy.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_ui_behavior.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_013/tests/test.sh b/task_013/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..76fc765a05dd75147adf1b8ebc40310dee2c11b4 --- /dev/null +++ b/task_013/tests/test.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -uo pipefail +bash /tests/review_legacy.sh +CORE=$(cat /logs/verifier/reward.txt 2>/dev/null || echo 0) +mkdir -p /logs/verifier +node /tests/review_hard.js /app 2>&1 | tee /logs/verifier/review_hard.log +RC=${PIPESTATUS[0]} +if [ "$RC" -ne 0 ]; then echo "REVIEW_HARD failed with exit code $RC"; fi +if [ "$RC" -eq 0 ]; then echo "$CORE"; else echo 0; fi > /logs/verifier/reward.txt +exit 0 diff --git a/task_013/tests/validate_aaav_dynamic.js b/task_013/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..cc288567404e1542872b2b56b34463fd71c5623a --- /dev/null +++ b/task_013/tests/validate_aaav_dynamic.js @@ -0,0 +1,152 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 18; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + await page.route(/^https?:\/\//, route => route.abort('blockedbyclient')); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + // The visible-element/text-length padding threshold is dropped for this task: + // the required behavior (follow-up autofocus + Enter-submit) is verified by the + // dedicated behavioral checks, so cosmetic content volume is not gated here. + void stats; + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_013/tests/validate_browser_smoke.js b/task_013/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_013/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_013/tests/validate_enhanced_cases.js b/task_013/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..e159a4ba0378fba9573eb3655a8bc6098b9f6608 --- /dev/null +++ b/task_013/tests/validate_enhanced_cases.js @@ -0,0 +1,66 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +async function beginFirstQuestion(browser) { + const page = await browser.newPage({ viewport: { width: 900, height: 700 } }); + const attemptedNetwork = []; + await page.route(/^https?:\/\//, route => { + attemptedNetwork.push(route.request().url()); + return route.abort('blockedbyclient'); + }); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + await page.locator('[data-testid="write-trigger"]').click(); + await page.locator('[data-testid="prompt-input"]').fill('first deterministic question'); + await page.locator('[data-testid="send-button"]').click(); + const followup = page.locator('[data-testid="followup-input"]'); + await followup.waitFor({ state: 'visible', timeout: 2000 }); + return { page, followup, attemptedNetwork }; +} + +(async () => { + const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] }); + try { + // ENHANCED_CASE_1: the newly created follow-up editor itself owns focus after the first send. + { + const { page, followup, attemptedNetwork } = await beginFirstQuestion(browser); + assert(await followup.evaluate(el => document.activeElement === el), 'new follow-up input must receive focus automatically'); + assert(attemptedNetwork.length === 0, 'enhanced case must run without network access'); + await page.close(); + } + + // ENHANCED_CASE_2: immediate typing, without any extra click, is captured by the focused follow-up editor. + { + const { page, followup, attemptedNetwork } = await beginFirstQuestion(browser); + const question = 'typed immediately as a follow up'; + await page.keyboard.type(question); + assert(await followup.inputValue() === question, 'typing immediately must populate the follow-up input'); + assert(attemptedNetwork.length === 0, 'enhanced case must run without network access'); + await page.close(); + } + + // ENHANCED_CASE_3: Enter submits the focused follow-up question from the keyboard. + { + const { page, followup, attemptedNetwork } = await beginFirstQuestion(browser); + const question = 'keyboard submitted follow up'; + await page.keyboard.type(question); + const before = await page.locator('body').innerText(); + await page.keyboard.press('Enter'); + await page.waitForFunction(text => window.__getSubmissions().at(-1) === text, question, { timeout: 1500 }); + const after = await page.locator('body').innerText(); + assert(await page.evaluate(text=>window.__getSubmissions().at(-1)===text,question), 'Enter must submit or record the follow-up question'); + assert(attemptedNetwork.length === 0, 'enhanced case must run without network access'); + await page.close(); + } + } finally { + await browser.close(); + } + console.log('enhanced cases passed for task 18'); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_013/tests/validate_semantics.js b/task_013/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_013/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_013/tests/validate_ui_behavior.js b/task_013/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..4761c072223791ad4db6320815581448de90f556 --- /dev/null +++ b/task_013/tests/validate_ui_behavior.js @@ -0,0 +1,28 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 900, height: 700 } }); + await page.route(/^https?:\/\//, route => route.abort('blockedbyclient')); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + await page.locator('[data-testid="write-trigger"]').click(); + const prompt = page.locator('[data-testid="prompt-input"]'); + await prompt.fill('first question'); + await page.locator('[data-testid="send-button"]').click(); + await page.waitForTimeout(150); + const followup = page.locator('[data-testid="followup-input"]'); + if (!(await followup.isVisible())) throw new Error('follow-up input should be created after first send'); + const focusedId = await page.evaluate(() => document.activeElement && document.activeElement.getAttribute('data-testid')); + if (focusedId !== 'followup-input') throw new Error(`follow-up input should autofocus, focused=${focusedId}`); + await page.keyboard.type('second question'); + const value = await followup.inputValue(); + if (value !== 'second question') throw new Error('typing should go directly into focused follow-up input'); + await page.keyboard.press('Enter'); + await page.waitForTimeout(100); + const submitted = (await page.evaluate(()=>window.__getSubmissions())).at(-1); + if (submitted !== 'second question') { + throw new Error('Enter should submit or record the focused follow-up question'); + } + await browser.close(); +})().catch(err => { console.error(err && err.stack || err); process.exit(1); }); diff --git a/task_014/acceptance_checklist.json b/task_014/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..1024934ff25a539fea8bb1a59019aaa93da39f3d --- /dev/null +++ b/task_014/acceptance_checklist.json @@ -0,0 +1,15 @@ +{ + "task_id": 19, + "category": "application_development", + "language": "go", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Go sources compile and `go test ./...` passes when tests are present." + ], + "input_assets": [], + "expected_outputs": [], + "risk_notes": [], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_014/environment/Dockerfile b/task_014/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f7c63c1afe472bd572b57d5a48ffd3cf28ff5c8a --- /dev/null +++ b/task_014/environment/Dockerfile @@ -0,0 +1,4 @@ +# syntax=docker/dockerfile:1.7-labs +FROM golang:1.23-bookworm@sha256:167053a2bb901972bf2c1611f8f52c44d5fe7e762e5cab213708d82c421614db +WORKDIR /app +COPY ./code /app diff --git a/task_014/environment/code/go.mod b/task_014/environment/code/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..49b4ce09bf5e988d1a6dd0133a0369c4add714ef --- /dev/null +++ b/task_014/environment/code/go.mod @@ -0,0 +1,3 @@ +module lru_cache + +go 1.23 diff --git a/task_014/environment/code/lru.go b/task_014/environment/code/lru.go new file mode 100644 index 0000000000000000000000000000000000000000..5678a592dafee8c43a40df387ebc65926adced54 --- /dev/null +++ b/task_014/environment/code/lru.go @@ -0,0 +1,21 @@ +package lru + +import "time" + +type Cache struct{} + +func NewCache(capacity int) *Cache { + return &Cache{} +} + +func (c *Cache) Set(key string, value string) {} + +func (c *Cache) SetWithTTL(key string, value string, ttl time.Duration) {} + +func (c *Cache) Get(key string) (string, bool) { + return "", false +} + +func (c *Cache) GetAndRenewTTL(key string) (string, bool) { + return "", false +} diff --git a/task_014/environment/code/lru_ttl_test.go b/task_014/environment/code/lru_ttl_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2482ce8f9ef49328c2f9f290746dcb888a0070cb --- /dev/null +++ b/task_014/environment/code/lru_ttl_test.go @@ -0,0 +1,71 @@ +package lru + +import ( + "testing" + "time" +) + +type ttlTestClock struct{ now time.Time } + +func (c *ttlTestClock) Now() time.Time { return c.now } +func (c *ttlTestClock) Advance(d time.Duration) { c.now = c.now.Add(d) } + +func TestGetAndRenewTTLResetsExpiration(t *testing.T) { + clock := &ttlTestClock{now: time.Unix(1000, 0)} + cache := NewCacheWithClock(2, clock.Now) + cache.SetWithTTL("token", "abc", 120*time.Millisecond) + clock.Advance(70 * time.Millisecond) + value, ok := cache.GetAndRenewTTL("token") + if !ok || value != "abc" { + t.Fatalf("GetAndRenewTTL should return non-expired value, got %q ok=%v", value, ok) + } + clock.Advance(80 * time.Millisecond) + value, ok = cache.Get("token") + if !ok || value != "abc" { + t.Fatalf("TTL should have been renewed from original duration") + } + clock.Advance(60 * time.Millisecond) + if value, ok = cache.Get("token"); ok { + t.Fatalf("entry should expire after renewed TTL, got %q", value) + } +} + +func TestExpiredEntryIsNotRenewed(t *testing.T) { + clock := &ttlTestClock{now: time.Unix(1000, 0)} + cache := NewCacheWithClock(2, clock.Now) + cache.SetWithTTL("short", "gone", 30*time.Millisecond) + clock.Advance(50 * time.Millisecond) + if value, ok := cache.GetAndRenewTTL("short"); ok { + t.Fatalf("expired entry should not be renewed, got %q", value) + } +} + +func TestNormalGetDoesNotRenewTTL(t *testing.T) { + clock := &ttlTestClock{now: time.Unix(1000, 0)} + cache := NewCacheWithClock(2, clock.Now) + cache.SetWithTTL("plain", "value", 80*time.Millisecond) + clock.Advance(50 * time.Millisecond) + if value, ok := cache.Get("plain"); !ok || value != "value" { + t.Fatalf("normal Get should return before expiration") + } + clock.Advance(50 * time.Millisecond) + if value, ok := cache.Get("plain"); ok { + t.Fatalf("normal Get must not renew TTL, got %q", value) + } +} + +func TestLRUEvictionStillWorks(t *testing.T) { + cache := NewCache(2) + cache.Set("a", "1") + cache.Set("b", "2") + if _, ok := cache.Get("a"); !ok { + t.Fatalf("expected a before eviction") + } + cache.Set("c", "3") + if _, ok := cache.Get("b"); ok { + t.Fatalf("least recently used key b should be evicted") + } + if value, ok := cache.Get("a"); !ok || value != "1" { + t.Fatalf("recently used key a should remain") + } +} diff --git a/task_014/environment/docker-compose.yaml b/task_014/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_014/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_014/instruction.md b/task_014/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..897b347cc85e88ca9fb191e00c1f7c6ebc9e8b82 --- /dev/null +++ b/task_014/instruction.md @@ -0,0 +1,17 @@ +# Renewing reads for a Go LRU cache + +Extend the supplied Go cache without changing ordinary `Get` expiration behavior. Add a separate read method that renews a live entry's original time to live. Keep existing cache APIs and capacity-based LRU eviction. + +## API and expiry + +- Keep `NewCache(capacity int) *Cache` and provide `NewCacheWithClock(capacity int, now func() time.Time) *Cache`. Setting, reading and checking expiry use the injected clock. +- `GetAndRenewTTL(key string) (string, bool)` returns a live value and sets its expiry to the current time plus the duration from the most recent write. Repeated renewals use that original duration, not the remaining time or the previous deadline. A renewal counts as access for LRU recency. +- A missing entry or one with `now >= expiresAt` returns a miss and cannot be revived. Plain `Get` never extends a TTL. A non-expiring entry can be read with either method without gaining a deadline. Replacing an entry with a new TTL updates the duration used for later renewals. + +Write unit tests for renewal and run `go test ./...` offline. + +## Acceptance Checklist + +- Normal reads and eviction still work. Renewing a live entry returns its value and makes it recently used. +- A renewal extends expiry by the full most recently set TTL. Overwriting and repeated renewal use the correct duration. +- Plain reads do not renew. An entry misses at or after its deadline and stays expired; entries written without TTL remain non-expiring. diff --git a/task_014/quality_notes.md b/task_014/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..6a8dfa0cd464aece2bfb438d2ede7b4352b186c3 --- /dev/null +++ b/task_014/quality_notes.md @@ -0,0 +1,2 @@ +# Quality Notes +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. diff --git a/task_014/solution/README.md b/task_014/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_014/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_014/solution/code/go.mod b/task_014/solution/code/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..49b4ce09bf5e988d1a6dd0133a0369c4add714ef --- /dev/null +++ b/task_014/solution/code/go.mod @@ -0,0 +1,3 @@ +module lru_cache + +go 1.23 diff --git a/task_014/solution/code/lru.go b/task_014/solution/code/lru.go new file mode 100644 index 0000000000000000000000000000000000000000..e74c5ef52b30dcbda60204709d6f3a1685557dc1 --- /dev/null +++ b/task_014/solution/code/lru.go @@ -0,0 +1,139 @@ +package lru + +import "time" + +type entry struct { + key string + value string + expiresAt time.Time + ttl time.Duration + prev *entry + next *entry +} + +type Cache struct { + capacity int + items map[string]*entry + head *entry + tail *entry + now func() time.Time +} + +func NewCache(capacity int) *Cache { + if capacity < 1 { + capacity = 1 + } + return NewCacheWithClock(capacity, time.Now) +} + +// NewCacheWithClock exposes deterministic TTL testing without changing NewCache. +func NewCacheWithClock(capacity int, now func() time.Time) *Cache { + if capacity < 1 { + capacity = 1 + } + if now == nil { + now = time.Now + } + return &Cache{capacity: capacity, items: map[string]*entry{}, now: now} +} + +func (c *Cache) Set(key string, value string) { c.set(key, value, 0) } + +func (c *Cache) SetWithTTL(key string, value string, ttl time.Duration) { c.set(key, value, ttl) } + +func (c *Cache) set(key, value string, ttl time.Duration) { + if e, ok := c.items[key]; ok { + e.value = value + e.ttl = ttl + if ttl > 0 { + e.expiresAt = c.now().Add(ttl) + } else { + e.expiresAt = time.Time{} + } + c.moveToFront(e) + return + } + e := &entry{key: key, value: value, ttl: ttl} + if ttl > 0 { + e.expiresAt = c.now().Add(ttl) + } + c.items[key] = e + c.pushFront(e) + if len(c.items) > c.capacity { + c.remove(c.tail) + } +} + +func (c *Cache) Get(key string) (string, bool) { + e, ok := c.items[key] + if !ok || c.expired(e) { + if ok { + c.remove(e) + } + return "", false + } + c.moveToFront(e) + return e.value, true +} + +func (c *Cache) GetAndRenewTTL(key string) (string, bool) { + e, ok := c.items[key] + if !ok || c.expired(e) { + if ok { + c.remove(e) + } + return "", false + } + if e.ttl > 0 { + e.expiresAt = c.now().Add(e.ttl) + } + c.moveToFront(e) + return e.value, true +} + +func (c *Cache) expired(e *entry) bool { return !e.expiresAt.IsZero() && !c.now().Before(e.expiresAt) } + +func (c *Cache) pushFront(e *entry) { + e.prev = nil + e.next = c.head + if c.head != nil { + c.head.prev = e + } + c.head = e + if c.tail == nil { + c.tail = e + } +} + +func (c *Cache) moveToFront(e *entry) { + if e == c.head { + return + } + if e.prev != nil { + e.prev.next = e.next + } + if e.next != nil { + e.next.prev = e.prev + } + if e == c.tail { + c.tail = e.prev + } + c.pushFront(e) +} + +func (c *Cache) remove(e *entry) { + if e == nil { + return + } + if e.prev != nil { + e.prev.next = e.next + } else { + c.head = e.next + } + if e.next != nil { + e.next.prev = e.prev + } else { + c.tail = e.prev + } + delete(c.items, e.key) +} diff --git a/task_014/solution/solve.sh b/task_014/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_014/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_014/task.toml b/task_014/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_014/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_014/task_meta.json b/task_014/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..f28664fcef2d5ce69ab13cf535ddc2d928b12fa2 --- /dev/null +++ b/task_014/task_meta.json @@ -0,0 +1,19 @@ +{ + "task_id": 19, + "task_category": "application_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 1, + "language": "go", + "tool_files_from_selected_trace": [ + "expirable_lru.go", + "expirable_lru_test.go", + "go.mod", + "list.go" + ], + "input_assets": [], + "expected_outputs": [], + "source_row_id": 114, + "repair_revision": "2026-09-29", + "instruction_sha256": "61ae00d433a628cf6b9e3484a540d9b9a65e4a2e7f4603206dedf92884800a4a" +} diff --git a/task_014/tests/_shared/contract_checker.js b/task_014/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_014/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_014/tests/_shared/static_enhancer.sh b/task_014/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_014/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_014/tests/enhancement_cases.json b/task_014/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..fd0d51462e24c4c4327552b5b6c1d85a2d9d0652 --- /dev/null +++ b/task_014/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "如果缓存未过期,会返回这个缓存并且重设这个缓存的过期时间为最初的过期时间", + "validator": "tests/validate_enhanced_ttl_test.go", + "behavior": "A renewing read returns a live value, extends it past the original deadline, and it later expires after the renewed original TTL." + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "在我获取带有过期时间的缓存时,如果缓存已过期则返回空", + "validator": "tests/validate_enhanced_ttl_test.go", + "behavior": "A renewing read of an already expired entry is a miss and does not revive the entry." + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "普通 TTL `Get` 保持既有过期语义;新增 renew 方法在条目未过期时返回值,并将过期时间重置为最初 TTL;已过期条目必须返回空/未命中,且不能被续期。", + "validator": "tests/validate_enhanced_ttl_test.go", + "behavior": "The original ordinary Get still returns a live TTL entry without renewing its expiration." + } +] diff --git a/task_014/tests/test.sh b/task_014/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..52d37cb6cc5272563de6d183905aa8e28ac288e6 --- /dev/null +++ b/task_014/tests/test.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set +e +T="$(cd "$(dirname "$0")" && pwd)"; R=/logs/verifier; mkdir -p "$R"; p=1 +command -v go >/dev/null 2>&1 || p=0 +[ "$p" = 1 ] && go test ./... || p=0 +[ "$p" = 1 ] && timeout 30s bash "$T/validate_enhanced_cases.sh" || p=0 +echo "$p" > "$R/reward.txt"; exit 0 diff --git a/task_014/tests/validate_enhanced_cases.sh b/task_014/tests/validate_enhanced_cases.sh new file mode 100644 index 0000000000000000000000000000000000000000..6ae6206a29d27543465cdaf2ae6f7b7878212188 --- /dev/null +++ b/task_014/tests/validate_enhanced_cases.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +set -euo pipefail + +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +CANDIDATE_DIR="$(pwd)" +WORK_DIR="$(mktemp -d)" +cleanup() { rm -rf -- "$WORK_DIR"; } +trap cleanup EXIT + +cp -R "$CANDIDATE_DIR/." "$WORK_DIR/" +cp "$TEST_DIR/validate_enhanced_ttl_test.go" "$WORK_DIR/enhanced_ttl_test.go" + +export GOPROXY=off +export GOSUMDB=off +export GOFLAGS='-mod=readonly' +export TEST_SEED=19019 +if command -v timeout >/dev/null 2>&1; then + (cd "$WORK_DIR" && timeout 20s go test -tags enhanced_validator -count=1 -run '^TestEnhanced' .) +else + (cd "$WORK_DIR" && go test -tags enhanced_validator -count=1 -run '^TestEnhanced' .) +fi diff --git a/task_014/tests/validate_enhanced_ttl_test.go b/task_014/tests/validate_enhanced_ttl_test.go new file mode 100644 index 0000000000000000000000000000000000000000..53eff5c7f1c46fd032996e242efca12c5cd65217 --- /dev/null +++ b/task_014/tests/validate_enhanced_ttl_test.go @@ -0,0 +1,135 @@ +//go:build enhanced_validator + +package lru + +import ( + "testing" + "time" +) + +type fakeClock struct{ t time.Time } + +func (c *fakeClock) Now() time.Time { return c.t } +func (c *fakeClock) Advance(d time.Duration) { c.t = c.t.Add(d) } + +func TestEnhancedRenewingReadRestartsOriginalTTL(t *testing.T) { + clock := &fakeClock{t: time.Unix(1000, 0)} + cache := NewCacheWithClock(2, clock.Now) + cache.SetWithTTL("session", "value", 10*time.Second) + clock.Advance(7 * time.Second) + if value, ok := cache.GetAndRenewTTL("session"); !ok || value != "value" { + t.Fatalf("renew failed") + } + clock.Advance(4 * time.Second) + if _, ok := cache.Get("session"); !ok { + t.Fatal("entry expired at original deadline") + } + clock.Advance(7 * time.Second) + if _, ok := cache.Get("session"); ok { + t.Fatal("entry survived renewed deadline") + } +} + +func TestEnhancedExpiredEntryCannotBeRenewed(t *testing.T) { + clock := &fakeClock{t: time.Unix(1000, 0)} + cache := NewCacheWithClock(2, clock.Now) + cache.SetWithTTL("expired", "gone", time.Second) + clock.Advance(2 * time.Second) + if _, ok := cache.GetAndRenewTTL("expired"); ok { + t.Fatal("expired entry revived") + } +} + +func TestEnhancedOrdinaryGetDoesNotRenewTTL(t *testing.T) { + clock := &fakeClock{t: time.Unix(1000, 0)} + cache := NewCacheWithClock(2, clock.Now) + cache.SetWithTTL("ordinary", "value", 10*time.Second) + clock.Advance(7 * time.Second) + if _, ok := cache.Get("ordinary"); !ok { + t.Fatal("early expiry") + } + clock.Advance(4 * time.Second) + if _, ok := cache.Get("ordinary"); ok { + t.Fatal("ordinary Get renewed TTL") + } +} + +func TestEnhancedExactDeadlineIsExpired(t *testing.T) { + clock := &fakeClock{t: time.Unix(1000, 0)} + cache := NewCacheWithClock(2, clock.Now) + cache.SetWithTTL("boundary", "value", 10*time.Second) + clock.Advance(10 * time.Second) + if _, ok := cache.GetAndRenewTTL("boundary"); ok { + t.Fatal("exact deadline revived an expired entry") + } +} + +func TestEnhancedNonTTLDoesNotGainExpiration(t *testing.T) { + clock := &fakeClock{t: time.Unix(1000, 0)} + cache := NewCacheWithClock(2, clock.Now) + cache.Set("persistent", "value") + if value, ok := cache.GetAndRenewTTL("persistent"); !ok || value != "value" { + t.Fatal("non-TTL read failed") + } + clock.Advance(24 * time.Hour) + if _, ok := cache.Get("persistent"); !ok { + t.Fatal("non-TTL entry acquired an expiration") + } +} + +func TestEnhancedRenewalPreservesLRURecency(t *testing.T) { + clock := &fakeClock{t: time.Unix(1000, 0)} + cache := NewCacheWithClock(2, clock.Now) + cache.SetWithTTL("a", "A", time.Hour) + cache.Set("b", "B") + if _, ok := cache.GetAndRenewTTL("a"); !ok { + t.Fatal("renew read failed") + } + cache.Set("c", "C") + if _, ok := cache.Get("b"); ok { + t.Fatal("renew read did not refresh LRU recency") + } + if _, ok := cache.Get("a"); !ok { + t.Fatal("renewed entry was evicted") + } +} + +func TestEnhancedOverwriteChangesOriginalTTL(t *testing.T) { + clock := &fakeClock{t: time.Unix(2000, 0)} + cache := NewCacheWithClock(3, clock.Now) + cache.SetWithTTL("updated", "old", time.Hour) + cache.SetWithTTL("updated", "new", 3*time.Second) + clock.Advance(2 * time.Second) + if value, ok := cache.GetAndRenewTTL("updated"); !ok || value != "new" { + t.Fatal("overwriting did not replace the cached value") + } + clock.Advance(3 * time.Second) + if _, ok := cache.GetAndRenewTTL("updated"); ok { + t.Fatal("renewal used a stale TTL after overwrite") + } + cache.SetWithTTL("persistent", "timed", time.Second) + cache.Set("persistent", "untimed") + clock.Advance(time.Hour) + if value, ok := cache.GetAndRenewTTL("persistent"); !ok || value != "untimed" { + t.Fatal("Set did not remove a previously assigned TTL") + } +} + +func TestEnhancedRepeatedRenewalUsesOriginalDuration(t *testing.T) { + clock := &fakeClock{t: time.Unix(3000, 0)} + cache := NewCacheWithClock(2, clock.Now) + cache.SetWithTTL("repeated", "value", 7*time.Second) + for i := 0; i < 5; i++ { + clock.Advance(6 * time.Second) + if value, ok := cache.GetAndRenewTTL("repeated"); !ok || value != "value" { + t.Fatalf("renewal %d shortened the original TTL", i) + } + } + clock.Advance(7 * time.Second) + if _, ok := cache.Get("repeated"); ok { + t.Fatal("repeated renewals extended TTL beyond its original duration") + } + if value, ok := cache.GetAndRenewTTL("missing"); ok || value != "" { + t.Fatal("a missing key must remain a miss") + } +} diff --git a/task_015/acceptance_checklist.json b/task_015/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..362d1a52da719e9b4839f312a06cd204f20e0a5c --- /dev/null +++ b/task_015/acceptance_checklist.json @@ -0,0 +1,19 @@ +{ + "task_id": 20, + "category": "application_development", + "language": "python", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Python files compile; data-analysis tasks generate the requested output files from fixture data." + ], + "input_assets": [ + "original_go/cron.go" + ], + "expected_outputs": [], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_015/environment/Dockerfile b/task_015/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc4e749304efa37f966a363cd3fa4ec09b78695d --- /dev/null +++ b/task_015/environment/Dockerfile @@ -0,0 +1,4 @@ +# syntax=docker/dockerfile:1.7-labs +FROM python:3.12-slim@sha256:090ba77e2958f6af52a5341f788b50b032dd4ca28377d2893dcf1ecbdfdfe203 +WORKDIR /app +COPY ./code /app diff --git a/task_015/environment/code/README.md b/task_015/environment/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..642e85706ef2cb61c8a3d2fe46bdb6ac4de027d7 --- /dev/null +++ b/task_015/environment/code/README.md @@ -0,0 +1,3 @@ +# PyCron Port + +TODO: document features and usage. diff --git a/task_015/environment/code/example/example.py b/task_015/environment/code/example/example.py new file mode 100644 index 0000000000000000000000000000000000000000..30afdceb85e0ec0c73d29001d097a8ad7257d1f3 --- /dev/null +++ b/task_015/environment/code/example/example.py @@ -0,0 +1,9 @@ +from pycron import CronScheduler + +if __name__ == "__main__": + scheduler = CronScheduler() + counter = {"count": 0} + scheduler.add_interval_job(0.05, lambda: counter.__setitem__("count", counter["count"] + 1)) + scheduler.start() + scheduler.stop() + print(f"executions={counter['count']}") diff --git a/task_015/environment/code/original_go/cron.go b/task_015/environment/code/original_go/cron.go new file mode 100644 index 0000000000000000000000000000000000000000..05b41a79132fb14f146619ec83a9f8fd8dec95b7 --- /dev/null +++ b/task_015/environment/code/original_go/cron.go @@ -0,0 +1,4 @@ +package cron + +// Closed fixture source behavior: a scheduler can add interval jobs, start, +// stop, and execute jobs repeatedly according to a short interval. diff --git a/task_015/environment/code/pycron/__init__.py b/task_015/environment/code/pycron/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6bffa50f07a7dfb61555ec85b0889b9df0bf39ef --- /dev/null +++ b/task_015/environment/code/pycron/__init__.py @@ -0,0 +1 @@ +from .cron import CronScheduler, IntervalSchedule diff --git a/task_015/environment/code/pycron/cron.py b/task_015/environment/code/pycron/cron.py new file mode 100644 index 0000000000000000000000000000000000000000..ec996c89dfd49992970261673b108a23dc7b8550 --- /dev/null +++ b/task_015/environment/code/pycron/cron.py @@ -0,0 +1,16 @@ +class IntervalSchedule: + def __init__(self, seconds): + self.seconds = seconds + +class CronScheduler: + def __init__(self): + self.jobs = [] + + def add_interval_job(self, seconds, func): + self.jobs.append((seconds, func)) + + def start(self): + pass + + def stop(self): + pass diff --git a/task_015/environment/docker-compose.yaml b/task_015/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_015/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_015/instruction.md b/task_015/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5ff9ba81841984b690eab0f5f143b162fa5ca514 --- /dev/null +++ b/task_015/instruction.md @@ -0,0 +1,18 @@ +# Python interval scheduler + +Implement a Python interval scheduler from the behavior documented in `original_go/cron.go`. Keep that file as the source specification. Cron expression parsing is out of scope. Run offline. + +## API and deliverables + +Export `CronScheduler` and `IntervalSchedule` from the `pycron` package. `IntervalSchedule(seconds)` stores a positive finite interval. `CronScheduler.add_interval_job(seconds, callback)` registers a recurring job. Reject zero, negative, NaN and infinite durations immediately with `ValueError` or `TypeError`. + +Jobs do not run until `start()`. Each has its own interval and first executes no sooner than one full interval after starting, allowing normal scheduling delay. Calling `start()` again while running must not duplicate callbacks. `stop()` cancels pending executions and prevents further callbacks; a later `start()` resumes the registered schedule. + +Provide a runnable `example/example.py` that demonstrates a scheduled callback and prints its result. Write `README.md` explaining features, usage and the scope of the Go behavior specification. + +## Acceptance Checklist + +- The package imports both classes; the example runs and produces demonstration output, and the README explains usage. +- Jobs stay dormant before starting, execute repeatedly at independent intervals and never execute early. Repeated starts do not produce duplicate ticking. +- Stop prevents future callbacks, including a pending first callback; restarting resumes execution. +- Both public interval entry points reject invalid durations. diff --git a/task_015/quality_notes.md b/task_015/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..569002e2a2f22166aad79b2875ae767eb3d71acf --- /dev/null +++ b/task_015/quality_notes.md @@ -0,0 +1,4 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. diff --git a/task_015/solution/README.md b/task_015/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_015/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_015/solution/code/README.md b/task_015/solution/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..dc2c176ac1ddbd068682152ffc560e24d32a918c --- /dev/null +++ b/task_015/solution/code/README.md @@ -0,0 +1,19 @@ +# PyCron interval scheduler + +This closed fixture's `original_go/cron.go` contains an interval-scheduler behavior summary, not an executable Go implementation. The Python package implements that scope; it does not parse cron expressions. + +`CronScheduler.add_interval_job(seconds, callback)` registers a callback with a positive finite interval. Jobs begin only after `start()`, run repeatedly, and stop after `stop()`. Repeated `start()` calls are idempotent; a stopped scheduler can be started again. Register jobs before starting. `IntervalSchedule` stores a validated interval. + +Usage: + +```python +from pycron import CronScheduler + +scheduler = CronScheduler() +scheduler.add_interval_job(0.1, lambda: print("tick")) +scheduler.start() +# Perform other work, then stop the scheduler. +scheduler.stop() +``` + +Run `python example/example.py` for a complete short-running example. The implementation uses only Python's standard library and needs no network access. diff --git a/task_015/solution/code/example/example.py b/task_015/solution/code/example/example.py new file mode 100644 index 0000000000000000000000000000000000000000..be905cca66bd2a9a9b826de545a0eec0209a990f --- /dev/null +++ b/task_015/solution/code/example/example.py @@ -0,0 +1,19 @@ +"""Example usage of the pycron scheduler. + +This runnable example demonstrates the core features; see README.md for the +full documentation and additional usage examples. +""" +import time +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from pycron import CronScheduler + +if __name__ == "__main__": + scheduler = CronScheduler() + counter = {"count": 0} + scheduler.add_interval_job(0.05, lambda: counter.__setitem__("count", counter["count"] + 1)) + scheduler.start() + time.sleep(0.18) + scheduler.stop() + print(f"executions={counter['count']}") diff --git a/task_015/solution/code/pycron/__init__.py b/task_015/solution/code/pycron/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6bffa50f07a7dfb61555ec85b0889b9df0bf39ef --- /dev/null +++ b/task_015/solution/code/pycron/__init__.py @@ -0,0 +1 @@ +from .cron import CronScheduler, IntervalSchedule diff --git a/task_015/solution/code/pycron/cron.py b/task_015/solution/code/pycron/cron.py new file mode 100644 index 0000000000000000000000000000000000000000..b4ef1e46ddbeb2be81e05a5e032ee33766fac335 --- /dev/null +++ b/task_015/solution/code/pycron/cron.py @@ -0,0 +1,45 @@ +import threading +import math + +class IntervalSchedule: + def __init__(self, seconds): + self.seconds = float(seconds) + if not math.isfinite(self.seconds) or self.seconds <= 0: + raise ValueError("interval seconds must be a positive finite number") + +class CronScheduler: + def __init__(self): + self.jobs = [] + self._stop = threading.Event() + self._threads = [] + self._running = False + + def add_interval_job(self, seconds, func): + if not callable(func): + raise TypeError("interval callback must be callable") + if self._running: + raise RuntimeError("register jobs before starting the scheduler") + self.jobs.append((IntervalSchedule(seconds), func)) + + def _run_job(self, schedule, func): + while not self._stop.wait(schedule.seconds): + func() + + def start(self): + if self._running: + return + self._stop = threading.Event() + self._threads = [] + for schedule, func in self.jobs: + thread = threading.Thread(target=self._run_job, args=(schedule, func), daemon=True) + thread.start() + self._threads.append(thread) + self._running = True + + def stop(self): + if not self._running: + return + self._stop.set() + for thread in self._threads: + thread.join(timeout=1) + self._running = False diff --git a/task_015/solution/solve.sh b/task_015/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_015/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_015/task.toml b/task_015/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_015/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_015/task_meta.json b/task_015/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..0bb36db2819470dca44c27ee18da119ddf0700a3 --- /dev/null +++ b/task_015/task_meta.json @@ -0,0 +1,43 @@ +{ + "task_id": 20, + "task_category": "application_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 3, + "language": "python", + "tool_files_from_selected_trace": [ + "README.md", + "__init__.py", + "chain.go", + "chain.py", + "constant_delay.py", + "constantdelay.go", + "cron.go", + "cron.py", + "example.py", + "final_verification.py", + "job.py", + "logger.go", + "logger.py", + "option.go", + "option.py", + "parser.go", + "parser.py", + "schedule.py", + "setup.py", + "spec.go", + "test_actual_example.py", + "test_basic.py", + "test_example_run.py", + "test_quick_accuracy.py", + "test_scheduling_accuracy.py", + "test_simple.py" + ], + "input_assets": [ + "original_go/cron.go" + ], + "expected_outputs": [], + "source_row_id": 120, + "repair_revision": "2026-09-29", + "instruction_sha256": "f79682f63d8e74dc5672c9be02ebc23d1adb8342ae987a6a2f885241984a2842" +} diff --git a/task_015/tests/_shared/contract_checker.js b/task_015/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_015/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_015/tests/_shared/static_enhancer.sh b/task_015/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_015/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_015/tests/enhancement_cases.json b/task_015/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..527dbeab04dc853507a304fc245ff9c329c4b463 --- /dev/null +++ b/task_015/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "将 `original_go/` 视为需要迁移的源行为。需要实现 Python cron scheduler package,提供 class/function API", + "validator": "tests/validate_enhancements.py", + "behavior": "An added interval job remains dormant before start, then repeats after the scheduler starts." + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "verifier 会运行示例并检查短间隔任务至少触发两次、scheduler 可 start/stop、README 记录已迁移的功能点。", + "validator": "tests/validate_enhancements.py", + "behavior": "Two independently added short-interval jobs both execute repeatedly while running." + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "verifier 会运行示例并检查短间隔任务至少触发两次、scheduler 可 start/stop", + "validator": "tests/validate_enhancements.py", + "behavior": "Stopping before a pending interval elapses prevents that callback from running later." + } +] diff --git a/task_015/tests/test.sh b/task_015/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ad1c256e938f20a82cdedba71e6c4717a5a5bbf7 --- /dev/null +++ b/task_015/tests/test.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set +e +T="$(cd "$(dirname "$0")" && pwd)"; R=/logs/verifier; mkdir -p "$R"; p=1 +command -v python3 >/dev/null 2>&1 || p=0 +[ "$p" = 1 ] && python3 "$T/validate_outputs.py" || p=0 +[ "$p" = 1 ] && timeout 20s python3 "$T/validate_enhancements.py" || p=0 +echo "$p" > "$R/reward.txt"; exit 0 diff --git a/task_015/tests/validate_enhancements.py b/task_015/tests/validate_enhancements.py new file mode 100644 index 0000000000000000000000000000000000000000..4d0035e6d206cfdcd34449aaf4678de7389ccc55 --- /dev/null +++ b/task_015/tests/validate_enhancements.py @@ -0,0 +1,128 @@ +import importlib +import pathlib +import socket +import sys +import time +import threading +import math + + +def deny_network(*_args, **_kwargs): + raise AssertionError("network access is forbidden during enhanced validation") + + +socket.create_connection = deny_network +socket.socket.connect = deny_network + +root = pathlib.Path.cwd() +sys.path.insert(0, str(root)) +pycron = importlib.import_module("pycron") + + +def new_scheduler(): + return pycron.CronScheduler() + + +def wait_until(predicate, timeout=1.5): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if predicate(): + return True + time.sleep(0.01) + return predicate() + + +# ENHANCED_CASE_1: adding an interval job must not run it until start() is called. +dormant_count = {"value": 0} +dormant = new_scheduler() +dormant.add_interval_job( + 0.04, lambda: dormant_count.__setitem__("value", dormant_count["value"] + 1) +) +time.sleep(0.10) +assert dormant_count["value"] == 0, "an added job ran before the scheduler was started" +dormant.start() +assert wait_until(lambda: dormant_count["value"] >= 2), ( + "a started short-interval job did not repeat" +) +dormant.stop() + + +# ENHANCED_CASE_2: separately added interval jobs must both execute repeatedly. +counts = {"fast": 0, "slow": 0} +multiple = new_scheduler() +multiple.add_interval_job(0.03, lambda: counts.__setitem__("fast", counts["fast"] + 1)) +multiple.add_interval_job(0.06, lambda: counts.__setitem__("slow", counts["slow"] + 1)) +multiple.start() +assert wait_until(lambda: counts["fast"] >= 3 and counts["slow"] >= 2), ( + f"separately added interval jobs did not both repeat: {counts}" +) +multiple.stop() + + +# ENHANCED_CASE_3: stop() must cancel a pending interval, including its first callback. +late_count = {"value": 0} +stopped_early = new_scheduler() +stopped_early.add_interval_job( + 0.25, lambda: late_count.__setitem__("value", late_count["value"] + 1) +) +stopped_early.start() +stopped_early.stop() +time.sleep(0.28) +assert late_count["value"] == 0, "a callback ran after stop() cancelled its pending interval" + + +# ENHANCED_CASE_4: a stopped scheduler can start again without losing jobs. +restart_count = {"value": 0} +restarted = new_scheduler() +restarted.add_interval_job(0.04, lambda: restart_count.__setitem__("value", restart_count["value"] + 1)) +restarted.start() +assert wait_until(lambda: restart_count["value"] >= 2), "job did not run before restart" +restarted.stop() +before_restart = restart_count["value"] +restarted.start() +assert wait_until(lambda: restart_count["value"] >= before_restart + 2), "job did not resume after restart" +restarted.stop() + + +# ENHANCED_CASE_5: invalid intervals must not create busy loops or delayed failures. +for invalid in (0, -0.01, float("nan"), float("inf")): + constructors = { + "IntervalSchedule": pycron.IntervalSchedule, + "add_interval_job": lambda seconds: new_scheduler().add_interval_job(seconds, lambda: None), + } + for name, construct in constructors.items(): + try: + construct(invalid) + except (ValueError, TypeError): + continue + raise AssertionError(f"{name} accepted invalid interval {invalid!r}") + +pycron.IntervalSchedule(0.125) + + +# ENHANCED_CASE_6: calling start twice must not duplicate each interval tick. +idempotent_count = {"value": 0} +idempotent = new_scheduler() +idempotent.add_interval_job(0.10, lambda: idempotent_count.__setitem__("value", idempotent_count["value"] + 1)) +started_at = time.monotonic() +idempotent.start() +idempotent.start() +assert wait_until(lambda: idempotent_count["value"] >= 4), "repeated start stopped execution" +idempotent.stop() +elapsed = time.monotonic() - started_at +assert idempotent_count["value"] <= math.floor(elapsed / 0.10) + 1, ( + f"repeated start duplicated interval callbacks: {idempotent_count['value']}" +) + +# The first callback must wait for its interval; late scheduling is permissible. +first_tick = threading.Event() +fired_at = [] +not_early = new_scheduler() +not_early.add_interval_job(0.20, lambda: (fired_at.append(time.monotonic()), first_tick.set())) +started_at = time.monotonic() +not_early.start() +assert first_tick.wait(2), "first callback never fired" +not_early.stop() +assert fired_at[0] - started_at >= 0.195, "callback ran before its initial interval" + +print("enhanced cases passed for task 20") diff --git a/task_015/tests/validate_outputs.py b/task_015/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..31330756d009f49b9dabeea18065931541bc84fc --- /dev/null +++ b/task_015/tests/validate_outputs.py @@ -0,0 +1,60 @@ +import subprocess +import time +import os +import pathlib +import sys +import importlib + +root = pathlib.Path(__file__).resolve().parents[1] + +candidate_roots = [ + pathlib.Path.cwd(), + root / 'environment' / 'code', + root / 'solution' / 'code', + root, +] +base = next((p for p in candidate_roots if p.exists()), root) + +assert (base / 'original_go' / 'cron.go').exists(), f'missing original_go/cron.go in {base}' +assert (base / 'pycron').exists(), f'missing pycron package in {base}' +assert (base / 'example' / 'example.py').exists(), f'missing example/example.py in {base}' +assert (base / 'README.md').exists() and (base / 'README.md').stat().st_size > 0, f'missing README.md in {base}' + +sys.path.insert(0, str(base)) +mod = importlib.import_module('pycron') +assert hasattr(mod, 'CronScheduler'), 'pycron should expose CronScheduler' +assert hasattr(mod, 'IntervalSchedule'), 'pycron should expose IntervalSchedule' + +env = os.environ.copy() +env["PYTHONPATH"] = str(base) + (os.pathsep + env.get("PYTHONPATH", "")) +proc = subprocess.run( + [sys.executable, str(base / 'example' / 'example.py')], + cwd=base, + env=env, + capture_output=True, + text=True, + timeout=5, +) +assert proc.returncode == 0, 'example/example.py should run successfully: ' + proc.stderr +assert proc.stdout.strip(), 'example output should show that the scheduled callback ran' + +counter = {'count': 0} +scheduler = mod.CronScheduler() +assert hasattr(scheduler, 'add_interval_job'), 'CronScheduler missing add_interval_job' +assert hasattr(scheduler, 'start') and hasattr(scheduler, 'stop'), 'CronScheduler missing start/stop' +scheduler.add_interval_job(0.05, lambda: counter.__setitem__('count', counter['count'] + 1)) +scheduler.start() +deadline = time.monotonic() + 2.0 +while counter['count'] < 2 and time.monotonic() < deadline: + time.sleep(0.01) +scheduler.stop() +assert counter['count'] >= 2, f'interval job did not repeat within the execution budget: {counter["count"]}' +# stop() must actually halt the scheduler: no further ticks after stopping +count_at_stop = counter['count'] +time.sleep(0.3) +assert counter['count'] == count_at_stop, ( + f'stop() should halt the scheduler: ticked from {count_at_stop} to {counter["count"]} after stop' +) + +readme = (base / 'README.md').read_text(encoding='utf-8', errors='ignore').lower() +assert any(term in readme for term in ('usage', '使用', '用法', '示例')), 'README should explain how to use the scheduler' diff --git a/task_016/acceptance_checklist.json b/task_016/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..450209cbe8bae36b6ee9528663af208d448d9e9e --- /dev/null +++ b/task_016/acceptance_checklist.json @@ -0,0 +1,26 @@ +{ + "task_id": 21, + "category": "application_development", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Wrong admin password is rejected.", + "admin/admin whitelist login succeeds.", + "Only 中文 and 英文 can enter lessons; other languages show `unsupport`.", + "Lessons include boy, women, man, apple and Chinese equivalents." + ], + "input_assets": [ + "index.html", + "src/LoginScreen.tsx", + "src/register.tsx", + "src/lesson.tsx" + ], + "expected_outputs": [], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "v2_notes": "Strengthened using sampled non-from-scratch/multi-turn trajectory signals.", + "repair_revision": "2026-09-29" +} diff --git a/task_016/environment/Dockerfile b/task_016/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_016/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_016/environment/code/index.html b/task_016/environment/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..70912074ea68ea9a5475e7324bfd4b14bb14664b --- /dev/null +++ b/task_016/environment/code/index.html @@ -0,0 +1,35 @@ + + + + + Language Learning Fixture + + + +
      + + + +

      not logged in

      +
      + + + + + + + diff --git a/task_016/environment/code/src/LoginScreen.tsx b/task_016/environment/code/src/LoginScreen.tsx new file mode 100644 index 0000000000000000000000000000000000000000..62b7b7ddb12b28cfd1d96d5ceb092f74393b7c6c --- /dev/null +++ b/task_016/environment/code/src/LoginScreen.tsx @@ -0,0 +1,2 @@ +// Implement the admin whitelist here. +window.loginWhitelist = { admin: "admin" }; diff --git a/task_016/environment/code/src/lesson.tsx b/task_016/environment/code/src/lesson.tsx new file mode 100644 index 0000000000000000000000000000000000000000..5cb6b578e731d80675ca03111dcbe831b40b761e --- /dev/null +++ b/task_016/environment/code/src/lesson.tsx @@ -0,0 +1,7 @@ +// Implement Chinese and English lesson cards here. +window.lessonWords = [ + { zh: "男孩", en: "boy" }, + { zh: "女人", en: "women" }, + { zh: "男人", en: "man" }, + { zh: "苹果", en: "apple" } +]; diff --git a/task_016/environment/code/src/register.tsx b/task_016/environment/code/src/register.tsx new file mode 100644 index 0000000000000000000000000000000000000000..41bd372b681715ca8ba079eae6fc8af6545a2b33 --- /dev/null +++ b/task_016/environment/code/src/register.tsx @@ -0,0 +1,2 @@ +// Implement the Chinese/English language guard here. +window.supportedLanguages = ["中文", "英文"]; diff --git a/task_016/environment/docker-compose.yaml b/task_016/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_016/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_016/instruction.md b/task_016/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..397f0cba8f3d79e1b60931c617f0c92e7cce0d7a --- /dev/null +++ b/task_016/instruction.md @@ -0,0 +1,17 @@ +# Local bilingual vocabulary lessons + +Extend the supplied offline learning demo at `/app/index.html`. Keep `src/LoginScreen.tsx`, `src/register.tsx`, and `src/lesson.tsx` and the starter's `data-testid` hooks. The HTML page must run without installing or contacting external services. + +## Login and lessons + +Only the local demo credentials `admin` / `admin` may enter language selection. A failed login clears any previous authorization and lesson view. A logged-out user must not reach a lesson through hidden controls or scripted activation. This is a local gate, not server-side authentication. + +Keep the native `language-select` dropdown. Offer Chinese and English (the labels 中文 and 英文 are also accepted) and at least one unsupported language. Only the supported options may proceed. An unsupported selection shows a dismissible popup containing `unsupport` and closes any open lesson. Use a native alert or a visible HTML dialog with an accessible Close/OK button; the popup is sufficient without a duplicate status message. + +In both supported lessons, display the vocabulary pairs **boy / 男孩**, **women / 女人**, **man / 男人**, and **apple / 苹果**. Provide learning prompts appropriate to the selected language. + +## Acceptance Checklist + +- The offline page renders and retains the source files and starter controls. Correct credentials open language selection; a wrong username or password does not. +- Both supported choices open their lesson and display all four vocabulary terms. +- Unsupported choices show the dismissible warning and never leave an old lesson visible. A later failed login resets authorization and cannot be bypassed through a hidden control. diff --git a/task_016/provenance/restoration_notes.md b/task_016/provenance/restoration_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..682efb6c34b0b9592e431d34b58e1f3849a47fab --- /dev/null +++ b/task_016/provenance/restoration_notes.md @@ -0,0 +1,11 @@ +# Restoration Notes for task_021 + +- 官方轨迹形态:existing React learning app feature additions +- v1 主要损失:功能合并为单轮,部分测试依赖关键词,未验证错误登录等真实 UI 路径。 +- v2 改动:增强 UI 行为测试:错误登录不应通过、admin 登录、unsupported language、课程内容。 + +## 代表性用户轮次 + +1. 添加 admin/admin 白名单登录、语言选择限制、补充中英文题目。 +2. 多轮要求搜索 LoginScreen/register/lesson 文件并验证位置。 +3. 后续要求不改代码验证功能点。 diff --git a/task_016/provenance/user_turns.json b/task_016/provenance/user_turns.json new file mode 100644 index 0000000000000000000000000000000000000000..7e3273a920a7b43344e66f82336a5c671f5d5533 --- /dev/null +++ b/task_016/provenance/user_turns.json @@ -0,0 +1,16 @@ +{ + "task_id": 21, + "source": "HF CC-Bench-trajectories sampled metadata; public Dataset Server may differ from local GLM-4.6 source table", + "trajectory_type": "multi-turn", + "data": { + "category": "application_development", + "official_task_shape": "existing React learning app feature additions", + "representative_user_turns": [ + "添加 admin/admin 白名单登录、语言选择限制、补充中英文题目。", + "多轮要求搜索 LoginScreen/register/lesson 文件并验证位置。", + "后续要求不改代码验证功能点。" + ], + "loss_in_v1": "功能合并为单轮,部分测试依赖关键词,未验证错误登录等真实 UI 路径。", + "v2_change": "增强 UI 行为测试:错误登录不应通过、admin 登录、unsupported language、课程内容。" + } +} diff --git a/task_016/quality_notes.md b/task_016/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..569002e2a2f22166aad79b2875ae767eb3d71acf --- /dev/null +++ b/task_016/quality_notes.md @@ -0,0 +1,4 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. diff --git a/task_016/solution/README.md b/task_016/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_016/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_016/solution/code/index.html b/task_016/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..2c476dc5fb0eb69ef4559c9e4bbdd2e337052672 --- /dev/null +++ b/task_016/solution/code/index.html @@ -0,0 +1,37 @@ + +Language Learning v2 + +

      not logged in

      + + + + + diff --git a/task_016/solution/code/src/LoginScreen.tsx b/task_016/solution/code/src/LoginScreen.tsx new file mode 100644 index 0000000000000000000000000000000000000000..e6bca194120f1e806ef7824081b52dc425454f86 --- /dev/null +++ b/task_016/solution/code/src/LoginScreen.tsx @@ -0,0 +1 @@ +window.loginWhitelist = { admin: 'admin' }; diff --git a/task_016/solution/code/src/lesson.tsx b/task_016/solution/code/src/lesson.tsx new file mode 100644 index 0000000000000000000000000000000000000000..af18c6b80d9c9897a2a86c78d696a17dfa1ceb0f --- /dev/null +++ b/task_016/solution/code/src/lesson.tsx @@ -0,0 +1 @@ +window.lessonWords = [{zh:'\u7537\u5b69',en:'boy'},{zh:'\u5973\u4eba',en:'women'},{zh:'\u7537\u4eba',en:'man'},{zh:'\u82f9\u679c',en:'apple'}]; diff --git a/task_016/solution/code/src/register.tsx b/task_016/solution/code/src/register.tsx new file mode 100644 index 0000000000000000000000000000000000000000..e3617e4e729eae09adbb962b414a64a777c0122b --- /dev/null +++ b/task_016/solution/code/src/register.tsx @@ -0,0 +1 @@ +window.supportedLanguages = ['\u4e2d\u6587', '\u82f1\u6587']; diff --git a/task_016/solution/solve.sh b/task_016/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_016/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_016/task.toml b/task_016/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_016/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_016/task_meta.json b/task_016/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..f2620c82bdd4caaef085ace9a61d1304e672fa6a --- /dev/null +++ b/task_016/task_meta.json @@ -0,0 +1,29 @@ +{ + "task_id": 21, + "task_category": "application_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 3, + "language": "javascript", + "tool_files_from_selected_trace": [ + "LanguageCarousel.tsx", + "LoginScreen.tsx", + "Svgs.tsx", + "index.tsx", + "languages.ts", + "learn.tsx", + "lesson.tsx", + "package.json", + "register.tsx" + ], + "input_assets": [ + "index.html", + "src/LoginScreen.tsx", + "src/register.tsx", + "src/lesson.tsx" + ], + "expected_outputs": [], + "source_row_id": 126, + "repair_revision": "2026-09-29", + "instruction_sha256": "9017b8bbb92b9513944c06fbeeec235157d16c35b972d45b1041f4cc85b370bd" +} diff --git a/task_016/tests/_shared/contract_checker.js b/task_016/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_016/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_016/tests/_shared/offline_browser.js b/task_016/tests/_shared/offline_browser.js new file mode 100644 index 0000000000000000000000000000000000000000..ccb050000819e4156a9923758a041c526dbbfc5e --- /dev/null +++ b/task_016/tests/_shared/offline_browser.js @@ -0,0 +1,65 @@ +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { spawnSync } = require('child_process'); +const { pathToFileURL } = require('url'); + +function chromiumBinary() { + const candidates = [process.env.CHROMIUM_BIN, '/snap/bin/chromium', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/usr/bin/google-chrome']; + const found = candidates.find(candidate => candidate && fs.existsSync(candidate)); + if (!found) throw new Error('offline Chromium binary is unavailable'); + return found; +} + +function runBrowserCase(entryPath, caseFunction, input = null) { + const snapShared = path.join(os.homedir(), 'snap', 'chromium', 'common'); + const stagingRoot = fs.existsSync(snapShared) ? snapShared : os.tmpdir(); + const tempDir = fs.mkdtempSync(path.join(stagingRoot, 'harbor-offline-browser-')); + const wrapperPath = path.join(tempDir, 'runner.html'); + const candidateDir = path.join(tempDir, 'candidate'); + const resolvedEntry = path.resolve(entryPath); + fs.cpSync(path.dirname(resolvedEntry), candidateDir, { + recursive: true, + filter: source => !['tests', 'logs', 'node_modules'].includes(path.basename(source)), + }); + const entryUrl = pathToFileURL(path.join(candidateDir, path.basename(resolvedEntry))).href; + const payload = JSON.stringify(input).replace(/WAITING + + + + diff --git a/task_017/environment/docker-compose.yaml b/task_017/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_017/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_017/instruction.md b/task_017/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..758e15e0d4a6f2cb48da358477122aa8a42e55f3 --- /dev/null +++ b/task_017/instruction.md @@ -0,0 +1,15 @@ +# Click-outside behavior for a paragraph editor + +Fix the supplied block editor in the root `index.html`. Each paragraph can be opened for editing and closed by clicking anywhere outside that editor, including another paragraph. Closing must return to the non-editing view, not simply remove focus. + +## Editing and persistence + +Treat whitespace-only input as empty and restore the editable empty paragraph. For nonempty input, keep the typed text in that block and show it when closed. Leading and trailing whitespace may be preserved or trimmed. Show literal HTML characters as text. Save each block independently and restore its text after a reload, without reopening editors. Reopening a block loads its own saved text. + +Keep the starter's paragraph hooks (including `block-1`, `block-2`, and `block-3`) and label the active editable control with `data-testid="active-input"`. The page runs directly and offline. + +## Acceptance Checklist + +- Clicking away closes the editor and either restores the empty state or saves the typed text. Moving between blocks does not mix their values. +- Reopening displays the saved value; changing and closing the editor updates that block alone. All saved blocks survive reload, with editors closed. +- HTML-looking text stays literal. Clearing a paragraph with whitespace persists the empty state while leaving the block available to edit. diff --git a/task_017/quality_notes.md b/task_017/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..8da9186e00ac25a6fdb20000e9bb7861ad049825 --- /dev/null +++ b/task_017/quality_notes.md @@ -0,0 +1,4 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. \ No newline at end of file diff --git a/task_017/solution/README.md b/task_017/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_017/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_017/solution/code/index.html b/task_017/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..e58d4ec314f807a3c5e02d8a13e0c357e9f23f18 --- /dev/null +++ b/task_017/solution/code/index.html @@ -0,0 +1,51 @@ + +Paragraph Editor + + +

      Notion-like editor

      +

      Click any paragraph to edit it. Click outside the paragraph to finish editing; your text will be preserved.

      +
      Paragraph Editor
      +
      +
      +
      +
      3 paragraph blocks
      + + diff --git a/task_017/solution/solve.sh b/task_017/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_017/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_017/task.toml b/task_017/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_017/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_017/task_meta.json b/task_017/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..fdcacbdbb0ac001544c3dbb939cf4c8f093bd108 --- /dev/null +++ b/task_017/task_meta.json @@ -0,0 +1,31 @@ +{ + "task_id": 26, + "task_category": "ui_optimization", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 13, + "language": "javascript", + "tool_files_from_selected_trace": [ + "AIContentArea.tsx", + "LayoutWindow.tsx", + "MainContentArea.tsx", + "NavigationSidebar.tsx", + "TopNavigation.tsx", + "ai-state-machine.ts", + "package.json", + "page-1-before-input.json", + "page-2-input-on-focus.json", + "page.tsx", + "parser.ts", + "postcss.config.js", + "route.ts", + "types.ts" + ], + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "source_row_id": 156, + "repair_revision": "2026-09-29", + "instruction_sha256": "5459ee268d2b55e727f21ecdc2a276e1326b4a1cc9e063a71ff638479cfff29a" +} diff --git a/task_017/tests/_shared/contract_checker.js b/task_017/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_017/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_017/tests/_shared/offline_browser.js b/task_017/tests/_shared/offline_browser.js new file mode 100644 index 0000000000000000000000000000000000000000..66f3146e7c88159bd6d44ee4786af119f67ecc89 --- /dev/null +++ b/task_017/tests/_shared/offline_browser.js @@ -0,0 +1,66 @@ +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { spawnSync } = require('child_process'); +const { pathToFileURL } = require('url'); + +function chromiumBinary() { + const candidates = [process.env.CHROMIUM_BIN, '/snap/bin/chromium', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/usr/bin/google-chrome']; + const found = candidates.find(candidate => candidate && fs.existsSync(candidate)); + if (!found) throw new Error('offline Chromium binary is unavailable'); + return found; +} + +function runBrowserCase(entryPath, caseFunction, input = null) { + const snapShared = path.join(os.homedir(), 'snap', 'chromium', 'common'); + const stagingRoot = fs.existsSync(snapShared) ? snapShared : os.tmpdir(); + const tempDir = fs.mkdtempSync(path.join(stagingRoot, 'harbor-offline-browser-')); + const wrapperPath = path.join(tempDir, 'runner.html'); + const candidateDir = path.join(tempDir, 'candidate'); + const resolvedEntry = path.resolve(entryPath); + fs.cpSync(path.dirname(resolvedEntry), candidateDir, { + recursive: true, + filter: source => !['tests', 'logs', 'node_modules'].includes(path.basename(source)), + }); + const entryUrl = pathToFileURL(path.join(candidateDir, path.basename(resolvedEntry))).href; + const payload = JSON.stringify(input).replace(/WAITING + + + + diff --git a/task_018/environment/docker-compose.yaml b/task_018/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_018/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_018/instruction.md b/task_018/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..10b4495d260b7108213a55d5da5bf4e7b58d0f4b --- /dev/null +++ b/task_018/instruction.md @@ -0,0 +1,15 @@ +# Responsive sidebar and content layout + +Repair the supplied sidebar layout in the root `index.html`. The page must open directly offline. Preserve the starter's `sidebar`, `sidebar-toggle`, `layout` and `main-content` test IDs. + +## Layout and controls + +- In desktop layouts, keep the sidebar flush with the viewport's left edge and the main column horizontally beside it. In an extra-wide viewport, center the main column in the space between the sidebar's right edge and the viewport's right edge. +- On narrow screens, set a positive minimum width for the main column that it can honor while remaining within the viewport. At 420 px and 640 px the page must not scroll horizontally; at 420 px both edges of the main column must be visible. Do not hide overflowing content to simulate a fit. +- The toggle must visually collapse the sidebar. Hide it, move it off-screen, or reduce its visible width to less than 40 px; an ARIA attribute alone is not a collapse. At 420 px, the sidebar may start collapsed and open as an overlay, but the toggle must stay clickable to close it. + +## Acceptance Checklist + +- Desktop content sits to the right of the visible sidebar. The sidebar stays at the left edge as the main column centers in the available space at a wider viewport. +- Toggling changes the visible sidebar layout. On mobile the toggle can close an open sidebar without being covered. +- The narrow column honors a positive minimum width and remains fully visible without horizontal overflow or script errors. diff --git a/task_018/quality_notes.md b/task_018/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..8da9186e00ac25a6fdb20000e9bb7861ad049825 --- /dev/null +++ b/task_018/quality_notes.md @@ -0,0 +1,4 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. \ No newline at end of file diff --git a/task_018/solution/README.md b/task_018/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_018/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_018/solution/code/index.html b/task_018/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..70839887fb226f0449fd74ef66f19b01fe35ea38 --- /dev/null +++ b/task_018/solution/code/index.html @@ -0,0 +1,22 @@ + +Responsive Layout + + +
      + +

      Main content

      +
      + + diff --git a/task_018/solution/solve.sh b/task_018/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_018/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_018/task.toml b/task_018/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_018/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_018/task_meta.json b/task_018/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..3d6b0fbc97d31ce5fb58be8d3b352de888d428c6 --- /dev/null +++ b/task_018/task_meta.json @@ -0,0 +1,21 @@ +{ + "task_id": 28, + "task_category": "ui_optimization", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 8, + "language": "javascript", + "tool_files_from_selected_trace": [ + "AIContentArea.tsx", + "LayoutWindow.tsx", + "MainContentArea.tsx", + "NavigationSidebar.tsx" + ], + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "source_row_id": 168, + "repair_revision": "2026-09-29", + "instruction_sha256": "44d9a7e60638bcc51cf5e8919fa7343e649246d6d0709460e7ca0fa60700605f" +} diff --git a/task_018/tests/_shared/contract_checker.js b/task_018/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_018/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_018/tests/_shared/static_enhancer.sh b/task_018/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_018/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_018/tests/enhancement_cases.json b/task_018/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..e0d89340e881221d2f24ea4a5abd303818fd0bbc --- /dev/null +++ b/task_018/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "修复后的页面必须保持 sidebar 在左、content 在右", + "validator": "tests/validate_enhanced_cases.js#ENHANCED_CASE_1", + "behavior": "At a desktop viewport, the fixture sidebar touches the left edge and vertically overlaps with a main content area positioned to its right." + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "点击 toggle 时折叠 sidebar", + "validator": "tests/validate_enhanced_cases.js#ENHANCED_CASE_2", + "behavior": "Clicking the fixture toggle changes the initially expanded sidebar to a collapsed or hidden state." + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "窄视口下避免横向滚动;超宽视口下 content column 居中,同时 sidebar 仍保持左对齐。", + "validator": "tests/validate_enhanced_cases.js#ENHANCED_CASE_3", + "behavior": "At a narrow viewport, main content defines and honors a positive fixed minimum width without page-level horizontal scrolling; at a wide viewport, the sidebar stays left and content is centered in the remaining region." + } +] diff --git a/task_018/tests/test.sh b/task_018/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ab2150eb79f6f15b53d20b21738b84bbe0d8003 --- /dev/null +++ b/task_018/tests/test.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_ui_behavior.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_018/tests/validate_aaav_dynamic.js b/task_018/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..d9a721332b0980c1098f155f0ef6fcec0d1ed2b4 --- /dev/null +++ b/task_018/tests/validate_aaav_dynamic.js @@ -0,0 +1,148 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 28; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_018/tests/validate_browser_smoke.js b/task_018/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_018/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_018/tests/validate_enhanced_cases.js b/task_018/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..3f6043f27108b18655530a7734a9a49f769e8afc --- /dev/null +++ b/task_018/tests/validate_enhanced_cases.js @@ -0,0 +1,180 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +const fs = require('node:fs'); +fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + +const entryUrl = pathToFileURL(path.join(process.cwd(), 'index.html')).href; +const seed = Number.parseInt(process.env.ENHANCED_SEED || '28031', 10); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +async function runCase(browser, name, viewport, validate) { + const context = await browser.newContext({ viewport }); + const networkAttempts = []; + await context.route('**/*', async (route) => { + const url = route.request().url(); + if (/^https?:/i.test(url)) { + networkAttempts.push(url); + await route.abort('blockedbyclient'); + return; + } + await route.continue(); + }); + await context.addInitScript(({ fixedSeed }) => { + let state = fixedSeed >>> 0; + Math.random = () => { + state = (state * 1664525 + 1013904223) >>> 0; + return state / 0x100000000; + }; + }, { fixedSeed: seed }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on('pageerror', (error) => errors.push(error.message)); + try { + await page.goto(entryUrl, { waitUntil: 'domcontentloaded' }); + await validate(page); + await page.screenshot({path: `/logs/verifier/visual-audit/${name}.png`, fullPage: true}); + assert(networkAttempts.length === 0, `${name}: external network request attempted`); + assert(errors.length === 0, `${name}: browser errors: ${errors.join(' | ')}`); + console.log(`${name} passed`); + } finally { + await context.close(); + } +} + +async function waitForCollapsedSidebar(page, selector, initialVisibleWidth) { + await page.evaluate(({ selector, initialVisibleWidth }) => new Promise((resolve, reject) => { + const deadline = performance.now() + 4500; + let lastWidth = initialVisibleWidth; + let stableFrames = 0; + let reduced = false; + const sample = () => { + const element = document.querySelector(selector); + if (!element) { + reject(new Error('fixture sidebar must exist')); + return; + } + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + const visibleWidth = Math.max(0, Math.min(innerWidth, rect.right) - Math.max(0, rect.left)); + reduced = visibleWidth < 40 || style.display === 'none' || style.visibility === 'hidden'; + stableFrames = reduced && Math.abs(visibleWidth - lastWidth) < 0.01 ? stableFrames + 1 : 0; + lastWidth = visibleWidth; + if (reduced && stableFrames >= 4) resolve(); + else if (performance.now() >= deadline) reject(new Error('sidebar did not reach a stable collapsed state')); + else requestAnimationFrame(sample); + }; + sample(); + }), { selector, initialVisibleWidth }); +} + +(async () => { + assert(Number.isInteger(seed), 'ENHANCED_SEED must be a fixed integer'); + const browser = await chromium.launch({ + headless: true, + args: ['--no-sandbox', '--disable-background-networking', '--disable-component-update', '--no-first-run'], + }); + try { + // ENHANCED_CASE_1: the sidebar and content remain in a left-to-right layout. + await runCase(browser, 'ENHANCED_CASE_1', { width: 1200, height: 800 }, async (page) => { + const boxes = await page.evaluate(() => { + const sidebar = document.querySelector('[data-testid="sidebar"]')?.getBoundingClientRect(); + const main = document.querySelector('[data-testid="main-content"]')?.getBoundingClientRect(); + return sidebar && main ? { + sidebar: { left: sidebar.left, right: sidebar.right, top: sidebar.top, bottom: sidebar.bottom }, + main: { left: main.left, top: main.top, bottom: main.bottom }, + } : null; + }); + assert(boxes, 'fixture sidebar and main content must exist'); + assert(boxes.sidebar.left <= 1, 'sidebar must stay against the left edge'); + assert(boxes.main.left >= boxes.sidebar.right - 1, 'main content must be to the right of the sidebar'); + assert(Math.min(boxes.sidebar.bottom, boxes.main.bottom) > Math.max(boxes.sidebar.top, boxes.main.top), + 'sidebar and main content must vertically overlap instead of stacking'); + }); + + // ENHANCED_CASE_2: activating the provided toggle visibly collapses the sidebar. + await runCase(browser, 'ENHANCED_CASE_2', { width: 900, height: 700 }, async (page) => { + const sidebar = page.locator('[data-testid="sidebar"]'); + const before = await sidebar.boundingBox(); + assert(before && before.width > 1, 'sidebar must initially be visible'); + await page.locator('[data-testid="sidebar-toggle"]').click(); + await waitForCollapsedSidebar(page, '[data-testid="sidebar"]', before.width); + const collapsed = await sidebar.evaluate((element, initialWidth) => { + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + const visibleWidth = Math.max(0, Math.min(innerWidth, rect.right) - Math.max(0, rect.left)); + return visibleWidth < 40 || style.display === 'none' || style.visibility === 'hidden'; + }, before.width); + assert(collapsed, 'sidebar must collapse after its toggle is clicked'); + }); + + // ENHANCED_CASE_3: responsive extremes preserve narrow usability and wide centering. + await runCase(browser, 'ENHANCED_CASE_3', { width: 420, height: 700 }, async (page) => { + const narrow = await page.evaluate(() => { + const mainElement = document.querySelector('[data-testid="main-content"]'); + const main = mainElement?.getBoundingClientRect(); + const minWidth = mainElement ? Number.parseFloat(getComputedStyle(mainElement).minWidth) : NaN; + return main ? { + mainLeft: main.left, + mainRight: main.right, + mainWidth: main.width, + minWidth, + scrollWidth: document.documentElement.scrollWidth, + clientWidth: document.documentElement.clientWidth, + } : null; + }); + assert(narrow, 'main content must exist at a narrow viewport'); + assert(Number.isFinite(narrow.minWidth) && narrow.minWidth > 0, + 'main content must define a fixed positive minimum width'); + assert(narrow.mainWidth + 1 >= narrow.minWidth, + 'rendered main content must honor its fixed minimum width'); + assert(narrow.mainLeft >= -1 && narrow.mainRight <= narrow.clientWidth + 1, + 'main content must remain fully visible, not clipped to hide overflow'); + assert(narrow.scrollWidth <= narrow.clientWidth + 1, 'narrow viewport must not expose horizontal page scrolling'); + await page.screenshot({path: '/logs/verifier/visual-audit/narrow-content.png', fullPage: true}); + const sidebar = page.locator('[data-testid="sidebar"]'); + const initiallyOpen = await sidebar.evaluate(element => { + const rect = element.getBoundingClientRect(), style = getComputedStyle(element); + return style.display !== 'none' && style.visibility !== 'hidden' && rect.right > 40 && rect.left < innerWidth; + }); + if (!initiallyOpen) { + await page.locator('[data-testid="sidebar-toggle"]').click(); + await page.waitForFunction(() => { + const el = document.querySelector('[data-testid="sidebar"]'); + const rect = el.getBoundingClientRect(), style = getComputedStyle(el); + return style.display !== 'none' && style.visibility !== 'hidden' && rect.right > 40; + }, null, {timeout: 3000}); + } + await page.screenshot({path: '/logs/verifier/visual-audit/narrow-open.png', fullPage: true}); + await page.locator('[data-testid="sidebar-toggle"]').click(); + await waitForCollapsedSidebar(page, '[data-testid="sidebar"]', 240); + await page.screenshot({path: '/logs/verifier/visual-audit/narrow-closed.png', fullPage: true}); + + await page.setViewportSize({ width: 1800, height: 900 }); + await page.goto(entryUrl, { waitUntil: 'domcontentloaded' }); + const wide = await page.evaluate(() => { + const sidebar = document.querySelector('[data-testid="sidebar"]')?.getBoundingClientRect(); + const main = document.querySelector('[data-testid="main-content"]')?.getBoundingClientRect(); + return sidebar && main ? { + sidebarLeft: sidebar.left, + sidebarRight: sidebar.right, + mainCenter: main.left + main.width / 2, + viewportWidth: document.documentElement.clientWidth, + } : null; + }); + assert(wide, 'sidebar and main content must exist at a wide viewport'); + assert(wide.sidebarLeft <= 1, 'wide viewport sidebar must remain left aligned'); + const availableCenter = (wide.sidebarRight + wide.viewportWidth) / 2; + assert(Math.abs(wide.mainCenter - availableCenter) <= 2, 'main content must be centered in the area beside the sidebar'); + }); + } finally { + await browser.close(); + } +})().catch((error) => { + console.error(error && error.stack || error); + process.exit(1); +}); diff --git a/task_018/tests/validate_semantics.js b/task_018/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_018/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_018/tests/validate_ui_behavior.js b/task_018/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..f7ea038b1aae16cae9e47396c7d3ab980a38567a --- /dev/null +++ b/task_018/tests/validate_ui_behavior.js @@ -0,0 +1,59 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage(); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + await page.setViewportSize({ width: 1200, height: 800 }); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + let boxes = await page.evaluate(() => { + const toBox = rect => ({ left: rect.left, right: rect.right, width: rect.width }); + const sidebar = toBox(document.querySelector('[data-testid="sidebar"]').getBoundingClientRect()); + const main = toBox(document.querySelector('[data-testid="main-content"]').getBoundingClientRect()); + return { sidebar, main, scrollWidth: document.documentElement.scrollWidth, clientWidth: document.documentElement.clientWidth }; + }); + if (!(boxes.sidebar.left <= 2 && boxes.main.left > boxes.sidebar.right - 1)) { + throw new Error('sidebar must be left of main content in horizontal layout'); + } + await page.locator('[data-testid="sidebar-toggle"]').click(); + await page.waitForFunction(() => { + const el = document.querySelector('[data-testid="sidebar"]'); + const rect = el.getBoundingClientRect(); + const style = getComputedStyle(el); + return Math.max(0, Math.min(innerWidth, rect.right) - Math.max(0, rect.left)) < 40 || + style.display === 'none' || style.visibility === 'hidden'; + }, null, {timeout: 3000}); + const collapsed = await page.locator('[data-testid="sidebar"]').evaluate(el => { + const rect = el.getBoundingClientRect(); + const style = getComputedStyle(el); + const visibleWidth = Math.max(0, Math.min(innerWidth, rect.right) - Math.max(0, rect.left)); + return visibleWidth < 40 || style.display === 'none' || style.visibility === 'hidden'; + }); + if (!collapsed) throw new Error('sidebar toggle did not collapse the sidebar'); + await page.setViewportSize({ width: 640, height: 800 }); + await page.waitForTimeout(150); + boxes = await page.evaluate(() => { + const rect = document.querySelector('[data-testid="main-content"]').getBoundingClientRect(); + const main = { left: rect.left, right: rect.right, width: rect.width }; + return { main, scrollWidth: document.documentElement.scrollWidth, clientWidth: document.documentElement.clientWidth }; + }); + if (boxes.scrollWidth > boxes.clientWidth + 1) throw new Error('narrow viewport should not create horizontal page scroll'); + if (boxes.main.width <= 0) throw new Error('main content should keep a positive minimum width'); + await page.setViewportSize({ width: 1600, height: 900 }); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(150); + boxes = await page.evaluate(() => { + const toBox = rect => ({ left: rect.left, right: rect.right, width: rect.width }); + const sidebar = toBox(document.querySelector('[data-testid="sidebar"]').getBoundingClientRect()); + const main = toBox(document.querySelector('[data-testid="main-content"]').getBoundingClientRect()); + return { sidebar, main, clientWidth: document.documentElement.clientWidth }; + }); + const mainCenter = boxes.main.left + boxes.main.width / 2; + if (boxes.sidebar.left > 2) throw new Error('wide viewport sidebar should remain left aligned'); + const availableCenter = (boxes.sidebar.right + boxes.clientWidth) / 2; + if (Math.abs(mainCenter - availableCenter) > 2) throw new Error('wide content is not centered beside the sidebar'); + if (errors.length) throw new Error(errors.join(' | ')); + await browser.close(); +})().catch(err => { console.error(err && err.stack || err); process.exit(1); }); diff --git a/task_019/acceptance_checklist.json b/task_019/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..675d0ad8d604e5e9372727e949657d3e328d0623 --- /dev/null +++ b/task_019/acceptance_checklist.json @@ -0,0 +1,22 @@ +{ + "task_id": 30, + "category": "ui_optimization", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Targets the specific UI defect described by the user.", + "Preserves surrounding behavior and avoids unrelated rewrites.", + "Uses responsive layout checks where the prompt mentions viewport size." + ], + "input_assets": [ + "index.html" + ], + "expected_outputs": [], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns.", + "A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_019/environment/Dockerfile b/task_019/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_019/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_019/environment/code/index.html b/task_019/environment/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..131084b9b8c4f74c4d80bc6c54b9c5b87c20d829 --- /dev/null +++ b/task_019/environment/code/index.html @@ -0,0 +1,32 @@ + + + + + Sidebar Spacing Fixture + + + +
      + +
      +
      + +
      Placeholder
      +
      +
      +
      + + + diff --git a/task_019/environment/docker-compose.yaml b/task_019/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_019/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_019/instruction.md b/task_019/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..04cdf4f9159376ee1044c7b555fe7ac2c03bbb06 --- /dev/null +++ b/task_019/instruction.md @@ -0,0 +1,15 @@ +# Consistent sidebar and content spacing + +Adjust the supplied root `index.html` so the content has a consistent horizontal inset as the sidebar is toggled and the window resizes. Preserve the existing page and sidebar controls; run directly offline. Keep `data-testid` values `sidebar`, `toggle-sidebar`, `content-shell`, `main-content`, and `placeholder`. + +## Layout requirements + +- With the sidebar collapsed, keep at least 64 px between the viewport's left edge and the main column. In the small-window initial view, keep at least 64 px between the content shell's left edge and the placeholder. +- With the sidebar expanded, keep at least 64 px between its right edge and the main column. +- In a wide window, center the column in the available area: between the sidebar's right edge and the viewport's right edge when expanded, or within the viewport when collapsed. Use any CSS layout that produces these positions. + +## Acceptance Checklist + +- The small-window placeholder is inset by at least 64 px. +- The expanded sidebar leaves at least 64 px before the main column, and the column is centered in the remaining space at a wide viewport. +- Collapsing the sidebar preserves the main column's left inset. The page stays usable without network requests or browser errors. diff --git a/task_019/provenance/restoration_notes.md b/task_019/provenance/restoration_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..d23b8703c3b6be7e98a1c109a30890e811ab8cec --- /dev/null +++ b/task_019/provenance/restoration_notes.md @@ -0,0 +1,11 @@ +# Restoration Notes for task_030 + +- 官方轨迹形态:existing layout responsive spacing fix +- v1 主要损失:核心 bounding-box 测试较好,但缺少截图和真实项目 CSS 复杂度。 +- v2 改动:仅补 provenance;建议后续加截图 artifact。 + +## 代表性用户轮次 + +1. 折叠侧边栏时内容紧贴左边,需要 64px。 +2. 小窗口 placeholder、大窗口居中、展开时 sidebar/content gap 都要兼顾。 +3. 多轮有运行日志和布局反馈。 diff --git a/task_019/provenance/user_turns.json b/task_019/provenance/user_turns.json new file mode 100644 index 0000000000000000000000000000000000000000..53e580b487be31379ad9e63f06b254dd46bf3185 --- /dev/null +++ b/task_019/provenance/user_turns.json @@ -0,0 +1,16 @@ +{ + "task_id": 30, + "source": "HF CC-Bench-trajectories sampled metadata; public Dataset Server may differ from local GLM-4.6 source table", + "trajectory_type": "multi-turn", + "data": { + "category": "ui_optimization", + "official_task_shape": "existing layout responsive spacing fix", + "representative_user_turns": [ + "折叠侧边栏时内容紧贴左边,需要 64px。", + "小窗口 placeholder、大窗口居中、展开时 sidebar/content gap 都要兼顾。", + "多轮有运行日志和布局反馈。" + ], + "loss_in_v1": "核心 bounding-box 测试较好,但缺少截图和真实项目 CSS 复杂度。", + "v2_change": "仅补 provenance;建议后续加截图 artifact。" + } +} diff --git a/task_019/quality_notes.md b/task_019/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..8da9186e00ac25a6fdb20000e9bb7861ad049825 --- /dev/null +++ b/task_019/quality_notes.md @@ -0,0 +1,4 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. \ No newline at end of file diff --git a/task_019/solution/README.md b/task_019/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_019/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_019/solution/code/index.html b/task_019/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..e19914ef1482a8df73c72bcd788959f59d059f38 --- /dev/null +++ b/task_019/solution/code/index.html @@ -0,0 +1,5 @@ + +Sidebar Spacing

      Sidebar spacing

      Main contentThe content area keeps comfortable breathing room whether the sidebar is expanded or collapsed.
      diff --git a/task_019/solution/solve.sh b/task_019/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_019/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_019/task.toml b/task_019/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_019/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_019/task_meta.json b/task_019/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..fd1d47970d1d525b2ec847b62e15a2b4fc7477f9 --- /dev/null +++ b/task_019/task_meta.json @@ -0,0 +1,25 @@ +{ + "task_id": 30, + "task_category": "ui_optimization", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 21, + "language": "javascript", + "tool_files_from_selected_trace": [ + "AIContentArea.tsx", + "LayoutWindow.tsx", + "MainContentArea.tsx", + "NavigationSidebar.tsx", + "TopNavigation.tsx", + "ai-state-machine.ts", + "globals.css", + "layout.tsx" + ], + "input_assets": [ + "index.html" + ], + "expected_outputs": [], + "source_row_id": 180, + "repair_revision": "2026-09-29", + "instruction_sha256": "44f7cfb8e57174f922db33c468b9c2ec36e73fa619b14f1d51ba2d020382687c" +} diff --git a/task_019/tests/_shared/contract_checker.js b/task_019/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_019/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_019/tests/_shared/static_enhancer.sh b/task_019/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_019/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_019/tests/enhancement_cases.json b/task_019/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..667e346367c67153631c80af09a546ccd83dbcbd --- /dev/null +++ b/task_019/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "初始状态下,小窗口时,Placeholder 也贴边了,同样需要 64px 的边距", + "validator": "tests/validate_enhanced_cases.js#ENHANCED_CASE_1", + "behavior": "At the initial small viewport, the fixture placeholder is at least 64px from the content shell's left edge." + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "修复后布局必须在 sidebar 折叠时保留至少 64px 左边距;小窗口下 placeholder 不能贴左边;大窗口下内容区保持居中;sidebar 展开时 sidebar 与 content 的间距至少 64px。", + "validator": "tests/validate_enhanced_cases.js#ENHANCED_CASE_2", + "behavior": "With the sidebar expanded at a large viewport, the content gap is at least 64px and the content is centered within the available shell." + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "当侧边栏被折叠时,内容区紧贴着左边框。我希望有一个 64px 的边距。", + "validator": "tests/validate_enhanced_cases.js#ENHANCED_CASE_3", + "behavior": "After the fixture sidebar is collapsed, main content retains at least 64px of left inset." + } +] diff --git a/task_019/tests/test.sh b/task_019/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ab2150eb79f6f15b53d20b21738b84bbe0d8003 --- /dev/null +++ b/task_019/tests/test.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_ui_behavior.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_019/tests/validate_aaav_dynamic.js b/task_019/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..8082dd22a8346d789ae77096ead5dfece635507e --- /dev/null +++ b/task_019/tests/validate_aaav_dynamic.js @@ -0,0 +1,148 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 30; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_019/tests/validate_browser_smoke.js b/task_019/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_019/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_019/tests/validate_enhanced_cases.js b/task_019/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..5966018a1b0095fd642628f3fb8b6cd6b3e18db3 --- /dev/null +++ b/task_019/tests/validate_enhanced_cases.js @@ -0,0 +1,167 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +const fs = require('node:fs'); +fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + +const entryUrl = pathToFileURL(path.join(process.cwd(), 'index.html')).href; +const seed = Number.parseInt(process.env.ENHANCED_SEED || '30031', 10); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +async function runCase(browser, name, viewport, validate) { + const context = await browser.newContext({ viewport }); + const networkAttempts = []; + await context.route('**/*', async (route) => { + const url = route.request().url(); + if (/^https?:/i.test(url)) { + networkAttempts.push(url); + await route.abort('blockedbyclient'); + return; + } + await route.continue(); + }); + await context.addInitScript(({ fixedSeed }) => { + let state = fixedSeed >>> 0; + Math.random = () => { + state = (state * 1664525 + 1013904223) >>> 0; + return state / 0x100000000; + }; + }, { fixedSeed: seed }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on('pageerror', (error) => errors.push(error.message)); + try { + await page.goto(entryUrl, { waitUntil: 'domcontentloaded' }); + await validate(page); + await page.screenshot({path: `/logs/verifier/visual-audit/${name}.png`, fullPage: true}); + assert(networkAttempts.length === 0, `${name}: external network request attempted`); + assert(errors.length === 0, `${name}: browser errors: ${errors.join(' | ')}`); + console.log(`${name} passed`); + } finally { + await context.close(); + } +} + +async function waitForCollapsedSidebar(page, selector, initialVisibleWidth) { + await page.evaluate(({ selector, initialVisibleWidth }) => new Promise((resolve, reject) => { + const deadline = performance.now() + 4500; + let lastWidth = initialVisibleWidth; + let stableFrames = 0; + let reduced = false; + const sample = () => { + const element = document.querySelector(selector); + if (!element) { + reject(new Error('fixture sidebar must exist')); + return; + } + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + const visibleWidth = Math.max(0, Math.min(innerWidth, rect.right) - Math.max(0, rect.left)); + reduced = visibleWidth < 40 || style.display === 'none' || style.visibility === 'hidden'; + stableFrames = reduced && Math.abs(visibleWidth - lastWidth) < 0.01 ? stableFrames + 1 : 0; + lastWidth = visibleWidth; + if (reduced && stableFrames >= 4) resolve(); + else if (performance.now() >= deadline) reject(new Error('sidebar did not reach a stable collapsed state')); + else requestAnimationFrame(sample); + }; + sample(); + }), { selector, initialVisibleWidth }); +} + +(async () => { + assert(Number.isInteger(seed), 'ENHANCED_SEED must be a fixed integer'); + const browser = await chromium.launch({ + headless: true, + args: ['--no-sandbox', '--disable-background-networking', '--disable-component-update', '--no-first-run'], + }); + try { + // ENHANCED_CASE_1: the initial small-window placeholder keeps the requested inset. + await runCase(browser, 'ENHANCED_CASE_1', { width: 500, height: 700 }, async (page) => { + const inset = await page.evaluate(() => { + const shell = document.querySelector('[data-testid="content-shell"]')?.getBoundingClientRect(); + const placeholder = document.querySelector('[data-testid="placeholder"]')?.getBoundingClientRect(); + return shell && placeholder ? placeholder.left - shell.left : null; + }); + assert(inset !== null, 'fixture content shell and placeholder must exist'); + assert(inset >= 63.5, `small-window placeholder must keep at least 64px from the content edge; got ${inset}`); + }); + + // ENHANCED_CASE_2: expanded sidebar spacing remains at least 64px and content is centered. + await runCase(browser, 'ENHANCED_CASE_2', { width: 1600, height: 800 }, async (page) => { + const layout = await page.evaluate(() => { + const sidebar = document.querySelector('[data-testid="sidebar"]')?.getBoundingClientRect(); + const shellElement = document.querySelector('[data-testid="content-shell"]'); + const shell = shellElement?.getBoundingClientRect(); + const content = document.querySelector('[data-testid="main-content"]')?.getBoundingClientRect(); + const paddingLeft = shellElement ? parseFloat(getComputedStyle(shellElement).paddingLeft) || 0 : 0; + return sidebar && shell && content ? { + gap: content.left - sidebar.right, + contentCenter: content.left + content.width / 2, + availableCenter: (sidebar.right + innerWidth) / 2, + } : null; + }); + assert(layout, 'fixture sidebar, shell, and content must exist'); + assert(layout.gap >= 63.5, `expanded sidebar/content gap must be at least 64px; got ${layout.gap}`); + assert(Math.abs(layout.contentCenter - layout.availableCenter) <= 2, 'large-window content must be centered in the visible area beside the sidebar'); + }); + + // ENHANCED_CASE_3: collapsed content still retains at least 64px on its left. + await runCase(browser, 'ENHANCED_CASE_3', { width: 900, height: 700 }, async (page) => { + const initialSidebar = await page.locator('[data-testid="sidebar"]').evaluate((element) => { + const rect = element.getBoundingClientRect(); + return Math.max(0, Math.min(innerWidth, rect.right) - Math.max(0, rect.left)); + }); + assert(initialSidebar > 1, 'sidebar must initially be visible'); + await page.locator('[data-testid="toggle-sidebar"]').click(); + await waitForCollapsedSidebar(page, '[data-testid="sidebar"]', initialSidebar); + const layout = await page.evaluate(() => { + const sidebar = document.querySelector('[data-testid="sidebar"]')?.getBoundingClientRect(); + const content = document.querySelector('[data-testid="main-content"]')?.getBoundingClientRect(); + return sidebar && content ? { contentLeft: content.left } : null; + }); + assert(layout, 'fixture sidebar and content must exist'); + assert(layout.contentLeft >= 63.5, `collapsed content must keep at least 64px from the left edge; got ${layout.contentLeft}`); + + await page.setViewportSize({width: 1600, height: 800}); + const wideSidebarWidth = await page.locator('[data-testid="sidebar"]').evaluate(async element => { + const started = performance.now(); + let previous = Number.NaN; + let stableFrames = 0; + while (performance.now() - started < 4500) { + await new Promise(requestAnimationFrame); + const frame = element.getBoundingClientRect(); + const style = getComputedStyle(element); + const hidden = style.display === 'none' || style.visibility === 'hidden'; + const visible = hidden ? 0 : Math.max(0, Math.min(innerWidth, frame.right) - Math.max(0, frame.left)); + stableFrames = Math.abs(visible - previous) < .05 ? stableFrames + 1 : 0; + previous = visible; + if (stableFrames >= 4 && performance.now() - started >= 150) return visible; + } + throw Error('sidebar did not settle after the viewport resized'); + }); + if (wideSidebarWidth >= 40) { + await page.waitForFunction(() => { + const sidebar = document.querySelector('[data-testid="sidebar"]').getBoundingClientRect(); + const content = document.querySelector('[data-testid="main-content"]').getBoundingClientRect(); + return content.left - sidebar.right >= 63.5 && + Math.abs(content.left + content.width / 2 - (sidebar.right + innerWidth) / 2) <= 2; + }, null, {timeout: 4500}); + await page.locator('[data-testid="toggle-sidebar"]').click(); + } + await waitForCollapsedSidebar(page, '[data-testid="sidebar"]', wideSidebarWidth); + await page.waitForFunction(() => { + const {left, width} = document.querySelector('[data-testid="main-content"]').getBoundingClientRect(); + return left >= 63.5 && Math.abs(left + width / 2 - innerWidth / 2) <= 2; + }, null, {timeout: 4500}); + }); + } finally { + await browser.close(); + } +})().catch((error) => { + console.error(error && error.stack || error); + process.exit(1); +}); diff --git a/task_019/tests/validate_semantics.js b/task_019/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_019/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_019/tests/validate_ui_behavior.js b/task_019/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..2ef2070426bf354dd678a0f0d53d27d2b285a624 --- /dev/null +++ b/task_019/tests/validate_ui_behavior.js @@ -0,0 +1,25 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage(); + await page.setViewportSize({ width: 500, height: 700 }); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + let small = await page.locator('[data-testid="placeholder"]').boundingBox(); + if (!small || small.x < 63) throw new Error(`small-window placeholder should keep 64px left margin, x=${small && small.x}`); + await page.setViewportSize({ width: 1200, height: 800 }); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + let expanded = await page.evaluate(() => { + const sidebar = document.querySelector('[data-testid="sidebar"]').getBoundingClientRect(); + const content = document.querySelector('[data-testid="main-content"]').getBoundingClientRect(); + return { gap: content.left - sidebar.right, contentLeft: content.left, contentWidth: content.width, viewport: innerWidth, sidebarRight: sidebar.right }; + }); + if (expanded.gap < 63) throw new Error(`expanded sidebar/content gap should be at least 64px, got ${expanded.gap}`); + const expandedCenter = expanded.contentLeft + expanded.contentWidth / 2; + await page.locator('[data-testid="toggle-sidebar"]').click(); + await page.waitForTimeout(150); + let collapsed = await page.locator('[data-testid="main-content"]').boundingBox(); + if (!collapsed || collapsed.x < 63) throw new Error(`collapsed content should keep 64px left margin, x=${collapsed && collapsed.x}`); + await browser.close(); +})().catch(err => { console.error(err && err.stack || err); process.exit(1); }); diff --git a/task_020/acceptance_checklist.json b/task_020/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..cf8eb2881b599061d015b063d3b2d16aad8c74e1 --- /dev/null +++ b/task_020/acceptance_checklist.json @@ -0,0 +1,22 @@ +{ + "task_id": 31, + "category": "ui_optimization", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Targets the specific UI defect described by the user.", + "Preserves surrounding behavior and avoids unrelated rewrites.", + "Uses responsive layout checks where the prompt mentions viewport size." + ], + "input_assets": [ + "index.html" + ], + "expected_outputs": [], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns.", + "A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_020/environment/Dockerfile b/task_020/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_020/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_020/environment/code/index.html b/task_020/environment/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..639a032a31f3b3cad4f0c0048e061ee3ec74aa0a --- /dev/null +++ b/task_020/environment/code/index.html @@ -0,0 +1,35 @@ + + + + + Demo 1001 Layout Gap Fixture + + + +
      + +
      +
      + + + +
      +
      +
      + + + diff --git a/task_020/environment/docker-compose.yaml b/task_020/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_020/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_020/instruction.md b/task_020/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6e341d501936030360919b6b169f449d8da5592f --- /dev/null +++ b/task_020/instruction.md @@ -0,0 +1,13 @@ +# Flush sidebar-to-content layout + +Fix the supplied demo layout in the root `index.html`, which must open directly offline. With the sidebar open, the content shell starts at its right edge. Remove the shell's 40 px left padding and do not recreate the gap through child margins or offsets. + +## Sidebar and composer behavior + +The sidebar toggles between a visible expanded panel and a fully collapsed panel with no visible width. Keep the toggle accessible in both states. During collapse the content must not first jump right. Revealing the prompt input must not reopen a collapsed sidebar. Preserve the starter controls and hooks, including `sidebar`, `collapse-sidebar`, `content-shell`, `main-content`, `show-prompt`, and `prompt-input`. The choice of CSS classes is unrestricted. + +## Acceptance Checklist + +- With the sidebar open, no layout gap or old left inset remains between the sidebar and the content. Content does not shift right while collapsing. +- Revealing the composer leaves a collapsed sidebar closed. +- At both 360 px and 960 px, the sidebar can repeatedly expand and collapse, and the prompt input remains editable with both edges inside the viewport, including when the sidebar is open. diff --git a/task_020/quality_notes.md b/task_020/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..8da9186e00ac25a6fdb20000e9bb7861ad049825 --- /dev/null +++ b/task_020/quality_notes.md @@ -0,0 +1,4 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. \ No newline at end of file diff --git a/task_020/solution/README.md b/task_020/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_020/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_020/solution/code/index.html b/task_020/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..c17ec45335000a76a93093bc2fd4bec67db11c7c --- /dev/null +++ b/task_020/solution/code/index.html @@ -0,0 +1,35 @@ + + + + + Demo 1001 Layout Gap Fixture + + + +
      + +
      +
      + + + +
      +
      +
      + + + diff --git a/task_020/solution/solve.sh b/task_020/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_020/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_020/task.toml b/task_020/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_020/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_020/task_meta.json b/task_020/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..59621aab1d463918a339edd2f056f0318d30037e --- /dev/null +++ b/task_020/task_meta.json @@ -0,0 +1,29 @@ +{ + "task_id": 31, + "task_category": "ui_optimization", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 13, + "language": "javascript", + "tool_files_from_selected_trace": [ + ".env.example", + ".env.local", + "AIContentArea.tsx", + "AddBlockPlaceholder.tsx", + "LayoutWindow.tsx", + "MainContentArea.tsx", + "NavigationSidebar.tsx", + "PromptResponseBlock.tsx", + "agent-config.ts", + "ai-state-machine.ts", + "package.json", + "page.tsx" + ], + "input_assets": [ + "index.html" + ], + "expected_outputs": [], + "source_row_id": 186, + "repair_revision": "2026-09-29", + "instruction_sha256": "b489c7cad1127bfb19f115ade1fce6f62abef6e528ecb7c93e4db98f6938d3af" +} diff --git a/task_020/tests/_shared/contract_checker.js b/task_020/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_020/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_020/tests/_shared/static_enhancer.sh b/task_020/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_020/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_020/tests/enhancement_cases.json b/task_020/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..b1eab5f185717e6e68b318ad4b5e9dfd7c9a00a2 --- /dev/null +++ b/task_020/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "把侧边栏和内容之间的空隙去掉", + "validator": "tests/validate_enhanced_cases.js#ENHANCED_CASE_1", + "behavior": "The fixture content shell begins exactly where the sidebar ends, with no visible gap." + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "内容左边有 40padding 也去掉", + "validator": "tests/validate_enhanced_cases.js#ENHANCED_CASE_2", + "behavior": "The computed left padding of the fixture main content is zero." + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "当 prompt input 出现时保持 collapsed-sidebar 状态;折叠 sidebar 时避免出现瞬时右移。", + "validator": "tests/validate_enhanced_cases.js#ENHANCED_CASE_3", + "behavior": "During collapse, sampled content positions never move right; subsequently showing the prompt visibly preserves the collapsed sidebar state." + } +] diff --git a/task_020/tests/review_hard.js b/task_020/tests/review_hard.js new file mode 100644 index 0000000000000000000000000000000000000000..c318f18ce18d79623f38f83eea7a4833883f315a --- /dev/null +++ b/task_020/tests/review_hard.js @@ -0,0 +1,40 @@ +const { chromium } = require('playwright'); +const assert = require('assert'); +const fs = require('node:fs'); + +(async () => { + const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] }); + try { + const page = await browser.newPage(); + await page.goto('file://' + process.argv[2] + '/index.html'); + await page.locator('[data-testid="show-prompt"]').click(); + const input = page.locator('[data-testid="prompt-input"]').first(); + const sidebar = page.locator('[data-testid="sidebar"]'); + const toggle = page.locator('[data-testid="collapse-sidebar"]'); + fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + async function waitForState(collapsed) { + await page.waitForFunction(expected => { + const el = document.querySelector('[data-testid="sidebar"]'); + const rect = el.getBoundingClientRect(), style = getComputedStyle(el); + const width = style.display === 'none' || style.visibility === 'hidden' ? 0 : Math.max(0, Math.min(innerWidth, rect.right) - Math.max(0, rect.left)); + return expected ? width <= 2 : width > 40; + }, collapsed, {timeout: 5000}); + } + for (const width of [360, 960]) { + await page.setViewportSize({ width, height: 700 }); + for (let round = 0; round < 3; round++) { + await toggle.click(); + await waitForState(true); + await toggle.click(); + await waitForState(false); + } + await input.fill('still usable'); + assert.equal(await input.inputValue(), 'still usable'); + const box = await input.boundingBox(); + assert(box && box.x >= -1 && box.x + box.width <= width + 1, 'prompt input must remain within the viewport'); + await page.screenshot({path: `/logs/verifier/visual-audit/usable-${width}.png`, fullPage: true}); + } + } finally { + await browser.close(); + } +})().catch(error => { console.error(error); process.exit(1); }); diff --git a/task_020/tests/review_legacy.sh b/task_020/tests/review_legacy.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ab2150eb79f6f15b53d20b21738b84bbe0d8003 --- /dev/null +++ b/task_020/tests/review_legacy.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_ui_behavior.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_020/tests/test.sh b/task_020/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..76fc765a05dd75147adf1b8ebc40310dee2c11b4 --- /dev/null +++ b/task_020/tests/test.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -uo pipefail +bash /tests/review_legacy.sh +CORE=$(cat /logs/verifier/reward.txt 2>/dev/null || echo 0) +mkdir -p /logs/verifier +node /tests/review_hard.js /app 2>&1 | tee /logs/verifier/review_hard.log +RC=${PIPESTATUS[0]} +if [ "$RC" -ne 0 ]; then echo "REVIEW_HARD failed with exit code $RC"; fi +if [ "$RC" -eq 0 ]; then echo "$CORE"; else echo 0; fi > /logs/verifier/reward.txt +exit 0 diff --git a/task_020/tests/validate_aaav_dynamic.js b/task_020/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..81bd31a12431339806984b368346832cdfbfb265 --- /dev/null +++ b/task_020/tests/validate_aaav_dynamic.js @@ -0,0 +1,148 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 31; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_020/tests/validate_browser_smoke.js b/task_020/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_020/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_020/tests/validate_enhanced_cases.js b/task_020/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..0a8df508268fe4821c66515ba4e7ea981f276296 --- /dev/null +++ b/task_020/tests/validate_enhanced_cases.js @@ -0,0 +1,168 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const entryUrl = pathToFileURL(path.join(process.cwd(), 'index.html')).href; +const seed = Number.parseInt(process.env.ENHANCED_SEED || '31031', 10); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +async function runCase(browser, name, validate) { + const context = await browser.newContext({ viewport: { width: 1200, height: 800 } }); + const networkAttempts = []; + await context.route('**/*', async (route) => { + const url = route.request().url(); + if (/^https?:/i.test(url)) { + networkAttempts.push(url); + await route.abort('blockedbyclient'); + return; + } + await route.continue(); + }); + await context.addInitScript(({ fixedSeed }) => { + let state = fixedSeed >>> 0; + Math.random = () => { + state = (state * 1664525 + 1013904223) >>> 0; + return state / 0x100000000; + }; + }, { fixedSeed: seed }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on('pageerror', (error) => errors.push(error.message)); + try { + await page.goto(entryUrl, { waitUntil: 'domcontentloaded' }); + await validate(page); + assert(networkAttempts.length === 0, `${name}: external network request attempted`); + assert(errors.length === 0, `${name}: browser errors: ${errors.join(' | ')}`); + console.log(`${name} passed`); + } finally { + await context.close(); + } +} + +async function waitForCollapsedSidebar(page, selector, initialVisibleWidth) { + await page.evaluate(({ selector, initialVisibleWidth }) => new Promise((resolve, reject) => { + const deadline = performance.now() + 4500; + let lastWidth = initialVisibleWidth; + let stableFrames = 0; + let reduced = false; + const sample = () => { + const element = document.querySelector(selector); + if (!element) { + reject(new Error('fixture sidebar must exist')); + return; + } + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + const visibleWidth = Math.max(0, Math.min(innerWidth, rect.right) - Math.max(0, rect.left)); + reduced = reduced || visibleWidth < initialVisibleWidth - 1 || style.display === 'none' || + style.visibility === 'hidden' || element.getAttribute('aria-hidden') === 'true'; + stableFrames = reduced && Math.abs(visibleWidth - lastWidth) < 0.01 ? stableFrames + 1 : 0; + lastWidth = visibleWidth; + if (reduced && stableFrames >= 4) resolve(); + else if (performance.now() >= deadline) reject(new Error('sidebar did not reach a stable collapsed state')); + else requestAnimationFrame(sample); + }; + sample(); + }), { selector, initialVisibleWidth }); +} + +(async () => { + assert(Number.isInteger(seed), 'ENHANCED_SEED must be a fixed integer'); + const browser = await chromium.launch({ + headless: true, + args: ['--no-sandbox', '--disable-background-networking', '--disable-component-update', '--no-first-run'], + }); + try { + // ENHANCED_CASE_1: the sidebar and content shell have no intervening gap. + await runCase(browser, 'ENHANCED_CASE_1', async (page) => { + const gap = await page.evaluate(() => { + const sidebar = document.querySelector('[data-testid="sidebar"]')?.getBoundingClientRect(); + const shell = document.querySelector('[data-testid="content-shell"]')?.getBoundingClientRect(); + return sidebar && shell ? shell.left - sidebar.right : null; + }); + assert(gap !== null, 'fixture sidebar and content shell must exist'); + assert(Math.abs(gap) <= 1, `sidebar/content gap must be removed; got ${gap}`); + }); + + // ENHANCED_CASE_2: the former 40px content-left padding is fully removed. + await runCase(browser, 'ENHANCED_CASE_2', async (page) => { + const paddingLeft = await page.locator('[data-testid="main-content"]').evaluate((element) => + parseFloat(getComputedStyle(element).paddingLeft) || 0); + assert(paddingLeft <= 1, `content left padding must be removed; got ${paddingLeft}px`); + const visualInset = await page.evaluate(() => { + const shell = document.querySelector('[data-testid="content-shell"]').getBoundingClientRect(); + const button = document.querySelector('[data-testid="collapse-sidebar"]').getBoundingClientRect(); + return button.left - shell.left; + }); + assert(visualInset <= 8, `content children must not recreate the removed 40px inset; got ${visualInset}px`); + }); + + // ENHANCED_CASE_3: collapsing never shifts content right and prompt display preserves collapse. + await runCase(browser, 'ENHANCED_CASE_3', async (page) => { + const shell = page.locator('[data-testid="content-shell"]'); + const initialLeft = await shell.evaluate((element) => element.getBoundingClientRect().left); + const initialSidebarWidth = await page.locator('[data-testid="sidebar"]').evaluate((element) => { + const rect = element.getBoundingClientRect(); + return Math.max(0, Math.min(innerWidth, rect.right) - Math.max(0, rect.left)); + }); + assert(initialSidebarWidth > 1, 'sidebar must initially be visible'); + await page.evaluate(() => { + window.__enhancedCollapseSamples = []; + window.__enhancedSampling = true; + const sample = () => { + const element = document.querySelector('[data-testid="content-shell"]'); + if (element) window.__enhancedCollapseSamples.push(element.getBoundingClientRect().left); + if (window.__enhancedSampling) requestAnimationFrame(sample); + }; + sample(); + }); + await page.locator('[data-testid="collapse-sidebar"]').click(); + await waitForCollapsedSidebar(page, '[data-testid="sidebar"]', initialSidebarWidth); + const samples = await page.evaluate(() => { + window.__enhancedSampling = false; + return window.__enhancedCollapseSamples.slice(); + }); + assert(samples.length > 0, 'collapse trajectory must produce at least one layout sample'); + assert(samples.every((left) => left <= initialLeft + 1), 'content must not shift right at any sampled point during sidebar collapse'); + + const collapsedSidebarWidth = await page.locator('[data-testid="sidebar"]').evaluate((element) => { + const rect = element.getBoundingClientRect(); + return Math.max(0, Math.min(innerWidth, rect.right) - Math.max(0, rect.left)); + }); + await page.locator('[data-testid="show-prompt"]').click(); + await page.waitForFunction(() => { + const prompt = document.querySelector('[data-testid="prompt-input"]'); + if (!prompt) return false; + const rect = prompt.getBoundingClientRect(); + const style = getComputedStyle(prompt); + return !prompt.hidden && rect.width > 0 && rect.height > 0 && + style.display !== 'none' && style.visibility !== 'hidden'; + }); + const state = await page.evaluate(() => { + const sidebar = document.querySelector('[data-testid="sidebar"]')?.getBoundingClientRect(); + const prompt = document.querySelector('[data-testid="prompt-input"]'); + if (!sidebar || !prompt) return null; + const promptRect = prompt.getBoundingClientRect(); + const promptStyle = getComputedStyle(prompt); + return { + sidebarVisibleWidth: Math.max(0, Math.min(innerWidth, sidebar.right) - Math.max(0, sidebar.left)), + promptVisible: !prompt.hidden && promptRect.width > 0 && promptRect.height > 0 && + promptStyle.display !== 'none' && promptStyle.visibility !== 'hidden', + }; + }); + assert(state, 'fixture sidebar and prompt input must exist'); + assert(state.promptVisible, 'prompt input must become visible'); + assert(state.sidebarVisibleWidth <= collapsedSidebarWidth + 1, + 'showing prompt must preserve collapsed-sidebar state'); + }); + } finally { + await browser.close(); + } +})().catch((error) => { + console.error(error && error.stack || error); + process.exit(1); +}); diff --git a/task_020/tests/validate_semantics.js b/task_020/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_020/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_020/tests/validate_ui_behavior.js b/task_020/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..792cce2c1059d96ca82aed541fc8f01211717eb1 --- /dev/null +++ b/task_020/tests/validate_ui_behavior.js @@ -0,0 +1,32 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1200, height: 800 } }); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + let boxes = await page.evaluate(() => { + const sidebar = document.querySelector('[data-testid="sidebar"]').getBoundingClientRect(); + const shell = document.querySelector('[data-testid="content-shell"]').getBoundingClientRect(); + const content = document.querySelector('[data-testid="main-content"]').getBoundingClientRect(); + const style = getComputedStyle(document.querySelector('[data-testid="main-content"]')); + return { gap: shell.left - sidebar.right, paddingLeft: parseFloat(style.paddingLeft), contentLeft: content.left }; + }); + if (Math.abs(boxes.gap) > 2) throw new Error(`sidebar/content gap should be removed, got ${boxes.gap}`); + if (boxes.paddingLeft > 2) throw new Error(`content left padding should be removed, got ${boxes.paddingLeft}`); + await page.locator('[data-testid="collapse-sidebar"]').click(); + await page.waitForFunction(() => { + const el = document.querySelector('[data-testid=sidebar]'); + const rect = el.getBoundingClientRect(), style = getComputedStyle(el); + return style.display === 'none' || style.visibility === 'hidden' || Math.max(0, Math.min(innerWidth, rect.right) - Math.max(0, rect.left)) <= 2; + }, null, {timeout:5000}); + await page.waitForTimeout(250); + await page.locator('[data-testid="show-prompt"]').click(); + await page.waitForTimeout(150); + const sidebarWidth = await page.locator('[data-testid="sidebar"]').evaluate(el => { + const rect = el.getBoundingClientRect(), style = getComputedStyle(el); + return style.display === 'none' || style.visibility === 'hidden' ? 0 : Math.max(0, Math.min(innerWidth, rect.right) - Math.max(0, rect.left)); + }); + if (sidebarWidth > 2) throw new Error('showing prompt should not re-open a collapsed sidebar'); + await browser.close(); +})().catch(err => { console.error(err && err.stack || err); process.exit(1); }); diff --git a/task_021/acceptance_checklist.json b/task_021/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..ec2c4adbe0a56de13ac59890af7ba088aca6f436 --- /dev/null +++ b/task_021/acceptance_checklist.json @@ -0,0 +1,22 @@ +{ + "task_id": 32, + "category": "ui_optimization", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Targets the specific UI defect described by the user.", + "Preserves surrounding behavior and avoids unrelated rewrites.", + "Uses responsive layout checks where the prompt mentions viewport size." + ], + "input_assets": [ + "index.html" + ], + "expected_outputs": [], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns.", + "A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_021/environment/Dockerfile b/task_021/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_021/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_021/environment/code/index.html b/task_021/environment/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..c0a8bf753de20c4a1e8622fbe8612a011e7a2d7d --- /dev/null +++ b/task_021/environment/code/index.html @@ -0,0 +1,22 @@ + + + + + Component Name Fixture + + + +
      + +
      +
      + +
      Response
      +
      +
      +
      + + + diff --git a/task_021/environment/docker-compose.yaml b/task_021/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_021/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_021/instruction.md b/task_021/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ec5bcdcd36a82b2727f22363f4affa5df3a3b017 --- /dev/null +++ b/task_021/instruction.md @@ -0,0 +1,22 @@ +# Stable names for page components + +Extend the supplied offline `index.html` with a component registry for the existing layout. Keep current styles, controls and interactions. Label each of these DOM elements with its exact `data-component-name`: + +| Component | Element | +| --- | --- | +| `AppShell` | App wrapper | +| `NavigationSidebar` | Sidebar | +| `MainContentArea` | Main content area | +| `PromptResponseBlock` | Prompt/response group | +| `PromptInput` | Editable prompt | +| `AIContentArea` | Response display area | + +## Registry API + +Expose an object at `window.componentRegistry` with these six initial keys, each resolving to the corresponding element. Expose `window.getComponentByName(name)`, returning the actual DOM element from the current registry mapping, or `null` if the name is unknown. Support mappings added or replaced at runtime rather than hard-coding the initial names. The registry's internal value representation is up to you. + +## Acceptance Checklist + +- The offline page renders with each of the six required names present exactly once on the corresponding element. +- Looking up any initial name returns the named DOM element. Unknown names return `null`; added or replaced mappings take effect immediately. +- The named prompt remains editable. diff --git a/task_021/quality_notes.md b/task_021/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..8da9186e00ac25a6fdb20000e9bb7861ad049825 --- /dev/null +++ b/task_021/quality_notes.md @@ -0,0 +1,4 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. \ No newline at end of file diff --git a/task_021/solution/README.md b/task_021/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_021/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_021/solution/code/index.html b/task_021/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..f6a25d5d6d7618f1f44f068c2075ad4449bc235f --- /dev/null +++ b/task_021/solution/code/index.html @@ -0,0 +1,5 @@ + +Component Names +
      Response
      + + diff --git a/task_021/solution/solve.sh b/task_021/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_021/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_021/task.toml b/task_021/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_021/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_021/task_meta.json b/task_021/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..fdd015a3a0c90a64488e3a0b26d6fe0992aee46f --- /dev/null +++ b/task_021/task_meta.json @@ -0,0 +1,34 @@ +{ + "task_id": 32, + "task_category": "ui_optimization", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 9, + "language": "javascript", + "tool_files_from_selected_trace": [ + ".env.example", + ".env.local", + "AIContentArea.tsx", + "AddBlockPlaceholder.tsx", + "LayoutWindow.tsx", + "MainContentArea.tsx", + "NavigationSidebar.tsx", + "PromptResponseBlock.tsx", + "TopNavigation.tsx", + "agent-config.ts", + "agent-integration.ts", + "cli.ts", + "client.ts", + "layout.tsx", + "package.json", + "page.tsx", + "route.ts" + ], + "input_assets": [ + "index.html" + ], + "expected_outputs": [], + "source_row_id": 192, + "repair_revision": "2026-09-29", + "instruction_sha256": "90e39169c9970d6d58333e46b7f9044b3df0cebc7350c5026a9437b15a0ab453" +} diff --git a/task_021/tests/_shared/contract_checker.js b/task_021/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_021/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_021/tests/_shared/static_enhancer.sh b/task_021/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_021/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_021/tests/enhancement_cases.json b/task_021/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..7bab49437c06c5d11c43ad115ca114c51dba8a09 --- /dev/null +++ b/task_021/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "必须使用这 6 个 PascalCase 名称:`AppShell`、`NavigationSidebar`、`MainContentArea`、`PromptResponseBlock`、`PromptInput`、`AIContentArea`。每个名称必须作为 `data-component-name` 值出现一次", + "validator": "tests/validate_enhanced_cases.js#ENHANCED_CASE_1", + "behavior": "Each required layout name—AppShell, NavigationSidebar, and MainContentArea—appears exactly once as a data-component-name value." + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "必须使用这 6 个 PascalCase 名称:`AppShell`、`NavigationSidebar`、`MainContentArea`、`PromptResponseBlock`、`PromptInput`、`AIContentArea`。每个名称必须作为 `data-component-name` 值出现一次", + "validator": "tests/validate_enhanced_cases.js#ENHANCED_CASE_2", + "behavior": "Each required prompt name—PromptResponseBlock, PromptInput, and AIContentArea—appears exactly once as a data-component-name value." + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "全局 `window.componentRegistry` 需要以这 6 个名称作为 key。", + "validator": "tests/validate_enhanced_cases.js#ENHANCED_CASE_3", + "behavior": "window.componentRegistry is an object with all six prescribed PascalCase component names as own keys." + } +] diff --git a/task_021/tests/review_hard.js b/task_021/tests/review_hard.js new file mode 100644 index 0000000000000000000000000000000000000000..367b0c7aa8810fa63bb4d7befd1ca531d24c5042 --- /dev/null +++ b/task_021/tests/review_hard.js @@ -0,0 +1,39 @@ +const {chromium} = require('playwright'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const {pathToFileURL} = require('node:url'); +const path = require('node:path'); + +(async () => { + const browser = await chromium.launch({headless: true, args: ['--no-sandbox']}); + try { + const page = await browser.newPage(); + await page.route(/^https?:/, route => route.abort()); + await page.goto(pathToFileURL(path.join(process.argv[2], 'index.html')).href); + const failures = await page.evaluate(() => { + const failures = []; + const required = ['AppShell', 'NavigationSidebar', 'MainContentArea', 'PromptResponseBlock', 'PromptInput', 'AIContentArea']; + for (const name of required) { + const element = window.getComponentByName(name); + if (!(element instanceof Element) || element !== document.querySelector(`[data-component-name="${name}"]`)) + failures.push(`${name} must resolve to the actual named DOM element`); + } + if (window.getComponentByName('Missing') !== null) failures.push('unknown name must return null'); + window.componentRegistry.Extension = window.componentRegistry.AppShell; + if (window.getComponentByName('Extension') !== window.getComponentByName('AppShell')) failures.push('new mapping was ignored'); + const original = window.componentRegistry.PromptInput; + const target = window.getComponentByName('AIContentArea'); + window.componentRegistry.PromptInput = window.componentRegistry.AIContentArea; + if (window.getComponentByName('PromptInput') !== target) failures.push('updated mapping was ignored'); + window.componentRegistry.PromptInput = original; + delete window.componentRegistry.Extension; + return failures; + }); + assert.deepEqual(failures, []); + await page.locator('[data-component-name="PromptInput"]').fill('registry input remains usable'); + fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + await page.screenshot({path: '/logs/verifier/visual-audit/component-registry.png', fullPage: true}); + } finally { + await browser.close(); + } +})().catch(error => {console.error(error); process.exit(1)}); diff --git a/task_021/tests/review_legacy.sh b/task_021/tests/review_legacy.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ab2150eb79f6f15b53d20b21738b84bbe0d8003 --- /dev/null +++ b/task_021/tests/review_legacy.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_ui_behavior.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_021/tests/test.sh b/task_021/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..76fc765a05dd75147adf1b8ebc40310dee2c11b4 --- /dev/null +++ b/task_021/tests/test.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -uo pipefail +bash /tests/review_legacy.sh +CORE=$(cat /logs/verifier/reward.txt 2>/dev/null || echo 0) +mkdir -p /logs/verifier +node /tests/review_hard.js /app 2>&1 | tee /logs/verifier/review_hard.log +RC=${PIPESTATUS[0]} +if [ "$RC" -ne 0 ]; then echo "REVIEW_HARD failed with exit code $RC"; fi +if [ "$RC" -eq 0 ]; then echo "$CORE"; else echo 0; fi > /logs/verifier/reward.txt +exit 0 diff --git a/task_021/tests/validate_aaav_dynamic.js b/task_021/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..ca90496c94dbc2cd08d9b90ce65e1132d12324a0 --- /dev/null +++ b/task_021/tests/validate_aaav_dynamic.js @@ -0,0 +1,148 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 32; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_021/tests/validate_browser_smoke.js b/task_021/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_021/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_021/tests/validate_enhanced_cases.js b/task_021/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..46928756f5ab35d5377690c64a0377fb6c23896b --- /dev/null +++ b/task_021/tests/validate_enhanced_cases.js @@ -0,0 +1,92 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const entryUrl = pathToFileURL(path.join(process.cwd(), 'index.html')).href; +const seed = Number.parseInt(process.env.ENHANCED_SEED || '32031', 10); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +async function runCase(browser, name, validate) { + const context = await browser.newContext({ viewport: { width: 1000, height: 700 } }); + const networkAttempts = []; + await context.route('**/*', async (route) => { + const url = route.request().url(); + if (/^https?:/i.test(url)) { + networkAttempts.push(url); + await route.abort('blockedbyclient'); + return; + } + await route.continue(); + }); + await context.addInitScript(({ fixedSeed }) => { + let state = fixedSeed >>> 0; + Math.random = () => { + state = (state * 1664525 + 1013904223) >>> 0; + return state / 0x100000000; + }; + }, { fixedSeed: seed }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on('pageerror', (error) => errors.push(error.message)); + try { + await page.goto(entryUrl, { waitUntil: 'domcontentloaded' }); + await validate(page); + assert(networkAttempts.length === 0, `${name}: external network request attempted`); + assert(errors.length === 0, `${name}: browser errors: ${errors.join(' | ')}`); + console.log(`${name} passed`); + } finally { + await context.close(); + } +} + +async function assertNamesAppearOnce(page, names) { + for (const name of names) { + const count = await page.locator(`[data-component-name="${name}"]`).count(); + assert(count === 1, `${name} must occur exactly once as a data-component-name value; got ${count}`); + } +} + +(async () => { + assert(Number.isInteger(seed), 'ENHANCED_SEED must be a fixed integer'); + const browser = await chromium.launch({ + headless: true, + args: ['--no-sandbox', '--disable-background-networking', '--disable-component-update', '--no-first-run'], + }); + try { + // ENHANCED_CASE_1: all required layout component names occur exactly once. + await runCase(browser, 'ENHANCED_CASE_1', async (page) => { + await assertNamesAppearOnce(page, ['AppShell', 'NavigationSidebar', 'MainContentArea']); + }); + + // ENHANCED_CASE_2: all required prompt component names occur exactly once. + await runCase(browser, 'ENHANCED_CASE_2', async (page) => { + await assertNamesAppearOnce(page, ['PromptResponseBlock', 'PromptInput', 'AIContentArea']); + }); + + // ENHANCED_CASE_3: the prescribed component names are exposed as registry keys. + await runCase(browser, 'ENHANCED_CASE_3', async (page) => { + const required = ['AppShell', 'NavigationSidebar', 'MainContentArea', 'PromptResponseBlock', 'PromptInput', 'AIContentArea']; + const registryState = await page.evaluate((names) => { + const registry = window.componentRegistry; + return { + isObject: registry !== null && typeof registry === 'object' && !Array.isArray(registry), + ownKeys: registry && typeof registry === 'object' + ? names.filter((name) => Object.prototype.hasOwnProperty.call(registry, name)) + : [], + }; + }, required); + assert(registryState.isObject, 'window.componentRegistry must be an object'); + assert(required.every(name => registryState.ownKeys.includes(name)), + `window.componentRegistry must expose all six prescribed names; found ${registryState.ownKeys.join(', ')}`); + }); + } finally { + await browser.close(); + } +})().catch((error) => { + console.error(error && error.stack || error); + process.exit(1); +}); diff --git a/task_021/tests/validate_semantics.js b/task_021/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_021/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_021/tests/validate_ui_behavior.js b/task_021/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..7994182b0a7624762d19bca233b69c625607e53c --- /dev/null +++ b/task_021/tests/validate_ui_behavior.js @@ -0,0 +1,21 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1000, height: 700 } }); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + const required = ['AppShell', 'NavigationSidebar', 'MainContentArea', 'PromptResponseBlock', 'PromptInput', 'AIContentArea']; + const names = await page.locator('[data-component-name]').evaluateAll(nodes => nodes.map(n => n.getAttribute('data-component-name'))); + for (const name of required) { + if (!names.includes(name)) throw new Error(`missing data-component-name ${name}`); + } + const duplicates = names.filter((name, index) => names.indexOf(name) !== index); + if (duplicates.length) throw new Error(`component names should be stable and unique: ${duplicates.join(',')}`); + const registry = await page.evaluate(() => window.componentRegistry || window.COMPONENT_REGISTRY || null); + if (!registry || typeof registry !== 'object') throw new Error('component registry should be exposed for future component-name conversations'); + for (const name of required) { + if (!(name in registry)) throw new Error(`component registry missing ${name}`); + } + await browser.close(); +})().catch(err => { console.error(err && err.stack || err); process.exit(1); }); diff --git a/task_022/acceptance_checklist.json b/task_022/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..6913e5c3b7395814b5ebf2be1543e1ac88de412f --- /dev/null +++ b/task_022/acceptance_checklist.json @@ -0,0 +1,22 @@ +{ + "task_id": 33, + "category": "ui_optimization", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Targets the specific UI defect described by the user.", + "Preserves surrounding behavior and avoids unrelated rewrites.", + "Uses responsive layout checks where the prompt mentions viewport size." + ], + "input_assets": [ + "index.html" + ], + "expected_outputs": [], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns.", + "A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_022/environment/Dockerfile b/task_022/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_022/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_022/environment/code/index.html b/task_022/environment/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..7b90ede93bf381a859bc1c4f95c39d7d94a7b90c --- /dev/null +++ b/task_022/environment/code/index.html @@ -0,0 +1,24 @@ + + + + + Floating Prompt Fixture + + + +

      Already sent message should stay in history.

      +
      + +
      +
      + Already sent message +
      + + diff --git a/task_022/environment/docker-compose.yaml b/task_022/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_022/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_022/instruction.md b/task_022/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..20ebdd78ca5f9abe87f495b01574d7dcf2fe58ff --- /dev/null +++ b/task_022/instruction.md @@ -0,0 +1,15 @@ +# Floating draft composer + +In the supplied root `index.html`, turn the floating prompt area into the composer for an unsent message. Move the existing editable control into it rather than making a second editor; remove the floating copy of sent content. Keep the page offline. + +## Interaction and style + +Retain `data-testid="floating-prompt-area"` and `data-testid="reusable-prompt-input"`. Keep the floating area fixed, visible within the viewport and stable during scrolling. Add an identifiable Send button with `data-testid="send-button"`. While editing, keep draft text only in the composer. Sending nonblank text appends one user message bubble containing the submitted text in the chat history and clears the composer. Whitespace-only input does not append anything. Mark user bubbles with the existing user-message class or `data-testid="chat-message-user"`. + +Expose `window.__setComposerCorners(mode)` with `"square"` and `"rounded"`. The square state has computed radius 0 and the rounded state has positive radius. Switching modes or scrolling must not replace the input, lose its draft or inadvertently reset its corners. + +## Acceptance Checklist + +- The offline page presents one reusable editor within a fixed, in-viewport composer. It stays put during scrolling and does not duplicate unsent drafts or display old sent-message text there. +- Send appends exactly one separate bubble with the entered text, clears the input and ignores blank text. +- Both corner styles take effect on the same composer and preserve the current draft. diff --git a/task_022/quality_notes.md b/task_022/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..8da9186e00ac25a6fdb20000e9bb7861ad049825 --- /dev/null +++ b/task_022/quality_notes.md @@ -0,0 +1,4 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. \ No newline at end of file diff --git a/task_022/solution/README.md b/task_022/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_022/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_022/solution/code/index.html b/task_022/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..a7c8640983efc32eda148e2686d402dc7ddaf5ad --- /dev/null +++ b/task_022/solution/code/index.html @@ -0,0 +1,89 @@ + + + + + +Floating Prompt Area + + + +
      Conversation
      + +
      +
      Hello! How can I help?
      +
      Please refactor the floating input area.
      +
      Done. The input area is now ready for a new message.
      +
      + + +
      + + +
      + + + + diff --git a/task_022/solution/solve.sh b/task_022/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_022/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_022/task.toml b/task_022/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_022/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_022/task_meta.json b/task_022/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..5b7aea63b64bf4162ab2e2cf2589a75bb3ae9753 --- /dev/null +++ b/task_022/task_meta.json @@ -0,0 +1,23 @@ +{ + "task_id": 33, + "task_category": "ui_optimization", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 20, + "language": "javascript", + "tool_files_from_selected_trace": [ + ".env.example", + ".env.local", + "PromptResponseBlock.tsx", + "agent-config.ts", + "client.ts", + "package.json" + ], + "input_assets": [ + "index.html" + ], + "expected_outputs": [], + "source_row_id": 198, + "repair_revision": "2026-09-29", + "instruction_sha256": "7b42a767f1ddc0c3221fa864e9d04568b1be689ded1d8669f5240b24399a5381" +} diff --git a/task_022/tests/_shared/contract_checker.js b/task_022/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_022/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_022/tests/_shared/static_enhancer.sh b/task_022/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_022/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_022/tests/enhancement_cases.json b/task_022/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..b76d2d7c9e97449b10862fd19f58c048f1a7174a --- /dev/null +++ b/task_022/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "之前是显示已经发出去的消息,现在需要改成一个输入框,是等待发送的状态。输入框已经有了,要复用现在的。", + "validator": "validate_enhanced_cases.js#casePendingEditor", + "验证行为": "发现浮动区域内唯一可编辑输入,写入包含 Unicode 与标记字符的草稿,并确认发送前不会出现在历史区域。" + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "verifier 会检查 floating prompt 仍是 fixed、复用现有 input、pending 文本可编辑、不再在该区域渲染 sent-message-only 内容,并检查 send 控件的 chat 行为:发送后向 history 追加一个包含输入文本的 user message bubble、清空 input,空白输入不追加。", + "validator": "validate_enhanced_cases.js#caseSendRoundTrip", + "验证行为": "通过浮动区域内实际发送控件发送特殊字符文本,验证区域外新增精确文本节点且输入被清空。" + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "注意圆角直角逻辑还在、浮动逻辑还要", + "validator": "validate_enhanced_cases.js#caseFloatingAndCorners", + "验证行为": "滚动到底后验证输入区仍锚定于同一视口位置,且当前圆角或直角状态保持不变。" + } +] diff --git a/task_022/tests/test.sh b/task_022/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ab2150eb79f6f15b53d20b21738b84bbe0d8003 --- /dev/null +++ b/task_022/tests/test.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_ui_behavior.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_022/tests/validate_aaav_dynamic.js b/task_022/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..8b0413c2e2d021162dabf2b575fb0d513ac207cf --- /dev/null +++ b/task_022/tests/validate_aaav_dynamic.js @@ -0,0 +1,148 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 33; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_022/tests/validate_browser_smoke.js b/task_022/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_022/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_022/tests/validate_enhanced_cases.js b/task_022/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..23d28f9819629ca962959f2064a191bc20e3fb25 --- /dev/null +++ b/task_022/tests/validate_enhanced_cases.js @@ -0,0 +1,154 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +const fs = require('node:fs'); +const inputText = input => input.evaluate(el => 'value' in el ? el.value : el.textContent || ''); +fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +async function openPage(browser) { + const page = await browser.newPage({ viewport: { width: 923, height: 641 } }); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { + waitUntil: 'domcontentloaded' + }); + return page; +} + +async function discoverComposer(page) { + return page.evaluateHandle(() => { + const visible = element => { + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + return rect.width > 0 && rect.height > 0 && style.display !== 'none' && + style.visibility !== 'hidden'; + }; + const editables = [...document.querySelectorAll('input, textarea, [contenteditable="true"]')] + .filter(visible) + .filter(element => !element.disabled && !element.readOnly); + const candidates = editables.map(input => { + let area = input.parentElement; + while (area && getComputedStyle(area).position !== 'fixed') { + area = area.parentElement; + } + return { input, area }; + }).filter(candidate => candidate.area); + if (candidates.length !== 1) { + throw new Error(`expected one reusable editable control in a floating area, found ${candidates.length}`); + } + return candidates[0]; + }); +} + +async function composerParts(handle) { + return { + input: await handle.getProperty('input'), + area: await handle.getProperty('area') + }; +} + +// ENHANCED_CASE_1: the floating region is a live pending editor, not a second sent-message rendering. +async function casePendingEditor(browser) { + const page = await openPage(browser); + const composer = await discoverComposer(page); + const { input, area } = await composerParts(composer); + const sentinel = 'pending 你好'; + await input.fill(sentinel); + assert(await inputText(input) === sentinel, 'pending input must retain arbitrary editable text before send'); + const duplicateOutside = await page.evaluate(({ area, text }) => { + const visible = element => { + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + return rect.width > 0 && rect.height > 0 && style.display !== 'none' && style.visibility !== 'hidden'; + }; + return [...document.querySelectorAll('body *')].some(element => + !area.contains(element) && visible(element) && element.children.length === 0 && + (element.textContent || '').trim() === text + ); + }, { area, text: sentinel }); + assert(!duplicateOutside, 'unsent draft must not already appear in message history'); + await page.screenshot({path: '/logs/verifier/visual-audit/pending.png', fullPage: true}); + await page.close(); +} + +// ENHANCED_CASE_2: sending appends the exact pending text outside the composer and clears it. +async function caseSendRoundTrip(browser) { + const page = await openPage(browser); + const composer = await discoverComposer(page); + const { input, area } = await composerParts(composer); + const sentinel = 'send & keep 世界'; + await input.fill(sentinel); + await page.evaluate(area => { + window.__enhancedNodesBeforeSend = new Set(document.querySelectorAll('*')); + const controls = [...area.querySelectorAll('button, [role="button"], input[type="submit"], input[type="button"]')] + .filter(element => { + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + return rect.width > 0 && rect.height > 0 && style.display !== 'none' && style.visibility !== 'hidden' && !element.disabled; + }); + const send = controls.find(element => element.dataset.testid === 'send-button') || + controls.find(element => /^(send|发送)$/i.test(element.textContent.trim())); + if (!send) throw new Error('composer needs an identifiable send control'); + send.click(); + }, area); + await page.waitForTimeout(50); + assert(await inputText(input) === '', 'successful send must clear the pending input'); + const additions = await page.evaluate(({ area, text }) => + [...document.querySelectorAll('*')].filter(element => + !window.__enhancedNodesBeforeSend.has(element) && !area.contains(element) && + (element.textContent || '').trim() === text + ).length, + { area, text: sentinel }); + assert(additions >= 1, 'send must append a message containing the exact input text outside the composer'); + await page.screenshot({path: '/logs/verifier/visual-audit/sent.png', fullPage: true}); + await page.close(); +} + +// ENHANCED_CASE_3: the composer stays viewport-anchored and keeps its rounded-or-square corner state while scrolling. +async function caseFloatingAndCorners(browser) { + const page = await openPage(browser); + const composer = await discoverComposer(page); + const { input, area } = await composerParts(composer); + const before = await area.evaluate(element => { + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + return { top: rect.top, left: rect.left, position: style.position, radius: style.borderRadius }; + }); + assert(before.position === 'fixed', 'composer must preserve fixed floating positioning'); + assert(before.radius.split(/\s+/).every(value => Number.isFinite(parseFloat(value))), + 'composer must expose a valid rounded-or-square corner state'); + await page.evaluate(() => window.scrollTo(0, document.documentElement.scrollHeight)); + await page.waitForTimeout(50); + const after = await area.evaluate(element => { + const rect = element.getBoundingClientRect(); + return { top: rect.top, left: rect.left, radius: getComputedStyle(element).borderRadius }; + }); + assert(Math.abs(after.top - before.top) <= 1 && Math.abs(after.left - before.left) <= 1, + 'floating composer must remain at the same viewport position after document scroll'); + assert(after.radius === before.radius, 'scrolling must not discard the current corner state'); + await input.fill('keep draft'); + await page.evaluate(()=>window.__setComposerCorners('square')); + assert(await area.evaluate(e=>getComputedStyle(e).borderRadius.split(/\s+/).every(v=>parseFloat(v)===0)),'square state must have zero radius'); + await page.evaluate(()=>window.__setComposerCorners('rounded')); + assert(await area.evaluate(e=>getComputedStyle(e).borderRadius.split(/\s+/).some(v=>parseFloat(v)>0)),'rounded state must have positive radius'); + assert(await inputText(input)==='keep draft','corner switch must preserve same draft'); + await page.screenshot({path: '/logs/verifier/visual-audit/corners-preserve-draft.png', fullPage: true}); + await page.close(); +} + +(async () => { + const browser = await chromium.launch({ headless: true }); + try { + await casePendingEditor(browser); + await caseSendRoundTrip(browser); + await caseFloatingAndCorners(browser); + } finally { + await browser.close(); + } + console.log('enhanced cases passed for task 33'); +})().catch(error => { + console.error(error && error.stack || error); + process.exit(1); +}); diff --git a/task_022/tests/validate_semantics.js b/task_022/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_022/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_022/tests/validate_ui_behavior.js b/task_022/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..0a2dcf02ff52a42c6cd9fa399e4fa3a8134b32a5 --- /dev/null +++ b/task_022/tests/validate_ui_behavior.js @@ -0,0 +1,60 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +const inputText = input => input.evaluate(el => 'value' in el ? el.value : el.textContent || ''); +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1000, height: 720 } }); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + const area = page.locator('[data-testid="floating-prompt-area"]'); + const input = area.locator('input, textarea, [contenteditable="true"]'); + if (!(await area.isVisible())) throw new Error('floating prompt area must remain visible'); + if (!(await input.first().isVisible())) throw new Error('floating prompt area should contain the reusable input'); + const box = await area.evaluate(el => { + const rect = el.getBoundingClientRect(); + const style = getComputedStyle(el); + return { position: style.position, bottom: style.bottom, radius: style.borderRadius, top: rect.top, bottomEdge: rect.bottom, height: rect.height }; + }); + if (box.position !== 'fixed') throw new Error('floating area must retain fixed positioning'); + // Real on-screen check: the floating area must be fully within the viewport, + // regardless of whether it is pinned to the top or the bottom. (Previously this + // used an arbitrary `top > 600` cutoff that rejected a legitimately on-screen + // bottom-pinned bar, contradicting the instruction to preserve the floating layout.) + const viewportHeight = 720; + if (!(box.bottomEdge <= viewportHeight + 1 && box.top >= -1 && box.bottomEdge > box.top)) { + throw new Error('floating area is not fully visible in viewport'); + } + await input.first().fill('pending prompt text'); + const value = await inputText(input.first()); + if (value !== 'pending prompt text') throw new Error('pending input should be editable'); + const areaText = ((await area.textContent()) || '').toLowerCase(); + if (areaText.includes('already sent') || areaText.includes('sent message')) { + throw new Error('floating area should not render sent-message-only content'); + } + const className = await area.getAttribute('class') || ''; + if (!/(rounded|square|radius|corner)/i.test(className) && !box.radius) { + throw new Error('corner logic signal should remain on floating area'); + } + + // Chat send behavior: sending appends a new user bubble, clears the input, + // and an empty input never appends. + const userBubbles = page.locator('.chat-message.user, [data-testid="chat-message-user"]'); + const sendBtn = page.locator('[data-testid="send-button"], .floating-prompt-area button, .send-btn').first(); + if (!(await sendBtn.isVisible())) throw new Error('a send control should exist in the floating prompt area'); + const before = await userBubbles.count(); + + await input.first().fill('hello world'); + await sendBtn.click(); + const after = await userBubbles.count(); + if (after !== before + 1) throw new Error('sending should append exactly one new user message bubble'); + const lastText = ((await userBubbles.last().textContent()) || '').trim(); + if (lastText !== 'hello world') throw new Error('the appended bubble should contain the sent text'); + if ((await inputText(input.first())) !== '') throw new Error('input should be cleared after sending'); + + // Empty / whitespace-only input must not append anything. + await input.first().fill(' '); + await sendBtn.click(); + if ((await userBubbles.count()) !== after) throw new Error('empty input should not append a message'); + + await browser.close(); +})().catch(err => { console.error(err && err.stack || err); process.exit(1); }); diff --git a/task_023/acceptance_checklist.json b/task_023/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..e674ba72098436077165d531beb309164672084b --- /dev/null +++ b/task_023/acceptance_checklist.json @@ -0,0 +1,29 @@ +{ + "task_id": 34, + "category": "ui_optimization", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Targets the specific UI defect described by the user.", + "Preserves surrounding behavior and avoids unrelated rewrites.", + "Uses responsive layout checks where the prompt mentions viewport size.", + "The redundant figma directory is removed.", + "No stale figma imports remain after cleanup.", + "Core app logic markers and project config are preserved.", + "The prompt page still renders and send/output behavior still works." + ], + "input_assets": [ + "src/app.js", + "package.json", + "figma/" + ], + "expected_outputs": [], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns.", + "A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "v2_notes": "Strengthened using sampled non-from-scratch/multi-turn trajectory signals.", + "repair_revision": "2026-09-29" +} diff --git a/task_023/environment/Dockerfile b/task_023/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_023/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_023/environment/code/figma/page-1.json b/task_023/environment/code/figma/page-1.json new file mode 100644 index 0000000000000000000000000000000000000000..0ca003c0bd10efb7deb4e6552ab03c9d28770456 --- /dev/null +++ b/task_023/environment/code/figma/page-1.json @@ -0,0 +1 @@ +{"unused": true} diff --git a/task_023/environment/code/index.html b/task_023/environment/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..04db2015329cd20657d422d6959954a0172678c6 --- /dev/null +++ b/task_023/environment/code/index.html @@ -0,0 +1,47 @@ + + + + + +demo-1001 + + + +
      Demo 1001 — single page app
      +
      +

      Prompt Demo

      +

      This project ships with a redundant figma/ folder that should be removed; the core app logic must stay unchanged.

      +
      + + +
      +
      Result will appear here.
      +
      +
      core logic version: demo-1001
      + + + + diff --git a/task_023/environment/code/package.json b/task_023/environment/code/package.json new file mode 100644 index 0000000000000000000000000000000000000000..218868e048bb2d8922659d2f35e2d14fc1250edf --- /dev/null +++ b/task_023/environment/code/package.json @@ -0,0 +1,9 @@ +{ + "name": "remove-figma-fixture", + "version": "1.0.0", + "description": "Single-page demo-1001 app that ships with a redundant figma/ folder.", + "main": "src/app.js", + "scripts": { + "test": "node src/app.js" + } +} diff --git a/task_023/environment/code/src/app.js b/task_023/environment/code/src/app.js new file mode 100644 index 0000000000000000000000000000000000000000..9eaec86d0a2aa0a01641f3ee5a56ba88b8681302 --- /dev/null +++ b/task_023/environment/code/src/app.js @@ -0,0 +1,11 @@ +// Core application logic. Exposed via CommonJS so the project's verifier +// scripts and `node --check` both resolve consistently. This logic is the +// part the task says must NOT change; only the redundant figma/ folder is +// expected to be removed. +const coreLogicVersion = "demo-1001"; + +function sendPrompt(input) { + return { title: "real title", content: input.trim() }; +} + +module.exports = { coreLogicVersion, sendPrompt }; diff --git a/task_023/environment/docker-compose.yaml b/task_023/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_023/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_023/instruction.md b/task_023/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b636e54932bbc5cacfc28579420b4a1e267ef9d3 --- /dev/null +++ b/task_023/instruction.md @@ -0,0 +1,9 @@ +# Remove unused design assets + +Delete the unused `figma/` directory from the supplied project. Limit the change to that directory; preserve `index.html`, `src/app.js` and `package.json` byte-for-byte. Do not refactor or add features. + +## Acceptance Checklist + +- The redundant directory is absent, and remaining code has no imports targeting the removed assets. +- The original package entry and `sendPrompt` behavior still work with the preserved files. +- The original page opens offline, renders its prompt area and produces the same output when a prompt is sent. diff --git a/task_023/provenance/restoration_notes.md b/task_023/provenance/restoration_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..f5977e9fa12a938e06642174575a2be75270118c --- /dev/null +++ b/task_023/provenance/restoration_notes.md @@ -0,0 +1,11 @@ +# Restoration Notes for task_034 + +- 官方轨迹形态:real maintenance loop: remove figma folder without breaking logic +- v1 主要损失:v1 只测删除 figma 和保留 marker,几乎丢失引用断裂、恢复功能、页面仍可用等维护难度。 +- v2 改动:新增 stale figma import 检查、页面渲染、prompt send/output 行为、配置保留测试。 + +## 代表性用户轮次 + +1. 检查目录结构,figma 文件夹多余,删除但逻辑不要改。 +2. 删除后出现 autoprefixer、LayoutWindow import、fs-extra、API 无响应、输出区域缺失等多轮问题。 +3. 用户多次要求保留/恢复原功能。 diff --git a/task_023/provenance/user_turns.json b/task_023/provenance/user_turns.json new file mode 100644 index 0000000000000000000000000000000000000000..ecb8fe7a9c263a6ef6879dc5e142b8121514cd8d --- /dev/null +++ b/task_023/provenance/user_turns.json @@ -0,0 +1,16 @@ +{ + "task_id": 34, + "source": "HF CC-Bench-trajectories sampled metadata; public Dataset Server may differ from local GLM-4.6 source table", + "trajectory_type": "multi-turn", + "data": { + "category": "ui_optimization", + "official_task_shape": "real maintenance loop: remove figma folder without breaking logic", + "representative_user_turns": [ + "检查目录结构,figma 文件夹多余,删除但逻辑不要改。", + "删除后出现 autoprefixer、LayoutWindow import、fs-extra、API 无响应、输出区域缺失等多轮问题。", + "用户多次要求保留/恢复原功能。" + ], + "loss_in_v1": "v1 只测删除 figma 和保留 marker,几乎丢失引用断裂、恢复功能、页面仍可用等维护难度。", + "v2_change": "新增 stale figma import 检查、页面渲染、prompt send/output 行为、配置保留测试。" + } +} diff --git a/task_023/quality_notes.md b/task_023/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..8da9186e00ac25a6fdb20000e9bb7861ad049825 --- /dev/null +++ b/task_023/quality_notes.md @@ -0,0 +1,4 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. \ No newline at end of file diff --git a/task_023/solution/README.md b/task_023/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_023/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_023/solution/code/index.html b/task_023/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..04db2015329cd20657d422d6959954a0172678c6 --- /dev/null +++ b/task_023/solution/code/index.html @@ -0,0 +1,47 @@ + + + + + +demo-1001 + + + +
      Demo 1001 — single page app
      +
      +

      Prompt Demo

      +

      This project ships with a redundant figma/ folder that should be removed; the core app logic must stay unchanged.

      +
      + + +
      +
      Result will appear here.
      +
      +
      core logic version: demo-1001
      + + + + diff --git a/task_023/solution/code/package.json b/task_023/solution/code/package.json new file mode 100644 index 0000000000000000000000000000000000000000..218868e048bb2d8922659d2f35e2d14fc1250edf --- /dev/null +++ b/task_023/solution/code/package.json @@ -0,0 +1,9 @@ +{ + "name": "remove-figma-fixture", + "version": "1.0.0", + "description": "Single-page demo-1001 app that ships with a redundant figma/ folder.", + "main": "src/app.js", + "scripts": { + "test": "node src/app.js" + } +} diff --git a/task_023/solution/code/src/app.js b/task_023/solution/code/src/app.js new file mode 100644 index 0000000000000000000000000000000000000000..9eaec86d0a2aa0a01641f3ee5a56ba88b8681302 --- /dev/null +++ b/task_023/solution/code/src/app.js @@ -0,0 +1,11 @@ +// Core application logic. Exposed via CommonJS so the project's verifier +// scripts and `node --check` both resolve consistently. This logic is the +// part the task says must NOT change; only the redundant figma/ folder is +// expected to be removed. +const coreLogicVersion = "demo-1001"; + +function sendPrompt(input) { + return { title: "real title", content: input.trim() }; +} + +module.exports = { coreLogicVersion, sendPrompt }; diff --git a/task_023/solution/solve.sh b/task_023/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a31cd445d2447ffcfb640e90da9e01f7292425d7 --- /dev/null +++ b/task_023/solution/solve.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +rm -rf "$TARGET/figma" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_023/task.toml b/task_023/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_023/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_023/task_meta.json b/task_023/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..dbbfd8874ff3103d9a3f40e317e27413633e3655 --- /dev/null +++ b/task_023/task_meta.json @@ -0,0 +1,30 @@ +{ + "task_id": 34, + "task_category": "ui_optimization", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 5, + "language": "javascript", + "tool_files_from_selected_trace": [ + ".env.example", + ".env.local", + "AIContentArea.tsx", + "LayoutWindow.tsx", + "MainContentArea.tsx", + "PromptResponseBlock.tsx", + "agent-config.ts", + "client.ts", + "page.tsx", + "parser.ts", + "route.ts" + ], + "input_assets": [ + "src/app.js", + "package.json", + "figma/" + ], + "expected_outputs": [], + "source_row_id": 204, + "repair_revision": "2026-09-29", + "instruction_sha256": "6dc0fa3f4c48b99aa7c51c3f907fbecace480af3fafaa521b8af3a495a8692c1" +} diff --git a/task_023/tests/_shared/contract_checker.js b/task_023/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_023/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_023/tests/_shared/static_enhancer.sh b/task_023/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_023/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_023/tests/enhancement_cases.json b/task_023/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..c32409fe339f3f2bcb0027d52ced63e0b9217d17 --- /dev/null +++ b/task_023/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "figma 文件夹是多余的,你给去掉。", + "validator": "validate_enhanced_cases.js#caseFigmaCleanup", + "验证行为": "递归确认 figma 目录消失、核心入口与配置仍在,并检查可执行源码没有残留指向 figma 的 import/require。" + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "逻辑不要改。", + "validator": "validate_enhanced_cases.js#caseModuleBehavior", + "验证行为": "从保留的 package 入口加载公共模块,用普通、Unicode/标记字符和空输入核对 fixture 的版本与 sendPrompt 返回行为。" + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "核心 prompt 页面仍必须能渲染并发送输出。", + "validator": "validate_enhanced_cases.js#caseRenderedPromptFlow", + "验证行为": "在真实浏览器按可见控件角色发现输入与操作控件,提交边界文本并确认页面实际输出。" + } +] diff --git a/task_023/tests/review_legacy.sh b/task_023/tests/review_legacy.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ab2150eb79f6f15b53d20b21738b84bbe0d8003 --- /dev/null +++ b/task_023/tests/review_legacy.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_ui_behavior.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_023/tests/test.sh b/task_023/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d5433f1a508f491a90c14d709292dfa19a3016a0 --- /dev/null +++ b/task_023/tests/test.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -uo pipefail +bash /tests/review_legacy.sh +exit 0 diff --git a/task_023/tests/validate_aaav_dynamic.js b/task_023/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..7e95ba6163253e8556a416c326c8c1314b28e84b --- /dev/null +++ b/task_023/tests/validate_aaav_dynamic.js @@ -0,0 +1,148 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 34; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_023/tests/validate_browser_smoke.js b/task_023/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_023/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_023/tests/validate_enhanced_cases.js b/task_023/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..458c2a56839596d56bd9ebbc130928603c7548e6 --- /dev/null +++ b/task_023/tests/validate_enhanced_cases.js @@ -0,0 +1,122 @@ +const fs = require('fs'); +const crypto = require('crypto'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(root, skip = new Set(['tests', 'logs', 'node_modules', '.git'])) { + const entries = []; + for (const entry of fs.readdirSync(root, { withFileTypes: true })) { + if (skip.has(entry.name)) continue; + const absolute = path.join(root, entry.name); + entries.push({ absolute, entry }); + if (entry.isDirectory()) entries.push(...walk(absolute, skip)); + } + return entries; +} + +// ENHANCED_CASE_1: remove the redundant directory completely without leaving executable imports to it. +function caseFigmaCleanup(root) { + const entries = walk(root); + const redundantDirs = entries.filter(({ entry }) => + entry.isDirectory() && entry.name.toLowerCase() === 'figma'); + assert(redundantDirs.length === 0, 'the redundant figma directory must be absent'); + for (const required of ['index.html', 'package.json']) { + assert(fs.statSync(path.join(root, required)).isFile(), `${required} must remain after cleanup`); + } + const preserved = { + 'index.html': '99f6e6fbc7d1acb64f46abaf69c52ae5caef0e888f36dbf77c9afdc506b7919f', + 'src/app.js': 'efd825c0643d35e5fb14fa1bad0fe5ffc18f306b4fca0ac06fa3f77549fa30b2', + 'package.json': '81c7353d98b36ad448f37d82ad7cb554d6a877efa2cb149bc513a8e3887cb76a' + }; + for (const [relative, expected] of Object.entries(preserved)) { + const actual = crypto.createHash('sha256').update(fs.readFileSync(path.join(root, relative))).digest('hex'); + assert(actual === expected, `only figma/ should be deleted; preserved file changed: ${relative}`); + } + const programFiles = entries + .filter(({ entry }) => entry.isFile() && /\.(?:[cm]?js|jsx|ts|tsx|html)$/i.test(entry.name)); + const staleImport = /(?:\bfrom\s*|\brequire\s*\(|\bimport\s*\()["'][^"']*(?:^|[/\\])figma(?:[/\\]|["'])/im; + for (const { absolute } of programFiles) { + assert(!staleImport.test(fs.readFileSync(absolute, 'utf8')), + `stale figma import remains in ${path.relative(root, absolute)}`); + } +} + +// ENHANCED_CASE_2: the package entry keeps the fixture's public logic and boundary behavior unchanged. +function caseModuleBehavior(root) { + const manifest = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')); + assert(typeof manifest.main === 'string' && manifest.main.length > 0, + 'preserved package configuration must identify its entry module'); + const entry = path.resolve(root, manifest.main); + assert(fs.existsSync(entry), 'package entry module must still exist'); + delete require.cache[require.resolve(entry)]; + const app = require(entry); + assert(app && app.coreLogicVersion === 'demo-1001', 'core logic version must remain demo-1001'); + assert(typeof app.sendPrompt === 'function', 'sendPrompt public behavior must remain available'); + for (const [input, content] of [ + [' plain ', 'plain'], + [' 世界 & ', '世界 & '], + ['', ''] + ]) { + const result = app.sendPrompt(input); + assert(result && result.title === 'real title' && result.content === content, + `sendPrompt behavior changed for ${JSON.stringify(input)}`); + } +} + +// ENHANCED_CASE_3: the preserved page still renders and performs its prompt-to-output interaction. +async function caseRenderedPromptFlow(root) { + const browser = await chromium.launch({ headless: true }); + try { + const page = await browser.newPage({ viewport: { width: 877, height: 613 } }); + await page.goto(pathToFileURL(path.join(root, 'index.html')).href, { waitUntil: 'domcontentloaded' }); + const parts = await page.evaluateHandle(() => { + const visible = element => { + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + return rect.width > 0 && rect.height > 0 && style.display !== 'none' && style.visibility !== 'hidden'; + }; + const inputs = [...document.querySelectorAll('input:not([type]), input[type="text"], textarea, [contenteditable="true"]')] + .filter(visible).filter(element => !element.disabled && !element.readOnly); + const actions = [...document.querySelectorAll('button, [role="button"], input[type="submit"], input[type="button"]')] + .filter(visible).filter(element => !element.disabled); + if (inputs.length !== 1 || actions.length !== 1) { + throw new Error(`expected one prompt and one action, found ${inputs.length}/${actions.length}`); + } + return { input: inputs[0], action: actions[0] }; + }); + const input = await parts.getProperty('input'); + const action = await parts.getProperty('action'); + const sent = ' preserve & 世界 '; + await input.fill(sent); + await action.click(); + const expected = sent.trim(); + const rendered = await page.evaluate(expected => [...document.querySelectorAll('body *')].some(element => { + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + return element.children.length === 0 && rect.width > 0 && rect.height > 0 && + style.display !== 'none' && style.visibility !== 'hidden' && + (element.textContent || '').includes(expected); + }), expected); + assert(rendered, 'prompt interaction must still render the submitted content'); + fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + await page.screenshot({path: '/logs/verifier/visual-audit/preserved-app.png', fullPage: true}); + } finally { + await browser.close(); + } +} + +(async () => { + const root = process.cwd(); + caseFigmaCleanup(root); + caseModuleBehavior(root); + await caseRenderedPromptFlow(root); + console.log('enhanced cases passed for task 34'); +})().catch(error => { + console.error(error && error.stack || error); + process.exit(1); +}); diff --git a/task_023/tests/validate_semantics.js b/task_023/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_023/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_023/tests/validate_ui_behavior.js b/task_023/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..46af03e79d92ad25613995897fb34d406f27bf11 --- /dev/null +++ b/task_023/tests/validate_ui_behavior.js @@ -0,0 +1,43 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +(async () => { + const root = process.cwd(); + if (fs.existsSync(path.join(root, 'figma'))) throw new Error('figma folder should be removed'); + for (const entry of fs.readdirSync(root, { withFileTypes: true })) { + if (entry.isDirectory() && entry.name.toLowerCase() === 'figma') throw new Error('no figma directory should remain'); + } + const sourceFiles = []; + function walk(dir) { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const p = path.join(dir, entry.name); + if (entry.isDirectory() && !['tests','logs','node_modules'].includes(entry.name)) walk(p); + if (entry.isFile() && /\.(js|jsx|ts|tsx)$/.test(entry.name)) sourceFiles.push(p); + } + } + walk(root); + const joined = sourceFiles.map(p => fs.readFileSync(p, 'utf8')).join('\n'); + if (/from\s+['\"][^'\"]*figma|require\(['\"][^'\"]*figma|@\/components\/figma/.test(joined)) throw new Error('source should not keep stale figma imports after removing the folder'); + const app = fs.readFileSync(path.join(root, 'src', 'app.js'), 'utf8'); + if (!app.includes('sendPrompt')) throw new Error('application sendPrompt logic should remain present'); + if (!fs.existsSync(path.join(root, 'package.json'))) throw new Error('project config should be preserved'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage(); + await page.goto(pathToFileURL(path.join(root, 'index.html')).href, { waitUntil: 'domcontentloaded' }); + // Accept either the data-testid contract hooks OR the starter fixture's original + // ids (#prompt / #send / #output and a
      /#app root). The instruction says the + // app logic must NOT change after removing figma/, so a solution that merely deletes + // the folder and keeps the fixture's original markup must still pass. + const appRoot = page.locator('[data-testid="app-root"], main, #app').first(); + const promptInput = page.locator('[data-testid="prompt-input"], #prompt').first(); + const sendButton = page.locator('[data-testid="send-button"], #send').first(); + const outputArea = page.locator('[data-testid="output-area"], #output').first(); + if (!(await appRoot.isVisible())) throw new Error('core page should still render after cleanup'); + await promptInput.fill('hello restored app'); + await sendButton.click(); + await page.waitForTimeout(100); + const output = (await outputArea.textContent()) || ''; + if (!/hello restored app/.test(output)) throw new Error('send/output area should keep working after figma cleanup'); + await browser.close(); +})().catch(err => { console.error(err && err.stack || err); process.exit(1); }); diff --git a/task_024/acceptance_checklist.json b/task_024/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..42d6c28130355ccf43f028984a76a06dea51caa3 --- /dev/null +++ b/task_024/acceptance_checklist.json @@ -0,0 +1,23 @@ +{ + "task_id": 40, + "category": "data_analysis", + "language": "python", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Python files compile; data-analysis tasks generate the requested output files from fixture data." + ], + "input_assets": [ + "titanic.csv" + ], + "expected_outputs": [ + "report.html", + "titanic_clean.csv" + ], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns.", + "Input assets are separated from candidate outputs; do not score candidates merely for recreating input files." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_024/environment/Dockerfile b/task_024/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b5c3125aadc8adae6187cdea0ad0c6d3cf3e505e --- /dev/null +++ b/task_024/environment/Dockerfile @@ -0,0 +1,7 @@ +FROM mcr.microsoft.com/playwright:v1.52.0-noble +USER root +RUN apt-get update && apt-get install -y --no-install-recommends python3-numpy python3-pil && ln -sf /usr/bin/python3 /usr/local/bin/python && rm -rf /var/lib/apt/lists/* +RUN npm install --global --prefix /usr playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules +WORKDIR /app +COPY ./code /app diff --git a/task_024/environment/code/titanic.csv b/task_024/environment/code/titanic.csv new file mode 100644 index 0000000000000000000000000000000000000000..f81f7bf9b532cc0d3fd92924b8539a6c4e71e38f --- /dev/null +++ b/task_024/environment/code/titanic.csv @@ -0,0 +1,7 @@ +survived,pclass,sex,age,sibsp,parch,fare,embarked,class,deck +1,1,female,29,0,0,211.3375,S,First,C +1,1,male,,1,0,151.5500,S,First,C +0,3,male,22,0,0,7.2500,S,Third, +1,3,female,26,0,0,7.9250,S,Third, +0,2,male,35,0,0,26.0000,S,Second, +1,2,female,,1,1,26.2500,C,Second,D diff --git a/task_024/environment/docker-compose.yaml b/task_024/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_024/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_024/instruction.md b/task_024/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b11a89da238e9a62c99fc0df5d411ebcd90a23ec --- /dev/null +++ b/task_024/instruction.md @@ -0,0 +1,21 @@ +# Titanic data cleaning and survival report + +Create a root `solve.py` that reads the current `titanic.csv`, creates `titanic_clean.csv` and `report.html` in the same directory, and runs offline. Compute results from the input each time; do not hard-code the bundled records or outputs. + +## Cleaned data + +- Resolve missing age and deck values by reasonable imputation or dropping rows missing one of these fields. Keep all complete rows and do not alter observed ages, decks or other original fields. Filled ages should be finite and within the observed age range. Keep a nonempty dataset with no missing age or deck. +- Keep the original category labels for `embarked` and `class` and add `embarked_code` and `class_code` as nonnegative integers. Within each field, use one distinct, consistent code per category. Pandas is optional; CSV does not carry category dtypes. +- Add boolean `is_alone`, true exactly when `sibsp + parch == 0`. + +## Report + +Summarize cleaning and the final row count. Compute survivors, total and survival rate separately for each sex category and each class category from the **final cleaned CSV**. In ``, display the category, counts and rate for each group. For each data row provide `data-group` (`sex` or `class`), `data-category` (original label), `data-survived`, `data-total` and `data-rate` (fraction from 0 to 1). + +Include a visible `` bar chart. Use exactly one `` per category with numeric `width` and `height` and matching `data-group`, `data-category` and `data-rate`; reserve rectangles in this SVG for the bars. Scale the bar width or height proportionally to the rate on a shared zero-origin scale. Display rates with sufficient precision, such as three fractional decimals or one decimal place for percentages. Print readable cleaning and report progress, for example, `[1/3] Cleaning age and deck` or percentage progress with named stages. + +## Acceptance Checklist + +- Running the script on the current or changed input preserves complete records and unchanged source fields, resolves missing age/deck, and computes reproducible codes and `is_alone`. +- The visible table and chart reflect the cleaned output, for every sex and class category. Visible counts and rates agree with metadata and bar lengths. +- Both outputs are regenerated and the script visibly reports cleaning and reporting progress. diff --git a/task_024/quality_notes.md b/task_024/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..2ef6090b0119048acd6aef0e3e8f39d848014b73 --- /dev/null +++ b/task_024/quality_notes.md @@ -0,0 +1,4 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. +- Input assets are separated from candidate outputs; do not score candidates merely for recreating input files. \ No newline at end of file diff --git a/task_024/solution/README.md b/task_024/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_024/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_024/solution/code/solve.py b/task_024/solution/code/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..d17b90b3fc3f58b17009df0b36ab1a2ba5ad0f18 --- /dev/null +++ b/task_024/solution/code/solve.py @@ -0,0 +1,82 @@ +import csv +from collections import defaultdict +from html import escape +from statistics import median + +rows = list(csv.DictReader(open('titanic.csv', encoding='utf-8-sig'))) +print(f'[1/4] loaded {len(rows)} Titanic records', flush=True) +ages = [float(r['age']) for r in rows if r.get('age')] +median_age = median(ages) if ages else 30 +for r in rows: + r['age'] = r.get('age') or str(median_age) + r['deck'] = r.get('deck') or 'Unknown' + r['embarked'] = r.get('embarked') or 'S' + r['class'] = r.get('class') or r.get('pclass', '') + sibsp = int(float(r.get('sibsp') or 0)) + parch = int(float(r.get('parch') or 0)) + r['is_alone'] = 'true' if sibsp + parch == 0 else 'false' + # bucket age into an ordered category column (pandas-style astype('category')) + age_val = float(r['age']) + r['age_category'] = 'child' if age_val < 18 else ('senior' if age_val >= 60 else 'adult') +print('[2/4] filled age/deck and derived is_alone', flush=True) + +# encode categorical columns into integer category codes (equivalent to +# df[col].astype('category').cat.codes) for downstream modelling +category_cols = ['sex', 'embarked', 'class', 'deck', 'age_category'] +for col in category_cols: + levels = sorted({(r.get(col) or '') for r in rows}) + codes = {level: idx for idx, level in enumerate(levels)} + for r in rows: + r[col + '_code'] = str(codes[r.get(col) or '']) +print('[3/4] encoded embarked/class categorical values', flush=True) + +extra = ['age', 'deck', 'embarked', 'class', 'is_alone', 'age_category'] + [c + '_code' for c in category_cols] +fields = list(dict.fromkeys(list(rows[0].keys()) + extra)) +with open('titanic_clean.csv', 'w', newline='', encoding='utf-8') as f: + writer = csv.DictWriter(f, fieldnames=fields) + writer.writeheader() + writer.writerows(rows) +groups = defaultdict(lambda: [0, 0]) +for row in rows: + survived = str(row.get('survived', '')).strip().lower() in {'1', 'true'} + for field in ('sex', 'class'): + counts = groups[(field, row[field])] + counts[0] += int(survived) + counts[1] += 1 + +table_rows = [] +bars = [] +for index, ((field, category), (survived, total)) in enumerate(sorted(groups.items())): + rate = survived / total + safe_field, safe_category = escape(field), escape(category) + table_rows.append( + f'
      ' + f'{safe_field}{safe_category}{survived}' + f'{total}{rate:.1%}
      ' + ) + y = 16 + index * 38 + bars.append( + f'{safe_field}: {safe_category}' + f'' + ) + +height = 32 + len(groups) * 38 +report = ( + '
      Titanic survival analysis' + '' + '

      Titanic survival analysis

      ' + f'

      Cleaned {len(rows)} records. Missing ages use the observed median; missing deck is Unknown.

      ' + '

      Survival rates by sex and class

      ' + '' + '' + ''.join(table_rows) + '
      GroupCategorySurvivedTotalRate
      ' + f'' + + ''.join(bars) + '
      ' +) +with open('report.html', 'w', encoding='utf-8') as handle: + handle.write(report) +print('[4/4] wrote titanic_clean.csv and report.html', flush=True) diff --git a/task_024/solution/solve.sh b/task_024/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_024/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_024/task.toml b/task_024/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_024/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_024/task_meta.json b/task_024/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..b4d190265fece613e39eed6f537b0d43ea88cf20 --- /dev/null +++ b/task_024/task_meta.json @@ -0,0 +1,21 @@ +{ + "task_id": 40, + "task_category": "data_analysis", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 2, + "language": "python", + "tool_files_from_selected_trace": [ + "titanic_analysis.py" + ], + "input_assets": [ + "titanic.csv" + ], + "expected_outputs": [ + "report.html", + "titanic_clean.csv" + ], + "source_row_id": 240, + "repair_revision": "2026-09-29", + "instruction_sha256": "cf3b070a2660ea5599a015c80b7db5a308d49c809eba9b4c87c7c8ea1957f858" +} diff --git a/task_024/tests/_shared/contract_checker.js b/task_024/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_024/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_024/tests/_shared/static_enhancer.sh b/task_024/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_024/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_024/tests/enhancement_cases.json b/task_024/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..8078af4918f2d46cf3acc3a30d8ed2fc5f808c0d --- /dev/null +++ b/task_024/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "检查缺失值,对 age 和 deck 列进行合理填充(如均值、众数或删除)。", + "validator": "tests/validate_enhancement.py::case_age_imputation", + "验证行为": "按 fare 对齐 fixture 与清洗输出,验证 age 缺失值被有限且位于观测范围内的数值填充,同时原有 age 不变。" + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "检查缺失值,对 age 和 deck 列进行合理填充(如均值、众数或删除)。\n将 embarked 和 class 转换为分类变量(category 类型)。", + "validator": "tests/validate_enhancement.py::case_deck_fill_and_categories", + "验证行为": "验证 deck 缺失值已填充且原值未改变,embarked/class 非空且保持 fixture 类别,并验证导出类别编码或明确的 category 类型转换。" + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "创建新特征 is_alone:如果 sibsp + parch == 0,则为 True。", + "validator": "tests/validate_enhancement.py::case_is_alone_truth_table", + "验证行为": "逐行从 fixture 重算 sibsp + parch == 0,验证 is_alone 的 True/False 两个分支。" + } +] diff --git a/task_024/tests/test.sh b/task_024/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..84faccbd8d6b235d57600e62b1f53aa065315eac --- /dev/null +++ b/task_024/tests/test.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -uo pipefail +mkdir -p /logs/verifier +echo 0 > /logs/verifier/reward.txt +cd /app || exit 1 +PASS=1 +rm -f -- titanic_clean.csv report.html +timeout 60s python3 solve.py > /tmp/harbor_data_run.log 2>&1 || PASS=0 +cat /tmp/harbor_data_run.log +python3 /tests/validate_outputs.py || PASS=0 +python3 /tests/validate_enhancement.py || PASS=0 +timeout 60s node /tests/validate_aaav_dynamic.js || PASS=0 +timeout 120s python3 /tests/validate_mutated_input.py || PASS=0 +echo "$PASS" > /logs/verifier/reward.txt diff --git a/task_024/tests/validate_aaav_dynamic.js b/task_024/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..e3200e11dc51a93f8d231c92dc948ca6eedda9bc --- /dev/null +++ b/task_024/tests/validate_aaav_dynamic.js @@ -0,0 +1,83 @@ +const {chromium} = require('playwright'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const {pathToFileURL} = require('node:url'); + +(async () => { + const browser = await chromium.launch({headless: true, args: ['--no-sandbox']}); + try { + const page = await browser.newPage({viewport: {width: 1100, height: 760}}); + await page.route(/^https?:/, route => route.abort()); + await page.goto(pathToFileURL(path.join(process.cwd(), 'report.html')).href); + const rows = page.locator('#survival-rates tr[data-group]'); + assert(await rows.count(), 'visible report needs survival rows'); + const roles = await rows.first().evaluate(row => { + const table = row.closest('table'); + const header = table.tHead?.rows[table.tHead.rows.length - 1] ?? table.rows[0]; + return Array.from(header.cells, cell => { + const text = cell.innerText.trim(); + if (/surviv(?:ed|ors?)|生还|幸存|存活/i.test(text) && + !/rate|%|率|\b(?:non[- ]?|not |did not )surviv|未(?:生还|幸存|存活)/i.test(text)) return 'survived'; + if (/^(?:total|total (?:passenger count|passengers|people|group size|size|count|records)|all passengers)$|总数|总计|总人数|样本数/i.test(text)) return 'total'; + if (/^(?:n|passengers|乘客数)$/i.test(text)) return 'total-fallback'; + return null; + }); + }); + const numbers = text => (text.match(/\d[\d,]*(?:\.\d+)?\s*%?/g) ?? []).map(value => { + const number = parseFloat(value.replaceAll(',', '')); + return value.includes('%') ? number / 100 : number; + }); + for (const row of await rows.all()) { + assert(await row.isVisible(), 'survival row is hidden'); + const text = await row.innerText(); + const category = await row.getAttribute('data-category'); + assert(text.includes(category), 'category exists only in hidden metadata'); + const rate = Number(await row.getAttribute('data-rate')); + const values = numbers(text); + const cells = await row.locator('td, th').all(); + for (const role of ['survived', 'total']) { + const expected = Number(await row.getAttribute('data-' + role)); + const exact = roles.indexOf(role); + const column = exact >= 0 || role !== 'total' ? exact : roles.indexOf('total-fallback'); + const visibleValues = column >= 0 + ? (cells[column] && await cells[column].isVisible() ? numbers(await cells[column].innerText()) : []) + : values; + assert(visibleValues.includes(expected), `${role} count is wrong or missing for ${category}`); + } + assert(values.some(value => Math.abs(value - rate) <= 0.0006), 'visible rate disagrees with metadata'); + } + assert(await page.locator('#survival-chart').isVisible(), 'chart is hidden'); + for (const bar of await page.locator('#survival-chart rect[data-rate]').all()) { + const rate = Number(await bar.getAttribute('data-rate')); + if (rate > 0) { + const painted = await bar.evaluate(node => { + const style = getComputedStyle(node); + const context = document.createElement('canvas').getContext('2d'); + const hasInk = paint => { + if (paint === 'none') return false; + if (paint.startsWith('url(')) return true; + context.fillStyle = '#000'; + context.fillStyle = paint; + context.clearRect(0, 0, 1, 1); + context.fillRect(0, 0, 1, 1); + return context.getImageData(0, 0, 1, 1).data[3] > 0; + }; + return ((+style.fillOpacity > 0 && hasInk(style.fill)) || + (+style.strokeOpacity > 0 && parseFloat(style.strokeWidth) > 0 && hasInk(style.stroke))) && + (() => { + for (let ancestor = node; ancestor; ancestor = ancestor.parentElement) { + if (+getComputedStyle(ancestor).opacity === 0) return false; + } + return true; + })(); + }); + assert(await bar.isVisible() && painted, 'positive-rate bar is hidden'); + } + } + fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + await page.screenshot({path: `/logs/verifier/visual-audit/${process.env.TITANIC_SCREENSHOT || 'titanic-report'}.png`, fullPage: true}); + } finally { + await browser.close(); + } +})().catch(error => {console.error(error); process.exit(1)}); diff --git a/task_024/tests/validate_enhancement.py b/task_024/tests/validate_enhancement.py new file mode 100644 index 0000000000000000000000000000000000000000..9232a18f2b7b7ea848276bde1f70f69385e00d74 --- /dev/null +++ b/task_024/tests/validate_enhancement.py @@ -0,0 +1,132 @@ +import csv +import math +import pathlib +import re +import sys + + +ROOT = pathlib.Path.cwd() + + +def read_csv(path): + with path.open(encoding="utf-8-sig", newline="") as handle: + return list(csv.DictReader(handle)) + + +def keyed(rows): + result = {} + for row in rows: + key = float(row["fare"]) + assert key not in result, "fixture fare values must be unique" + result[key] = row + return result + + +def boolean_value(value): + token = re.sub(r"[^a-z0-9]+", "", str(value).lower()) + if token in {"true", "1", "yes", "y"}: + return True + if token in {"false", "0", "no", "n"}: + return False + raise AssertionError(f"is_alone is not boolean-like: {value!r}") + + +def matching_rows(): + source = keyed(read_csv(ROOT / "titanic.csv")) + output = keyed(read_csv(ROOT / "titanic_clean.csv")) + assert output and set(output) <= set(source), "clean export must contain only fixture records" + for key, before in source.items(): + if key not in output: + assert not before.get('age', '').strip() or not before.get('deck', '').strip(), 'only records with missing age/deck may be deleted' + for key, after in output.items(): + before = source[key] + for field in ('survived', 'pclass', 'sibsp', 'parch'): + assert float(after[field]) == float(before[field]), f'non-cleaning field changed: {field}' + assert after['sex'] == before['sex'], 'sex label changed' + return source, output + + +# ENHANCED_CASE_1 +def case_age_imputation(): + """Every age is finite, observed ages survive, and fixture gaps get a plausible fill.""" + source, output = matching_rows() + observed = [float(row["age"]) for row in source.values() if row.get("age", "").strip()] + assert observed and any(not row.get("age", "").strip() for row in source.values()), "fixture must exercise age filling" + for key in output: + before = source[key] + try: + age = float(output[key].get("age", "")) + except ValueError as exc: + raise AssertionError(f"age is not numeric for fare={key}") from exc + assert math.isfinite(age), f"age is not finite for fare={key}" + if before.get("age", "").strip(): + assert age == float(before["age"]), f"observed age changed for fare={key}" + else: + assert min(observed) <= age <= max(observed), f"age fill is outside the fixture range for fare={key}" + + +# ENHANCED_CASE_2 +def case_deck_fill_and_categories(): + """Deck gaps are filled and embarked/class remain valid categorical values.""" + source, output = matching_rows() + assert any(not row.get("deck", "").strip() for row in source.values()), "fixture must exercise deck filling" + for key in output: + before = source[key] + after = output[key] + assert after.get("deck", "").strip(), f"deck remains empty for fare={key}" + if before.get("deck", "").strip(): + assert after["deck"].strip() == before["deck"].strip(), f"observed deck changed for fare={key}" + for name in ("embarked", "class"): + assert after.get(name, "").strip(), f"{name} is empty for fare={key}" + if before.get(name, "").strip(): + assert after[name].strip() == before[name].strip(), f"observed {name} changed for fare={key}" + + encoded = all(f"{name}_code" in next(iter(output.values())) for name in ("embarked", "class")) + assert encoded, "CSV must expose embarked_code and class_code as categorical evidence" + for name in ("embarked", "class"): + mapping = {} + for row in output.values(): + label = row[name].strip() + code = int(row[f"{name}_code"]) + assert code >= 0, f"{name}_code must be non-negative" + mapping.setdefault(label, code) + assert mapping[label] == code, f"{name} category has inconsistent codes" + assert len(set(mapping.values())) == len(mapping), f"distinct {name} categories share a code" + + +# ENHANCED_CASE_3 +def case_is_alone_truth_table(): + """is_alone follows sibsp + parch == 0 for every fixture record.""" + source, output = matching_rows() + assert "is_alone" in next(iter(output.values())), "clean export lacks is_alone" + expected_values = set() + for key in output: + before = source[key] + expected = float(before.get("sibsp") or 0) + float(before.get("parch") or 0) == 0 + expected_values.add(expected) + assert boolean_value(output[key].get("is_alone")) is expected, f"is_alone mismatch for fare={key}" + assert expected_values, "cleaning may not delete every record" + + +CASES = [ + ("ENHANCED_CASE_1", case_age_imputation), + ("ENHANCED_CASE_2", case_deck_fill_and_categories), + ("ENHANCED_CASE_3", case_is_alone_truth_table), +] + + +failures = [] +requested = set(sys.argv[1:]) +known = {case_id for case_id, _ in CASES} +assert requested <= known, f"unknown case id(s): {sorted(requested - known)}" +for case_id, validator in CASES: + if requested and case_id not in requested: + continue + try: + validator() + print(f"{case_id}: PASS") + except Exception as exc: + failures.append((case_id, exc)) + print(f"{case_id}: FAIL: {exc}", file=sys.stderr) +if failures: + raise SystemExit(1) diff --git a/task_024/tests/validate_mutated_input.py b/task_024/tests/validate_mutated_input.py new file mode 100644 index 0000000000000000000000000000000000000000..c5977127bc2ae3b1e1e5efe7c56dd0745a5f9352 --- /dev/null +++ b/task_024/tests/validate_mutated_input.py @@ -0,0 +1,37 @@ +"""Rerun in an isolated copy with changed rows to reject fixture hardcoding.""" +import csv +import os +import pathlib +import shutil +import subprocess +import sys +import tempfile + +source = pathlib.Path.cwd() +tests = pathlib.Path(__file__).parent +with tempfile.TemporaryDirectory(prefix='titanic-runtime-') as temporary: + work = pathlib.Path(temporary) / 'candidate' + shutil.copytree(source, work, ignore=shutil.ignore_patterns('logs', 'tests', '__pycache__', 'node_modules', '.git')) + with (work / 'titanic.csv').open(newline='', encoding='utf-8-sig') as handle: + rows = list(csv.DictReader(handle)) + fields = list(rows[0]) + for row in rows[:3]: + row['survived'] = str(1 - int(row['survived'])) + additional = {**rows[0], 'fare': '88.125', 'age': '41', 'sex': 'male', 'survived': '0', 'sibsp': '2', 'parch': '1'} + rows.append(additional) + rows.reverse() + with (work / 'titanic.csv').open('w', newline='', encoding='utf-8') as handle: + writer = csv.DictWriter(handle, fieldnames=fields) + writer.writeheader() + writer.writerows(rows) + for output in ('report.html', 'titanic_clean.csv'): + (work / output).unlink(missing_ok=True) + progress = pathlib.Path(temporary) / 'progress.log' + with progress.open('w', encoding='utf-8') as handle: + subprocess.run([sys.executable, 'solve.py'], cwd=work, check=True, timeout=60, + stdout=handle, stderr=subprocess.STDOUT) + env = {**os.environ, 'TITANIC_PROGRESS_LOG': str(progress), 'TITANIC_SCREENSHOT': 'titanic-report-mutated'} + for validator in ('validate_outputs.py', 'validate_enhancement.py'): + subprocess.run([sys.executable, str(tests / validator)], cwd=work, env=env, check=True, timeout=20) + subprocess.run(['node', str(tests / 'validate_aaav_dynamic.js')], cwd=work, env=env, check=True, timeout=30) + print('mutated-input rerun passed') diff --git a/task_024/tests/validate_outputs.py b/task_024/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..fccd040df39e929360e6828691534fb6a0d1861f --- /dev/null +++ b/task_024/tests/validate_outputs.py @@ -0,0 +1,109 @@ +import csv, pathlib, math, os, re +from html.parser import HTMLParser +root = pathlib.Path.cwd() +clean = root / 'titanic_clean.csv' +report = (root / 'report.html').read_text(encoding='utf-8', errors='ignore').lower() +rows = list(csv.DictReader(clean.open(encoding='utf-8-sig'))) +assert rows, 'titanic_clean.csv has no rows' +fields = set(rows[0]) +for col in ['age', 'deck', 'embarked', 'class', 'is_alone']: + assert col in fields, f'missing column {col}' +assert all(r['age'] != '' for r in rows), 'age still has missing values' +assert all(r['deck'] != '' for r in rows), 'deck still has missing values' + +# read the source fixture and assert row-count parity + recompute is_alone +src = root / 'titanic.csv' +src_rows = list(csv.DictReader(src.open(encoding='utf-8-sig'))) +assert len(rows) <= len(src_rows), 'cleaned output cannot add fixture records' +# recompute is_alone per row from sibsp+parch (sum==0 -> alone) and compare +def _truthy_alone(v): + return str(v).strip().lower() in ('true', '1', 'yes') +not_alone_count = 0 +src_by_fare = {float(r['fare']): r for r in src_rows} +for out_r in rows: + assert float(out_r['fare']) in src_by_fare, f'unexpected cleaned row fare={out_r["fare"]}' + src_r = src_by_fare[float(out_r['fare'])] + sibsp = int(float(src_r.get('sibsp') or 0)) + parch = int(float(src_r.get('parch') or 0)) + expected_alone = (sibsp + parch == 0) + got_alone = _truthy_alone(out_r['is_alone']) + assert got_alone == expected_alone, ( + f'is_alone mismatch for sibsp={sibsp} parch={parch}: ' + f'expected {expected_alone}, got {out_r["is_alone"]!r}' + ) + if not expected_alone: + not_alone_count += 1 + +assert 'survival' in report or '生存' in report or 'survived' in report, 'report missing survival content' + +class ReportParser(HTMLParser): + def __init__(self): + super().__init__() + self.table_depth = 0 + self.svg_depth = 0 + self.rows = [] + self.bars = [] + def handle_starttag(self, tag, attrs): + attrs = dict(attrs) + if tag == 'table' and attrs.get('id') == 'survival-rates': + self.table_depth += 1 + elif tag == 'svg' and attrs.get('id') == 'survival-chart': + self.svg_depth += 1 + elif tag == 'tr' and self.table_depth and attrs.get('data-group'): + self.rows.append(attrs) + elif tag == 'rect' and self.svg_depth: + self.bars.append(attrs) + def handle_endtag(self, tag): + if tag == 'table' and self.table_depth: + self.table_depth -= 1 + elif tag == 'svg' and self.svg_depth: + self.svg_depth -= 1 + +parsed = ReportParser() +parsed.feed((root / 'report.html').read_text(encoding='utf-8')) +expected = {} +for field in ('sex', 'class'): + for row in rows: + key = (field, row[field]) + expected.setdefault(key, [0, 0]) + expected[key][0] += int(str(row['survived']).strip().lower() in ('1', 'true')) + expected[key][1] += 1 +assert len(parsed.rows) == len(expected), 'report must contain one survival-rate row per sex/class category' +seen = set() +for row in parsed.rows: + key = (row.get('data-group'), row.get('data-category')) + assert key in expected and key not in seen, f'unexpected or duplicate survival row {key}' + seen.add(key) + survived, total = expected[key] + assert int(row.get('data-survived', -1)) == survived and int(row.get('data-total', -1)) == total, f'wrong counts for {key}' + assert math.isclose(float(row.get('data-rate', -1)), survived / total, abs_tol=0.0001), f'wrong survival rate for {key}' +assert seen == set(expected), 'report omitted a sex/class category' +assert len(parsed.bars) == len(expected), 'SVG chart needs one bar per reported category' +bar_sizes = {} +for bar in parsed.bars: + key = (bar.get('data-group'), bar.get('data-category')) + assert key in expected and key not in bar_sizes, f'unexpected or duplicate bar {key}' + survived, total = expected[key] + rate = survived / total + assert math.isclose(float(bar.get('data-rate', -1)), rate, abs_tol=0.0001), f'bar rate mismatch for {key}' + sizes = (float(bar.get('width', -1)), float(bar.get('height', -1))) + assert all(size >= 0 and math.isfinite(size) for size in sizes), f'invalid bar size for {key}' + bar_sizes[key] = sizes +assert set(bar_sizes) == set(expected), 'chart omitted a category' +# Horizontal and vertical bars are both valid. One dimension must share a +# linear zero-origin scale with the actual rates, not merely their ordering. +def proportional(dimension): + ratios = [bar_sizes[key][dimension] / (counts[0] / counts[1]) + for key, counts in expected.items() if counts[0]] + if not ratios: + return all(bar_sizes[key][dimension] <= 0.01 for key in expected) + if min(ratios) <= 0: + return False + return max(ratios) - min(ratios) <= max(ratios) * 0.01 and all( + bar_sizes[key][dimension] <= 0.01 for key, counts in expected.items() if not counts[0]) +assert proportional(0) or proportional(1), 'bar lengths must proportionally encode rates on a shared axis' + +log = pathlib.Path(os.environ.get('TITANIC_PROGRESS_LOG', '/tmp/harbor_data_run.log')).read_text(encoding='utf-8', errors='ignore') +assert re.search(r'\[\d+/\d+\]|\d+(?:\.\d+)?\s*%', log), 'script must show staged progress' +assert any(token in log.lower() for token in ('age', 'deck', '缺失', '清洗')), 'progress log missing cleaning stage' +assert any(token in log.lower() for token in ('report', '报告')), 'progress log missing report stage' diff --git a/task_025/acceptance_checklist.json b/task_025/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..fc4923322c6435046e6d68712de01c5c72db6aec --- /dev/null +++ b/task_025/acceptance_checklist.json @@ -0,0 +1,22 @@ +{ + "task_id": 41, + "category": "data_analysis", + "language": "python", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Python files compile; data-analysis tasks generate the requested output files from fixture data." + ], + "input_assets": [ + "gapminderDataFiveYear.csv" + ], + "expected_outputs": [ + "*.json", + "report.html" + ], + "risk_notes": [ + "Input assets are separated from candidate outputs; do not score candidates merely for recreating input files." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_025/environment/Dockerfile b/task_025/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b5c3125aadc8adae6187cdea0ad0c6d3cf3e505e --- /dev/null +++ b/task_025/environment/Dockerfile @@ -0,0 +1,7 @@ +FROM mcr.microsoft.com/playwright:v1.52.0-noble +USER root +RUN apt-get update && apt-get install -y --no-install-recommends python3-numpy python3-pil && ln -sf /usr/bin/python3 /usr/local/bin/python && rm -rf /var/lib/apt/lists/* +RUN npm install --global --prefix /usr playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules +WORKDIR /app +COPY ./code /app diff --git a/task_025/environment/code/gapminderDataFiveYear.csv b/task_025/environment/code/gapminderDataFiveYear.csv new file mode 100644 index 0000000000000000000000000000000000000000..533293ab3387ef0f992142c87420fd9a0b8798c3 --- /dev/null +++ b/task_025/environment/code/gapminderDataFiveYear.csv @@ -0,0 +1,13 @@ +country,year,pop,continent,lifeExp,gdpPercap,gdpTotal +China,1952,556263527,Asia,44.0,400.4,222727916210.8 +China,2007,1318683096,Asia,72.9,4959.1,6539481341373.6 +India,1952,372000000,Asia,37.9,546.6,203335200000 +India,2007,1110000000,Asia,65.5,2452.2,2721942000000 +United States,1952,157553000,Americas,68.4,13990.5,2204245246500 +United States,2007,301139947,Americas,78.2,42951.7,12934472661559.9 +Brazil,1952,56000000,Americas,50.9,2108.9,118098400000 +Brazil,2007,190000000,Americas,72.4,9065.1,1722369000000 +Germany,1952,69145952,Europe,67.5,7144.1,493985595683.2 +Germany,2007,82400996,Europe,79.4,32170.4,2650873001718.4 +France,1952,42000000,Europe,67.4,7029.8,295251600000 +France,2007,61000000,Europe,80.7,30470.0,1858670000000 diff --git a/task_025/environment/docker-compose.yaml b/task_025/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_025/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_025/instruction.md b/task_025/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8c31dced097cbe3a58ae7c452e518450b148db8c --- /dev/null +++ b/task_025/instruction.md @@ -0,0 +1,19 @@ +# Gapminder population and longevity report + +Write an offline Python analysis of `gapminderDataFiveYear.csv` in the project root. Provide a runnable entry script (for example `main.py` or `solve.py`) and generate a JSON export and a directly openable `report.html` beside the input. If there is more than one root Python file and no unique `main.py` or `solve.py`, write the entry script’s filename on one line in `entrypoint.txt`. You can also use that file to select a different entry explicitly. + +## Calculations + +Export one JSON record for each 2007 country. Keep every original CSV column under its original name and preserve its value, including `country`, `year`, `pop`, `continent`, `lifeExp`, `gdpPercap`, and `gdpTotal`. Equivalent number formats and numeric strings are accepted for numeric columns. Add a separate `gdp_per_capita` field computed as `gdpTotal / pop`; it should agree with `gdpPercap`. Compute the arithmetic mean 2007 population for each continent. Compare the same country's population in 1952 and 2007 and identify the country with the largest absolute increase in people, not the largest percentage growth. + +## Report interface + +- Use an SVG with `id="gdp-life-scatter"` for one mark per 2007 country. Marks carry `data-country`, `data-continent`, `data-gdp`, and `data-life`. Use per-capita GDP on the x-axis (linear or explicitly labeled log) and life expectancy on the linear y-axis, increasing rightward and upward. Show numeric ticks and visible labels with IDs `gdp-axis-label` and `life-axis-label`. In the visible legend with `id="continent-legend"`, use one labeled `data-continent` entry per continent, with its text color or SVG fill matching the distinct color of its marks. +- Display the means in `` and ``. Each data row and bar carries `data-continent` and `data-mean-pop`. Use one `` per continent with numeric `width` and `height`; reserve rectangles in this SVG for bars. Draw horizontal or vertical bars on a common zero-based scale. +- Display the fastest-growing country's name and increase in an element with `id="fastest-growth"`, `data-country`, and `data-absolute-growth`. + +## Acceptance Checklist + +- The JSON export contains exactly the 2007 records with all original column names and values, plus the independently computed `gdp_per_capita`. +- Scatter marks are visible, correctly scaled and colored by continent, with matching labels and legend. +- Table means and bar lengths represent the actual continent populations. The report identifies the correct country and absolute increase. diff --git a/task_025/quality_notes.md b/task_025/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..393a7eb36e828d66b6c4a695d30eac59285b8f73 --- /dev/null +++ b/task_025/quality_notes.md @@ -0,0 +1,3 @@ +# Quality Notes + +- Input assets are separated from candidate outputs; do not score candidates merely for recreating input files. \ No newline at end of file diff --git a/task_025/solution/README.md b/task_025/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_025/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_025/solution/code/solve.py b/task_025/solution/code/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..9c78aec13b033dc74b525587ead4c7dab76452fc --- /dev/null +++ b/task_025/solution/code/solve.py @@ -0,0 +1,116 @@ +import csv, json, statistics +from html import escape + +rows = list(csv.DictReader(open('gapminderDataFiveYear.csv', encoding='utf-8-sig'))) +rows2007 = [r for r in rows if str(r.get('year')) == '2007'] +for row in rows2007: + row['gdp_per_capita'] = round(float(row['gdpTotal']) / float(row['pop']), 6) + +with open('gapminder_2007.json', 'w', encoding='utf-8') as f: + json.dump(rows2007, f, ensure_ascii=False, indent=2) + +gdp = [float(r['gdp_per_capita']) for r in rows2007] +life = [float(r.get('lifeExp') or r.get('life') or 0) for r in rows2007] + +# Aggregate 2007 metrics by continent: mean life expectancy and mean GDP per +# capita for each continent, sorted by life expectancy. +by_continent = {} +for r in rows2007: + continent = r.get('continent') or 'Unknown' + entry = by_continent.setdefault(continent, {'life': [], 'gdp': [], 'pop': []}) + entry['life'].append(float(r.get('lifeExp') or r.get('life') or 0)) + entry['gdp'].append(float(r['gdp_per_capita'])) + entry['pop'].append(float(r.get('pop') or 0)) + +continent_stats = [] +for continent, vals in by_continent.items(): + continent_stats.append({ + 'continent': continent, + 'countries': len(vals['life']), + 'mean_lifeExp': round(statistics.mean(vals['life']), 2) if vals['life'] else 0, + 'mean_gdpPercap': round(statistics.mean(vals['gdp']), 2) if vals['gdp'] else 0, + 'mean_population': round(statistics.mean(vals['pop']), 2) if vals['pop'] else 0, + }) +continent_stats.sort(key=lambda c: c['mean_lifeExp'], reverse=True) + +by_country = {} +for row in rows: + by_country.setdefault(row['country'], {})[row['year']] = float(row['pop']) +growth = {country: years['2007'] - years['1952'] for country, years in by_country.items() + if '1952' in years and '2007' in years} +fastest_growth_country = max(growth, key=growth.get) + +with open('continent_2007_stats.csv', 'w', newline='', encoding='utf-8') as f: + writer = csv.DictWriter(f, fieldnames=['continent', 'countries', 'mean_lifeExp', 'mean_gdpPercap', 'mean_population']) + writer.writeheader() + writer.writerows(continent_stats) + +palette = {'Asia': '#2563eb', 'Americas': '#db2777', 'Europe': '#15803d'} +min_gdp, max_gdp = min(gdp), max(gdp) +min_life, max_life = min(life), max(life) +points = [] +axis_labels = ( + '' + f'{min_gdp:.0f}' + f'{max_gdp:.0f}' + 'GDP per capita' + f'{min_life:.1f}' + f'{max_life:.1f}' + 'Life expectancy (years)' +) +legend = '
      ' + ' · '.join( + f'● {escape(continent)}' + for continent, color in palette.items()) + '
      ' +for row in rows2007: + country = escape(row['country']) + continent = escape(row['continent']) + per_capita = float(row['gdp_per_capita']) + life_exp = float(row['lifeExp']) + x = 65 + (per_capita - min_gdp) / max(max_gdp - min_gdp, 1) * 500 + y = 280 - (life_exp - min_life) / max(max_life - min_life, 1) * 220 + points.append( + f'' + f'{country}: GDP/person {per_capita:.1f}, life {life_exp:.1f}' + ) + +rows_html = [] +bars = [] +max_population = max(item['mean_population'] for item in continent_stats) +for index, item in enumerate(continent_stats): + continent = escape(item['continent']) + mean_population = item['mean_population'] + rows_html.append( + f'' + f'' + ) + y = 15 + index * 42 + bars.append( + f'{continent}' + f'' + ) + +report = ( + 'Gapminder 2007 report' + '
      ' + '

      2007 GDP per capita and life expectancy

      ' + f'

      ' + f'Fastest absolute population growth (1952–2007): {escape(fastest_growth_country)}, ' + f'+{growth[fastest_growth_country]:,.0f} people.

      ' + '

      GDP per capita vs life expectancy by continent

      ' + '' + + axis_labels + ''.join(points) + '' + legend + + '

      Mean population by continent, 2007

      ' + '
      {continent}{item["countries"]}{mean_population:,.2f}
      ' + + ''.join(rows_html) + '
      ContinentCountriesMean population
      ' + f'' + + ''.join(bars) + '' +) +with open('report.html', 'w', encoding='utf-8') as handle: + handle.write(report) diff --git a/task_025/solution/solve.sh b/task_025/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_025/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_025/task.toml b/task_025/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_025/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_025/task_meta.json b/task_025/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..bd1c82fbe8d9b86230902d611f92ef0f382f40a8 --- /dev/null +++ b/task_025/task_meta.json @@ -0,0 +1,22 @@ +{ + "task_id": 41, + "task_category": "data_analysis", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 1, + "language": "python", + "tool_files_from_selected_trace": [ + "gapminderDataFiveYear.csv", + "gapminder_analysis.py" + ], + "input_assets": [ + "gapminderDataFiveYear.csv" + ], + "expected_outputs": [ + "*.json", + "report.html" + ], + "source_row_id": 246, + "repair_revision": "2026-09-29", + "instruction_sha256": "69cd628f7dfad94a452776766ef0a7ef353a128d0f61b68c5fccd38f910e67f4" +} diff --git a/task_025/tests/_shared/contract_checker.js b/task_025/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_025/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_025/tests/_shared/static_enhancer.sh b/task_025/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_025/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_025/tests/analysis_entry.py b/task_025/tests/analysis_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..7a92f05bc4e7cc631c7b71ec36fc28fc5529ce25 --- /dev/null +++ b/task_025/tests/analysis_entry.py @@ -0,0 +1,36 @@ +"""Locate the declared Python analysis and run it with bounded time.""" + +import os +import subprocess +import sys +from pathlib import Path + + +def entry_script(root): + declaration = root / "entrypoint.txt" + if declaration.is_file(): + name = declaration.read_text(encoding="utf-8").strip() + assert name and not any(character in name for character in "\r\n"), "entrypoint.txt needs one filename" + entry = root / name + assert entry.parent == root and entry.suffix == ".py", "declare a root Python script" + assert entry.is_file(), f"declared script {name!r} does not exist" + else: + scripts = list(root.glob("*.py")) + conventional = [path for path in scripts if path.name in {"solve.py", "main.py"}] + options = conventional or scripts + assert len(options) == 1, "provide one unambiguous entry or declare it in entrypoint.txt" + entry = options[0] + assert entry.resolve().parent == root.resolve(), "entry script must be inside the project root" + return entry + + +def run_analysis(root): + entry = entry_script(root) + env = {name: value for name, value in os.environ.items() + if name.lower() not in {"http_proxy", "https_proxy", "all_proxy"}} + env["PYTHONHASHSEED"] = "1" + subprocess.run([sys.executable, entry.name], cwd=root, env=env, timeout=60, check=True) + + +if __name__ == "__main__": + run_analysis(Path.cwd()) diff --git a/task_025/tests/enhancement_cases.json b/task_025/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..90aa4caa9693b45a3ce7509fdb138498a0c53333 --- /dev/null +++ b/task_025/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "筛选出 2007 年的数据。\n将 2007 年的数据导出为 JSON 文件。", + "validator": "tests/validate_enhancement.py::case_complete_2007_json_slice", + "验证行为": "自动定位结果 JSON,验证其无重复地包含且只包含 fixture 的全部 2007 国家记录。" + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "绘制人均 GDP 与预期寿命的散点图,颜色区分大洲。\n创建新列 gdp_per_capita(GDP 总量 / 人口)。", + "validator": "tests/validate_enhancement.py::case_scatter_fields_and_per_capita_values", + "验证行为": "逐国核对导出记录保留 CSV 原始列名和值,包括 gdpPercap 和 gdpTotal;另核对独立计算的 gdp_per_capita。" + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "筛选出 2007 年的数据,绘制人均 GDP 与预期寿命的散点图,颜色区分大洲。\n所有输出的文件全部写入当前 dir, 然后通过脚本最终输出一个包含上面所有任务结果的 report.html 出来。", + "validator": "tests/validate_enhancement.py::case_continent_gdp_life_report", + "验证行为": "从 fixture 重算各洲 2007 年 GDP/预期寿命结果,验证 report.html 包含 2007、全部大洲及对应数值。" + } +] diff --git a/task_025/tests/test.sh b/task_025/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ecaaa53c952e6d30f4b639ab67a37dd0670a1d7e --- /dev/null +++ b/task_025/tests/test.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +export NODE_PATH="${NODE_PATH:-$(npm root -g 2>/dev/null)}" +echo 0 > "$LOG_DIR/reward.txt" +if python3 "$TEST_DIR/validate_fresh_run.py"; then + echo 1 > "$LOG_DIR/reward.txt" +fi diff --git a/task_025/tests/validate_aaav_dynamic.js b/task_025/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..01f6e33f2b38ac21d062ecb1285045e4a82ca86d --- /dev/null +++ b/task_025/tests/validate_aaav_dynamic.js @@ -0,0 +1,101 @@ +const {chromium} = require('playwright'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const {pathToFileURL} = require('node:url'); + +function affineFit(values, positions, increasing) { + const xMean = values.reduce((a, b) => a + b, 0) / values.length; + const yMean = positions.reduce((a, b) => a + b, 0) / positions.length; + const variance = values.reduce((sum, x) => sum + (x - xMean) ** 2, 0); + if (!variance) return positions.every(y => Math.abs(y - yMean) <= 1); + const slope = values.reduce((sum, x, i) => sum + (x - xMean) * (positions[i] - yMean), 0) / variance; + return (increasing ? slope > 0 : slope < 0) && values.every((x, i) => + Math.abs(positions[i] - (yMean + slope * (x - xMean))) <= 1); +} + +(async () => { + const browser = await chromium.launch({headless: true, args: ['--no-sandbox']}); + try { + const page = await browser.newPage({viewport: {width: 1100, height: 760}}); + await page.route(/^https?:/, route => route.abort()); + await page.goto(pathToFileURL(path.join(process.cwd(), 'report.html')).href); + const allVisible = await page.locator('#gdp-life-scatter, #gdp-life-scatter [data-country], #continent-population-bars, #continent-population-bars rect').evaluateAll(elements => elements.every(element => { + for (let node = element; node; node = node.parentElement) { + const style = getComputedStyle(node); + if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) return false; + } + return true; + })); + assert(allVisible, 'chart or marks are hidden by their ancestors'); + const points = await page.locator('#gdp-life-scatter [data-country]').evaluateAll(elements => elements.map(element => { + const box = element.getBoundingClientRect(), style = getComputedStyle(element); + return {country: element.dataset.country, continent: element.dataset.continent, + gdp: Number(element.dataset.gdp), life: Number(element.dataset.life), + x: box.x + box.width / 2, y: box.y + box.height / 2, color: style.fill, + visible: box.width > 0 && box.height > 0 && style.display !== 'none' && style.visibility !== 'hidden' && Number(style.opacity) > 0}; + })); + assert(points.length && points.every(point => point.visible), 'every country needs a visible scatter mark'); + const colors = new Map(); + for (const point of points) { + assert(point.color !== 'none' && point.color !== 'rgba(0, 0, 0, 0)', 'scatter mark has no visible color'); + if (!colors.has(point.continent)) colors.set(point.continent, point.color); + assert.equal(colors.get(point.continent), point.color, 'continent colors are inconsistent'); + } + assert.equal(new Set(colors.values()).size, colors.size, 'continents must have distinct colors'); + for (const id of ['gdp-axis-label', 'life-axis-label']) { + const label = page.locator('#' + id); + assert(await label.isVisible() && (await label.textContent()).trim(), 'scatter axes need visible labels'); + } + const ticks = await page.locator('#gdp-life-scatter text:visible, #gdp-life-scatter foreignObject:visible') + .evaluateAll(labels => labels.filter(label => { + const style = getComputedStyle(label); + return label.getBoundingClientRect().width > 0 && Number(style.opacity) > 0 + && /^[-+−]?[$€£]?\s*\d[\d,.\s]*(?:[eE][+-]?\d+|[kKmMbB万亿])?$/.test(label.textContent.trim()); + }).length); + assert(ticks >= 2, 'scatter chart must display numeric tick labels'); + for (const [continent, color] of colors) { + const legend = page.locator('#continent-legend [data-continent]').filter({hasText: continent}); + assert(await legend.count() === 1 && await legend.isVisible(), 'each continent needs a visible color legend'); + assert(await legend.evaluate(element => { + const style = getComputedStyle(element); return [style.color, style.fill]; + }).then(values => values.includes(color)), 'legend color must agree with plotted continent'); + } + const gdp = points.map(point => point.gdp), x = points.map(point => point.x); + const linear = affineFit(gdp, x, true); + const logarithmic = affineFit(gdp.map(Math.log), x, true); + assert(linear || logarithmic, 'scatter horizontal position does not encode GDP'); + if (!linear) assert(/log|对数/i.test(await page.locator('body').innerText()), 'logarithmic axis must be labeled'); + assert(affineFit(points.map(point => point.life), points.map(point => point.y), false), 'scatter vertical position does not encode life expectancy'); + for (const selector of ['#continent-population', '#continent-population-bars', '#fastest-growth']) + assert(await page.locator(selector).isVisible(), `${selector} is hidden`); + const fastest = page.locator('#fastest-growth'); + const visibleNumbers = text => Array.from(text.matchAll(/([+-]?\d[\d,]*(?:\.\d+)?(?:e[+-]?\d+)?)\s*(billion|million|千|万|亿)?/gi), + match => Number(match[1].replaceAll(',', '')) * + ({billion: 1e9, million: 1e6, 千: 1e3, 万: 1e4, 亿: 1e8}[match[2]?.toLowerCase()] ?? 1)); + const growthText = await fastest.innerText(); + assert(growthText.includes(await fastest.getAttribute('data-country')), 'fastest-growth country exists only in metadata'); + const growth = Number(await fastest.getAttribute('data-absolute-growth')); + assert(visibleNumbers(growthText).some(value => Math.abs(value - growth) <= Math.max(0.51, Math.abs(growth) * 1e-6)), + 'the fastest-growing country must show its increase in people'); + const populationRows = page.locator('#continent-population tr[data-continent]'); + for (const row of await populationRows.all()) { + const {continent, mean, visibleCells} = await row.evaluate(element => ({ + continent: element.dataset.continent, + mean: Number(element.dataset.meanPop), + visibleCells: Array.from(element.cells).filter(cell => { + const style = getComputedStyle(cell); + return cell.getClientRects().length && style.visibility !== 'hidden' && Number(style.opacity) > 0; + }).map(cell => cell.innerText), + })); + assert(await row.isVisible() && visibleCells.some(text => text.includes(continent)), 'continent must be visible on its population row'); + const displayed = visibleCells.flatMap(visibleNumbers); + assert(displayed.some(value => Math.abs(value - mean) <= Math.max(0.51, Math.abs(mean) * 1e-6)), + `population table must display ${continent}'s mean on that row`); + } + fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + await page.screenshot({path: `/logs/verifier/visual-audit/${process.env.GAPMINDER_SCREENSHOT || 'gapminder-report'}.png`, fullPage: true}); + } finally { + await browser.close(); + } +})().catch(error => {console.error(error); process.exit(1)}); diff --git a/task_025/tests/validate_enhancement.py b/task_025/tests/validate_enhancement.py new file mode 100644 index 0000000000000000000000000000000000000000..9f203cc43bf4755a9e9ac35bfc1dd5fc6e5f5351 --- /dev/null +++ b/task_025/tests/validate_enhancement.py @@ -0,0 +1,284 @@ +import csv +import json +import math +import pathlib +import re +import sys +from decimal import Decimal, InvalidOperation +from html.parser import HTMLParser + + +ROOT = pathlib.Path.cwd() +NUMERIC_COLUMNS = {'year', 'pop', 'lifeExp', 'gdpPercap', 'gdpTotal'} + + +def read_csv(path): + with path.open(encoding="utf-8-sig", newline="") as handle: + return list(csv.DictReader(handle)) + + +def record_candidates(value): + """Yield common JSON table orientations without binding to pandas.""" + if isinstance(value, list) and value and all(isinstance(item, dict) for item in value): + yield value + if not isinstance(value, dict) or not value: + return + values = list(value.values()) + if values and all(isinstance(item, dict) for item in values): + yield values + index_sets = [set(item) for item in values] + if index_sets and all(index == index_sets[0] for index in index_sets): + yield [{column: value[column][index] for column in value} for index in sorted(index_sets[0], key=str)] + data = value.get("data") + if isinstance(data, list) and data: + if all(isinstance(item, dict) for item in data): + yield data + columns = value.get("columns") + if ( + isinstance(columns, list) + and all(isinstance(column, str) for column in columns) + and len(set(columns)) == len(columns) + and all(isinstance(item, list) and len(item) == len(columns) for item in data) + ): + yield [dict(zip(columns, item)) for item in data] + + +def expected_2007(): + rows = [row for row in read_csv(ROOT / "gapminderDataFiveYear.csv") if row.get("year", "").strip() == "2007"] + assert rows, "fixture must contain 2007 records" + return {row["country"]: row for row in rows} + + +def matching_exports(expected): + for path in sorted(ROOT.glob("*.json")): + try: + document = json.loads(path.read_text(encoding="utf-8"), parse_float=Decimal) + except (OSError, json.JSONDecodeError): + continue + for records in record_candidates(document): + countries = {record["country"] for record in records if isinstance(record.get("country"), str)} + if countries == expected.keys() and len(records) == len(expected): + yield records + + +def decimal_value(value, label): + try: + number = Decimal(str(value).strip()) + except InvalidOperation as exc: + raise AssertionError(f"{label} is not numeric") from exc + assert number.is_finite(), f"{label} is not finite" + return number + + +def check_source_value(column, value, original, country): + label = f"{country}: {column}" + if column not in NUMERIC_COLUMNS: + assert value == original, f"{label}: expected {original!r}, got {value!r}" + return + actual = decimal_value(value, label) + expected = Decimal(original) + if actual == expected: + return + # Allow normal binary float round trips for measured values. Year and population are integers. + tolerance = 0 if column in {"year", "pop"} else Decimal(str(4 * math.ulp(float(expected)))) + assert abs(actual - expected) <= tolerance, f"{label}: expected {expected}, got {actual}" + + +def require_export(expected, check): + error = None + for records in matching_exports(expected): + try: + for record in records: + check(record, expected[record["country"]]) + return + except AssertionError as exc: + if error is None: + error = str(exc) + raise AssertionError(error or "no JSON export matches the fixture's 2007 country set and row count") + + +def assert_close(got, want, label, tolerance=1e-6): + assert math.isfinite(got), f"{label} is not finite" + assert abs(got - want) <= max(tolerance, abs(want) * 1e-9), f"{label}: expected {want}, got {got}" + + +def report_has_number_near(report, label, value): + starts = [match.start() for match in re.finditer(re.escape(label.lower()), report)] + number = re.compile(r"(? 0 for value in sizes[continent]), f"{continent} has invalid bar size" + def proportional(dimension): + ratios = [sizes[continent][dimension] / means[continent] for continent in continents] + return max(ratios) - min(ratios) <= max(ratios) * 0.01 + assert proportional(0) or proportional(1), "bar lengths must share a zero-origin population scale" + + all_rows = read_csv(ROOT / "gapminderDataFiveYear.csv") + growth = {} + for country in {row["country"] for row in all_rows}: + years = {row["year"]: float(row["pop"]) for row in all_rows if row["country"] == country} + if "1952" in years and "2007" in years: + growth[country] = years["2007"] - years["1952"] + fastest = max(growth, key=growth.get) + assert parsed.fastest and parsed.fastest.get("data-country") == fastest, "fastest-growth conclusion is wrong" + assert_close(float(parsed.fastest.get("data-absolute-growth", "nan")), growth[fastest], "absolute growth") + + +CASES = [ + ("ENHANCED_CASE_1", case_complete_2007_json_slice), + ("ENHANCED_CASE_2", case_scatter_fields_and_per_capita_values), + ("ENHANCED_CASE_3", case_continent_population_and_growth_report), + ("ENHANCED_CASE_4", case_actual_visuals), +] + + +if __name__ == "__main__": + failures = [] + requested = set(sys.argv[1:]) + known = {case_id for case_id, _ in CASES} + assert requested <= known, f"unknown case id(s): {sorted(requested - known)}" + for case_id, validator in CASES: + if requested and case_id not in requested: + continue + try: + validator() + print(f"{case_id}: PASS") + except Exception as exc: + failures.append((case_id, exc)) + print(f"{case_id}: FAIL: {exc}", file=sys.stderr) + if failures: + raise SystemExit(1) diff --git a/task_025/tests/validate_fresh_run.py b/task_025/tests/validate_fresh_run.py new file mode 100644 index 0000000000000000000000000000000000000000..047738af0734db4e3f179d00d33477c4bb2649a7 --- /dev/null +++ b/task_025/tests/validate_fresh_run.py @@ -0,0 +1,83 @@ +"""Regenerate the report and validate it again against changed data.""" + +import csv +import json +import os +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +from analysis_entry import run_analysis + + +def candidate_field_sets(data): + if isinstance(data, list) and data and isinstance(data[0], dict): + yield set(data[0]) + if isinstance(data, dict): + yield set(data) + for item in data.values(): + if isinstance(item, dict): + yield set(item) + if isinstance(data.get("columns"), list): + yield set(str(column) for column in data["columns"]) + if isinstance(data.get("data"), list): + yield from candidate_field_sets(data["data"]) + + +def clear_generated_reports(root): + (root / "report.html").unlink(missing_ok=True) + for path in root.glob("*.json"): + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (ValueError, OSError): + continue + if any({"country", "year", "continent"} <= fields for fields in candidate_field_sets(data)): + path.unlink() + + +def generate(root): + source = root / "gapminderDataFiveYear.csv" + original = source.read_bytes() + clear_generated_reports(root) + run_analysis(root) + assert source.read_bytes() == original, "analysis must preserve the input CSV" + + +def run_validators(root, screenshot): + for script in ("validate_outputs.py", "validate_enhancement.py"): + subprocess.run([sys.executable, str(TESTS / script)], cwd=root, check=True, timeout=20) + env = {**os.environ, "GAPMINDER_SCREENSHOT": screenshot} + subprocess.run(["node", str(TESTS / "validate_aaav_dynamic.js")], cwd=root, env=env, check=True, timeout=45) + + +def mutate_input(root): + source = root / "gapminderDataFiveYear.csv" + with source.open(encoding="utf-8-sig", newline="") as handle: + reader = csv.DictReader(handle) + fields, rows = reader.fieldnames, list(reader) + changed = next(row for row in rows if row["year"] == "2007") + population = int(float(changed["pop"])) + 200_017 + changed["pop"] = str(population) + gdp_per_capita = float(changed["gdpPercap"]) * 1.14 + changed["gdpPercap"] = repr(gdp_per_capita) + changed["gdpTotal"] = repr(gdp_per_capita * population) + changed["lifeExp"] = repr(float(changed["lifeExp"]) - 1.7) + with source.open("w", encoding="utf-8", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=fields) + writer.writeheader() + writer.writerows(reversed(rows)) + + +if __name__ == "__main__": + TESTS = Path(__file__).resolve().parent + root = Path.cwd() + generate(root) + run_validators(root, "gapminder-report") + with tempfile.TemporaryDirectory(prefix="gapminder-") as directory: + work = Path(directory) / "candidate" + shutil.copytree(root, work, ignore=shutil.ignore_patterns("tests", "logs", "__pycache__", ".git")) + mutate_input(work) + generate(work) + run_validators(work, "gapminder-report-mutated") diff --git a/task_025/tests/validate_outputs.py b/task_025/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..8cc0bce4b563c45b4bf0e7107df9c4685bc3d7b0 --- /dev/null +++ b/task_025/tests/validate_outputs.py @@ -0,0 +1,9 @@ +from pathlib import Path + +from validate_enhancement import case_complete_2007_json_slice + + +case_complete_2007_json_slice() +report = Path("report.html").read_text(encoding="utf-8").lower() +assert "2007" in report, "report missing 2007 analysis" +assert "gdp" in report and ("life" in report or "预期" in report), "report missing GDP/life analysis" diff --git a/task_026/acceptance_checklist.json b/task_026/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..c0affdb3a606e9549ac4fd3035fa4e46f8579469 --- /dev/null +++ b/task_026/acceptance_checklist.json @@ -0,0 +1,24 @@ +{ + "task_id": 42, + "category": "data_analysis", + "language": "python", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Python files compile; data-analysis tasks generate the requested output files from fixture data." + ], + "input_assets": [ + "BostonHousing.txt", + "titanic.csv" + ], + "expected_outputs": [ + "boston_clean.csv", + "report.html", + "titanic_clean.csv" + ], + "risk_notes": [ + "Input assets are separated from candidate outputs; do not score candidates merely for recreating input files." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_026/environment/Dockerfile b/task_026/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b5c3125aadc8adae6187cdea0ad0c6d3cf3e505e --- /dev/null +++ b/task_026/environment/Dockerfile @@ -0,0 +1,7 @@ +FROM mcr.microsoft.com/playwright:v1.52.0-noble +USER root +RUN apt-get update && apt-get install -y --no-install-recommends python3-numpy python3-pil && ln -sf /usr/bin/python3 /usr/local/bin/python && rm -rf /var/lib/apt/lists/* +RUN npm install --global --prefix /usr playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules +WORKDIR /app +COPY ./code /app diff --git a/task_026/environment/code/BostonHousing.txt b/task_026/environment/code/BostonHousing.txt new file mode 100644 index 0000000000000000000000000000000000000000..f82845b3e74a8b7dba05403494ec29f02a3ca459 --- /dev/null +++ b/task_026/environment/code/BostonHousing.txt @@ -0,0 +1,14 @@ +crim zn indus chas nox rm age dis rad tax ptratio b lstat medv +0.00632 18.0 2.31 0 0.538 6.575 65.2 4.0900 1 296 15.3 396.90 4.98 24.0 +0.02731 0.0 7.07 0 0.469 6.421 78.9 4.9671 2 242 17.8 396.90 9.14 21.6 +0.02729 0.0 7.07 0 0.469 7.185 61.1 4.9671 2 242 17.8 392.83 4.03 34.7 +0.03237 0.0 2.18 0 0.458 6.998 45.8 6.0622 3 222 18.7 394.63 2.94 33.4 +0.06905 0.0 2.18 0 0.458 7.147 54.2 6.0622 3 222 18.7 396.90 5.33 36.2 +0.02985 0.0 2.18 0 0.458 6.430 58.7 6.0622 3 222 18.7 394.12 5.21 28.7 +0.08829 12.5 7.87 0 0.524 6.012 66.6 5.5605 5 311 15.2 395.60 12.43 19.2 +0.14455 12.5 7.87 0 0.524 6.172 96.1 5.9505 5 311 15.2 396.90 19.15 17.8 +0.21124 12.5 7.87 0 0.524 5.631 100.0 6.0821 5 311 15.2 386.63 29.93 16.5 +0.17004 12.5 7.87 0 0.524 6.004 85.9 6.5921 5 311 15.2 386.71 17.10 18.9 +0.22489 12.5 7.87 0 0.524 6.377 94.3 6.3467 5 311 15.2 392.52 20.45 15.0 +0.11747 12.5 7.87 0 0.524 6.009 82.9 6.2267 5 311 15.2 396.90 13.27 18.3 +0.09378 12.5 7.87 0 0.524 5.889 39.0 5.4509 5 311 15.2 390.50 15.71 99.0 diff --git a/task_026/environment/code/titanic.csv b/task_026/environment/code/titanic.csv new file mode 100644 index 0000000000000000000000000000000000000000..b9d4de05baa0a17ad9b3abef78efc3bdc94e841b --- /dev/null +++ b/task_026/environment/code/titanic.csv @@ -0,0 +1,9 @@ +survived,pclass,sex,age,sibsp,parch,fare,embarked,class,deck +1,1,female,29,0,0,211.3375,S,First,C +0,3,male,22,0,0,7.2500,S,Third, +1,2,female,34,1,1,26.2500,C,Second,D +0,1,male,,1,0,73.5000,C,First, +1,3,female,19,0,0,8.0500,Q,Third, +0,2,male,42,0,0,13.0000,S,Second,E +1,1,female,,0,1,80.0000,S,First, +0,3,male,31,2,0,15.5000,Q,Third, diff --git a/task_026/environment/docker-compose.yaml b/task_026/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_026/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_026/instruction.md b/task_026/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8f0950f0f290bac2030951387fa7b56977cfe737 --- /dev/null +++ b/task_026/instruction.md @@ -0,0 +1,25 @@ +# Boston housing and Titanic analysis + +Run the analysis as `python3 solve.py` from the project root using `BostonHousing.txt` (whitespace-delimited with a header) and `titanic.csv`. Work offline and do not change the inputs. Recompute `boston_clean.csv`, `titanic_clean.csv`, and `report.html` whenever inputs change. Print clear progress for the processing stages. + +## Boston housing + +- Calculate Q1 and Q3 of `medv` by linear interpolation at sorted positions `(n-1) × q`. Keep records within the inclusive fences Q1 − 1.5×IQR and Q3 + 1.5×IQR, preserving the original fields. Add `rm_rounded` by rounding positive room counts to the nearest integer, with half values rounded up. +- On the raw data compute Pearson r between each other numeric feature and `medv`; rank the top three by absolute correlation, using the feature name to break ties. On the cleaned data calculate mean `medv` for each `rm_rounded` group. +- Plot every cleaned observation with `rm` on x, `medv` on y, and the fitted least-squares line. Use independent SVG marks or Canvas 2D circles, ellipses or rectangles at most 20 px across. Use a plot spanning at least 50 px in each direction, with no decorative marks in the data series. Both linear axes increase right/up and have at least two numeric ticks consistent with the plotted coordinates (x below, y to the left). + +## Titanic + +Resolve missing `age` and `deck` by imputation or dropping only affected rows. Keep all complete rows, preserve other fields and observed values, and use finite imputed ages within the observed range. Treat `embarked` and `class` as categorical; pandas is optional and CSV need not encode dtypes. Add `is_alone`, true exactly when `sibsp + parch == 0`. + +Use the cleaned rows to compute survival rates for each sex-by-class combination. Draw one bar for each combination, labeled below with both sex and class, including groups with zero rate. Heights share a zero baseline and a linear scale; show 0 and 1 (or 0% and 100%) on the left axis. + +## Report and acceptance + +Use visible, legible HTML tables with a single header row and no merged data cells. Labels may be equivalent English or Chinese; table IDs, row order and styling are unrestricted. Show measurements to at least two decimal places (counts exact); percentages are acceptable for survival rates. Keep tables and graphics fully visible. + +## Acceptance Checklist + +- Boston CSV contains all and only in-fence records with unchanged data and correct half-up room groups. The report shows the five `Metric / Value` entries Q1, Q3, lower, upper and outliers, the top three `Feature / Pearson r`, and `rm_rounded / Mean medv` for all groups. +- Titanic CSV retains complete records, handles missing values and computes `is_alone`. The visible `Sex / Class / Survival rate` table follows the cleaned data. +- The Boston scatter and trend line and the Titanic bars, ticks and group labels represent the computed results. Processing progress is printed, and regenerating results from changed data does not modify the inputs. diff --git a/task_026/quality_notes.md b/task_026/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..393a7eb36e828d66b6c4a695d30eac59285b8f73 --- /dev/null +++ b/task_026/quality_notes.md @@ -0,0 +1,3 @@ +# Quality Notes + +- Input assets are separated from candidate outputs; do not score candidates merely for recreating input files. \ No newline at end of file diff --git a/task_026/solution/README.md b/task_026/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_026/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_026/solution/code/solve.py b/task_026/solution/code/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..8c4ed7f5f7264c3da3db86e15acbacde22dea122 --- /dev/null +++ b/task_026/solution/code/solve.py @@ -0,0 +1,213 @@ +import csv +import html +import math +from collections import defaultdict + + +def quantile(values, fraction): + values = sorted(values) + pos = (len(values) - 1) * fraction + lo, hi = math.floor(pos), math.ceil(pos) + return values[lo] + (values[hi] - values[lo]) * (pos - lo) + + +def pearson(xs, ys): + ax, ay = sum(xs) / len(xs), sum(ys) / len(ys) + num = sum((x - ax) * (y - ay) for x, y in zip(xs, ys)) + den = math.sqrt(sum((x - ax) ** 2 for x in xs) * sum((y - ay) ** 2 for y in ys)) + return num / den if den else 0.0 + + +def write_csv(path, rows): + with open(path, "w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +print("1/4 Read Boston data and detect IQR outliers") +lines = [line.split() for line in open("BostonHousing.txt", encoding="utf-8-sig") if line.strip()] +header = lines[0] +boston = [dict(zip(header, values)) for values in lines[1:] if len(values) == len(header)] +prices = [float(row["medv"]) for row in boston] +q1, q3 = quantile(prices, .25), quantile(prices, .75) +low, high = q1 - 1.5 * (q3 - q1), q3 + 1.5 * (q3 - q1) +outliers = [row for row in boston if not low <= float(row["medv"]) <= high] +clean = [row.copy() for row in boston if low <= float(row["medv"]) <= high] +for row in clean: + row["rm_rounded"] = str(math.floor(float(row["rm"]) + 0.5)) +write_csv("boston_clean.csv", clean) +print(f"Boston rows={len(boston)}, outliers={len(outliers)}, retained={len(clean)}") + +print("2/4 Compute Pearson correlations and room-group means") +correlations = { + name: pearson([float(row[name]) for row in boston], prices) + for name in header if name != "medv" +} +top = sorted(correlations, key=lambda name: (-abs(correlations[name]), name))[:3] +rooms = defaultdict(list) +for row in clean: + rooms[int(row["rm_rounded"])].append(float(row["medv"])) +means = {room: sum(values) / len(values) for room, values in rooms.items()} + +print("3/4 Clean Titanic and group survival outcomes") +with open("titanic.csv", newline="", encoding="utf-8-sig") as handle: + titanic = list(csv.DictReader(handle)) +ages = [float(row["age"]) for row in titanic if row.get("age", "").strip()] +age_fill = quantile(ages, .5) +for row in titanic: + row["age"] = row.get("age") or str(age_fill) + row["deck"] = row.get("deck") or "Unknown" + row["is_alone"] = str(int(float(row["sibsp"]) + float(row["parch"]) == 0)).lower() +write_csv("titanic_clean.csv", titanic) +groups = defaultdict(list) +for row in titanic: + groups[(row["sex"], row["class"])].append(int(row["survived"])) +rates = {key: sum(values) / len(values) for key, values in groups.items()} + +print("4/4 Render report with offline SVG charts") + + +def table(identifier, columns, rows): + headings = "".join(f"{html.escape(str(value))}" for value in columns) + body = "".join( + "" + "".join(f"{html.escape(str(value))}" for value in row) + "" + for row in rows + ) + return f'{headings}{body}
      ' + + +def svg_text(x, y, label, anchor="middle", extra=""): + return (f'' + f'{html.escape(str(label))}') + + +def scatter_chart(rows): + xs = [float(row["rm"]) for row in rows] + ys = [float(row["medv"]) for row in rows] + xmean, ymean = sum(xs) / len(xs), sum(ys) / len(ys) + denominator = sum((x - xmean) ** 2 for x in xs) + slope = sum((x - xmean) * (y - ymean) for x, y in zip(xs, ys)) / denominator if denominator else 0 + intercept = ymean - slope * xmean + xmin, xmax = min(xs), max(xs) + xlow, xhigh = (xmin, xmax) if xmin != xmax else (xmin - .5, xmax + .5) + # Include the complete fitted segment in the linear y scale, with marker clearance. + ylow = min(min(ys), slope * xmin + intercept, slope * xmax + intercept) + yhigh = max(max(ys), slope * xmin + intercept, slope * xmax + intercept) + padding = max((yhigh - ylow) * .08, .5) + ylow, yhigh = ylow - padding, yhigh + padding + left, right, top_edge, bottom = 68, 494, 22, 238 + + def xpx(value): + return left + (right - left) * (value - xlow) / (xhigh - xlow) + + def ypx(value): + return bottom - (bottom - top_edge) * (value - ylow) / (yhigh - ylow) + + parts = [''] + for index in range(5): + xvalue = xlow + (xhigh - xlow) * index / 4 + yvalue = ylow + (yhigh - ylow) * index / 4 + x, y = xpx(xvalue), ypx(yvalue) + parts.append(f'') + parts.append(f'') + parts.append(svg_text(x, bottom + 22, f"{xvalue:.2f}")) + parts.append(svg_text(left - 10, y + 4, f"{yvalue:.2f}", "end")) + parts.append(f'') + parts.append(svg_text((left + right) / 2, 287, "rm", extra='class="axis-title"')) + parts.append(svg_text(18, 130, "medv", extra='class="axis-title" transform="rotate(-90 18 130)"')) + parts.append(f'') + for x, y in zip(xs, ys): + parts.append(f'') + parts.append('') + return "".join(parts) + + +def survival_chart(group_rates): + groups = sorted(group_rates.items()) + left, right, top_edge, bottom = 68, 500, 22, 212 + slot = (right - left) / len(groups) + bar_width = min(40, slot * .58) + parts = [''] + for rate in (0, .25, .5, .75, 1): + y = bottom - (bottom - top_edge) * rate + parts.append(f'') + parts.append(svg_text(left - 10, y + 4, f"{rate:.0%}", "end")) + parts.append(f'') + parts.append(svg_text(18, 118, "Survival rate", extra='class="axis-title" transform="rotate(-90 18 118)"')) + for index, ((sex, category), rate) in enumerate(groups): + center = left + slot * (index + .5) + height = (bottom - top_edge) * rate + parts.append(f'') + parts.append(svg_text(center, bottom - height - 7, f"{rate:.0%}")) + # Labels exist independently of bar height, including zero-survival groups. + parts.append(f'' + f'{html.escape(sex)} ' + f'{html.escape(category)}') + parts.append(svg_text((left + right) / 2, 287, "Passenger group (sex × class)", extra='class="axis-title"')) + parts.append('') + return "".join(parts) + + +style = """ +* { box-sizing: border-box; } +body { margin: 0; padding: 24px; background: #f3f6fa; color: #1e3044; + font-family: system-ui, -apple-system, sans-serif; font-size: 13px; } +main { max-width: 1120px; margin: auto; } +h1 { margin: 0 0 6px; font-size: 26px; letter-spacing: -.5px; } +h2 { margin: 0 0 12px; font-size: 16px; } +p { line-height: 1.5; } +.subtitle { margin: 0 0 18px; color: #586a7f; } +.summaries, .charts { display: grid; gap: 16px; margin-bottom: 16px; } +.summaries { grid-template-columns: repeat(3, minmax(0, 1fr)); } +.charts { grid-template-columns: repeat(2, minmax(0, 1fr)); align-items: start; } +section { background: white; padding: 16px; border: 1px solid #dbe3ec; border-radius: 12px; } +table { border-collapse: collapse; width: 100%; font-variant-numeric: tabular-nums; } +th, td { text-align: left; padding: 5px 9px; border-bottom: 1px solid #e8edf3; } +th { color: #53677c; font-size: 12px; background: #f5f8fc; } +td:last-child, th:last-child { text-align: right; } +tbody tr:last-child td { border-bottom: 0; } +svg { display: block; width: 100%; height: auto; overflow: visible; } +svg text { font: 11px system-ui, sans-serif; fill: #40546b; } +svg .axis-title { font-size: 12px; font-weight: 600; } +.gridline { stroke: #e5ebf2; stroke-width: 1; } +.axis { fill: none; stroke: #8b9bad; stroke-width: 1; } +.caption { margin: 8px 0 0; color: #586a7f; font-size: 12px; } +@media (max-width: 760px) { body { padding: 12px; } .summaries, .charts { grid-template-columns: 1fr; } } +""" +parts = [ + '', + '', + 'Boston and Titanic analysis', f'
      ', + '

      Boston Housing & Titanic

      ', + f'

      Reproducible data cleaning and group analysis · Boston: {len(clean)} retained / {len(boston)} rows · Titanic: {len(titanic)} rows

      ', + '

      Boston · IQR screening

      ', + table('iqr-summary', ['Metric', 'Value'], [('Q1', f'{q1:.3f}'), ('Q3', f'{q3:.3f}'), + ('lower', f'{low:.3f}'), ('upper', f'{high:.3f}'), ('outliers', str(len(outliers)))]), + '

      Top correlations with medv

      ', + table('correlations', ['Feature', 'Pearson r'], [(name, f'{correlations[name]:.5f}') for name in top]), + '

      Pearson coefficients on the original Boston rows; ranked by absolute value.

      ', + '

      Mean medv by room group

      ', + table('room-means', ['rm_rounded', 'Mean medv'], [(room, f'{mean:.3f}') for room, mean in sorted(means.items())]), + '

      Boston · rooms and home value

      ', + scatter_chart(clean), + f'

      Blue: all {len(clean)} cleaned observations. Red: ordinary least-squares trend. Both axes use linear scales.

      ', + '

      Titanic · survival by passenger group

      ', + survival_chart(rates), + table('survival-rates', ['Sex', 'Class', 'Survival rate'], + [(sex, category, f'{rate:.2%}') for (sex, category), rate in sorted(rates.items())]), + '
      ', +] +with open("report.html", "w", encoding="utf-8") as handle: + handle.write("".join(parts)) diff --git a/task_026/solution/solve.sh b/task_026/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_026/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_026/task.toml b/task_026/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_026/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_026/task_meta.json b/task_026/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..e404316449074bac137870a37cba9535b24e3b8d --- /dev/null +++ b/task_026/task_meta.json @@ -0,0 +1,26 @@ +{ + "task_id": 42, + "task_category": "data_analysis", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 1, + "language": "python", + "tool_files_from_selected_trace": [ + "BostonHousing.txt", + "data_analysis.log", + "data_analysis.py", + "titanic.csv" + ], + "input_assets": [ + "BostonHousing.txt", + "titanic.csv" + ], + "expected_outputs": [ + "boston_clean.csv", + "report.html", + "titanic_clean.csv" + ], + "source_row_id": 252, + "repair_revision": "2026-09-29", + "instruction_sha256": "fd54b2d3f00f1723dbcccc2cedba4254d24ec0c66b006192480d503cceaf5c08" +} diff --git a/task_026/tests/_shared/contract_checker.js b/task_026/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_026/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_026/tests/_shared/static_enhancer.sh b/task_026/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_026/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_026/tests/enhancement_cases.json b/task_026/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..ce42d1040b0a87305121bd20704a106ab9163a19 --- /dev/null +++ b/task_026/tests/enhancement_cases.json @@ -0,0 +1,30 @@ +{ + "review_revision": "2026-10-08", + "cases": [ + { + "id": "entrypoint", + "description": "Documented solve.py executes and logs progress", + "source": "review_suite.py" + }, + { + "id": "csv", + "description": "Full inlier row identity, half-up rounding, retained Titanic fields, finite fill and is_alone", + "source": "validate_enhancement.py" + }, + { + "id": "tables", + "description": "Visible keyed IQR, top-three Pearson, room means and sex/class survival", + "source": "review_report.py" + }, + { + "id": "geometry", + "description": "Actual painted scatter, numeric axis calibration, OLS and labelled bars", + "source": "report_contract.py" + }, + { + "id": "metamorphic", + "description": "Fresh outputs on shifted medv and changed survival outcome; original inputs restored", + "source": "review_suite.py" + } + ] +} diff --git a/task_026/tests/report_contract.py b/task_026/tests/report_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..390080ef0e1f8b2d72a2cd7504a03cf6ccfbf826 --- /dev/null +++ b/task_026/tests/report_contract.py @@ -0,0 +1,174 @@ +"""Visible report semantics and shape-independent affine scatter checks.""" +import json +import math +import os +import re +from collections import Counter +from pathlib import Path +from PIL import Image + +DIRECTORY = Path(os.environ.get('REPORT_AUDIT_DIR', '/logs/verifier/report-review')) + + +def load_report(): + return json.loads((DIRECTORY / 'rendered.json').read_text()) + + +def numeric(value): + value = str(value).strip().replace('\u00a0', '').replace('\u202f', '').replace(',', '') + percent = value.endswith('%') + value = re.sub(r'^[¥¥$]\s*', '', value).removesuffix('%').strip() + number = float(value) + assert math.isfinite(number), f'nonfinite report value {value}' + return number / 100 if percent else number + + +def matching_rows(report, aliases): + for table in report['tables']: + for index, row in enumerate(table): + columns = [] + for choices in aliases: + columns.append(next((i for i, text in enumerate(row) + if any(re.search(pattern, text.lower()) for pattern in choices)), None)) + if None not in columns and len(set(columns)) == len(columns): + yield [[row[i] for i in columns] for row in table[index+1:] if len(row)>max(columns)] + break + + +def assert_rows(report, aliases, expected, key_count=1, tolerance=.0051, allow_extra=False): + """Require correctly associated visible rows; table IDs and column order are free.""" + for rows in matching_rows(report, aliases): + if len(rows) < len(expected) or (not allow_extra and len(rows) != len(expected)): + continue + try: + parsed = {} + for row in rows: + key=tuple(format(float(cell), '.12g') if re.fullmatch(r'[+-]?\d+(?:\.\d+)?',cell.strip()) else cell.strip().lower() for cell in row[:key_count]) + assert key not in parsed + parsed[key]=[numeric(cell) for cell in row[key_count:]] + wanted={tuple(str(k).lower() for k in row[:key_count]):row[key_count:] for row in expected} + keys_match=set(wanted)<=set(parsed) if allow_extra else set(parsed)==set(wanted) + if keys_match and all(len(parsed[k])==len(values) and all(abs(a-b)<=tolerance for a,b in zip(parsed[k],values)) for k,values in wanted.items()): + return + except (ValueError,AssertionError): + continue + raise AssertionError(f'Missing or misassociated visible report rows: {aliases}; expected={expected}') + + +def ink(image, x, y, radius=4): + """A reported geometry location must have actual non-background pixels.""" + w,h=image.size + x,y=int(round(x)),int(round(y)) + if not (0<=x4 for c in colors) + + +def affine_scatter(report, expected, trend=None): + """Accept SVG and Canvas, arbitrary translation/scale, point shapes and ordering.""" + a=min(expected,key=lambda p:p[0]); b=max(expected,key=lambda p:p[0]) + assert a[0]!=b[0] and a[1]!=b[1], 'fixture requires separated affine anchors' + for plot in report['plots']: + labels={t['text'].strip().lower() for t in plot['texts']} + if not {'rm','medv'} <= labels: continue + image=Image.open(DIRECTORY/plot['image']).convert('RGB') + points=[p for p in plot['points'] if ink(image,*p, radius=12)] + if len(points)2000: continue + for p in points: + for q in points: + sx=(q[0]-p[0])/(b[0]-a[0]); sy=(q[1]-p[1])/(b[1]-a[1]) + if sx<=0 or sy>=0 or q[0]-p[0]<50 or abs(sy)*(max(y for _,y in expected)-min(y for _,y in expected))<50: continue + ox=p[0]-sx*a[0]; oy=p[1]-sy*a[1] + targets=[(ox+sx*x,oy+sy*y) for x,y in expected] + choices=[[i for i,(u,v) in enumerate(points) if math.hypot(x-u,y-v)<=3] for x,y in targets] + if any(not options for options in choices): continue + assigned={} + def match(target,seen): + for i in choices[target]: + if i in seen: continue + seen.add(i) + if i not in assigned or match(assigned[i],seen): + assigned[i]=target;return True + return False + if not all(match(i,set()) for i in range(len(targets))): continue + # Extra in-plot observations (including the filtered outlier) are not data. + if any(i not in assigned for i in range(len(points))): continue + if not calibrated_axes(plot, sx, sy, ox, oy, expected): continue + if trend: + slope,intercept=trend + def line_ok(line): + x,y,u,v=line + if abs(u-x)<.7*(q[0]-p[0]): return False + target_y=lambda xx: oy+sy*(slope*((xx-ox)/sx)+intercept) + painted=all(ink(image,x+(u-x)*fraction,y+(v-y)*fraction,2) for fraction in (.05,.15,.25,.35,.45,.55,.65,.75,.85,.95)) + return abs(y-target_y(x))<=3 and abs(v-target_y(u))<=3 and painted + if not any(line_ok(line) for line in plot['lines']): continue + return + raise AssertionError('Rendered scatter/trend geometry does not match independently recomputed data') + + +def calibrated_axes(plot, sx, sy, ox, oy, expected): + """Bind the inferred data map to visible numeric ticks, not arbitrary geometry.""" + left=ox+sx*min(x for x,_ in expected) + bottom=oy+sy*min(y for _,y in expected) + ticks={'x':[], 'y':[]} + for text in plot['texts']: + try: + value=numeric(text['text']) + except (ValueError, AssertionError): + continue + if text['y']>bottom and abs(text['x']-(ox+sx*value))<=4: + ticks['x'].append(value) + if text['x']=2 for values in ticks.values()) + + +def survival_bars(report,rates): + for plot in report['plots']: + texts=plot['texts']; bars=plot['bars'] + if not bars: continue + maximum=max(b['height'] for b in bars) + if maximum<30: continue + image=Image.open(DIRECTORY/plot['image']).convert('RGB') + left=min(b['x']-b['width']/2 for b in bars) + categories={str(value).lower() for key in rates for value in key} + label_positions=[text['x'] for text in texts if categories & set(re.findall(r'\w+',text['text'].lower()))] + if label_positions: left=min(left,min(label_positions)) + ticks={} + for text in texts: + if text['x']>=left: continue + try: + value=numeric(text['text']) + except (ValueError, AssertionError): + continue + if value in (0,1): ticks[value]=text['y'] + if set(ticks)!={0,1} or ticks[0]-ticks[1]<30: continue + scale=ticks[0]-ticks[1] + success=True + for (sex,category),rate in rates.items(): + labels=[t for t in texts if t['y']>ticks[0] and sex.lower() in re.findall(r'\w+',t['text'].lower()) and category.lower() in re.findall(r'\w+',t['text'].lower())] + if not labels: + sex_labels=[t for t in texts if sex.lower() in re.findall(r'\w+',t['text'].lower()) and t['y']>ticks[0]] + class_labels=[t for t in texts if category.lower() in re.findall(r'\w+',t['text'].lower()) and t['y']>ticks[0]] + labels=[a for a in sex_labels if any(abs(a['x']-b['x'])<=6 and abs(a['y']-b['y'])<=40 for b in class_labels)] + if not labels: success=False;break + label=labels[0] + nearby=[b for b in bars if abs(b['x']-label['x'])2 for b in nearby): success=False;break + elif not any(abs(b['height']-rate*scale)<=3 and abs(b['y']+b['height']-ticks[0])<=4 and visible_bar(image,b) for b in nearby): + success=False;break + if success: return + raise AssertionError('Visible sex/class labels and bar heights do not match survival rates') + + +def visible_bar(image, bar): + """Check painted height at multiple levels, allowing filled and outlined bars.""" + return all(any(ink(image,bar['x']+offset,bar['y']+bar['height']*fraction,1) + for offset in (-bar['width']/2+1,0,bar['width']/2-1)) + for fraction in (.1,.25,.5,.75,.9)) diff --git a/task_026/tests/review_report.js b/task_026/tests/review_report.js new file mode 100644 index 0000000000000000000000000000000000000000..6a06797b0cab9d149d9ebbde1543f3505c102aab --- /dev/null +++ b/task_026/tests/review_report.js @@ -0,0 +1,137 @@ +// Inspect rendered tables and chart geometry without private DOM identifiers. +const fs = require('fs'); +const path = require('path'); +const {pathToFileURL} = require('url'); +const {chromium} = require('playwright'); + +async function main() { + const output = process.env.REPORT_AUDIT_DIR || '/logs/verifier/report-review'; + fs.mkdirSync(output, {recursive: true}); + const browser = await chromium.launch({headless: true}); + try { + const page = await browser.newPage({viewport: {width: 1200, height: 900}, deviceScaleFactor: 1}); + await page.route(/^https?:/, route => route.abort()); + const errors = []; + page.on('pageerror', error => errors.push(error.message)); + await page.addInitScript(() => { + const logs = new WeakMap(); + window.__chartAudit = logs; + const proto = CanvasRenderingContext2D.prototype; + const entry = context => { + if (!logs.has(context.canvas)) logs.set(context.canvas, {points: [], bars: [], lines: [], texts: [], path: [], pendingPoints: [], pendingBars: []}); + return logs.get(context.canvas); + }; + const xy = (context, x, y) => { const p = new DOMPoint(x, y).matrixTransform(context.getTransform()); return [p.x, p.y]; }; + const painted = (context, kind) => context.globalAlpha>0 && !['transparent','rgba(0, 0, 0, 0)'].includes(String(context[kind+'Style'])); + for (const name of ['beginPath', 'moveTo', 'lineTo', 'arc', 'ellipse', 'rect', 'fillRect', 'fill', 'stroke', 'fillText', 'clearRect']) { + const original = proto[name]; + proto[name] = function(...args) { + const log = entry(this); + if (name === 'beginPath') {log.path = []; log.pendingPoints=[]; log.pendingBars=[];} + if (name === 'moveTo' || name === 'lineTo') log.path.push({move: name === 'moveTo', point: xy(this, args[0], args[1])}); + if (name === 'arc' || name === 'ellipse') log.pendingPoints.push(xy(this, args[0], args[1])); + if (name === 'rect' || name === 'fillRect') { + const a = xy(this, args[0], args[1]), b = xy(this, args[0] + args[2], args[1] + args[3]); + const width = Math.abs(b[0]-a[0]), height = Math.abs(b[1]-a[1]); + const points=name==='rect' ? log.pendingPoints : log.points; + const bars=name==='rect' ? log.pendingBars : log.bars; + if (name==='rect' || painted(this,'fill')) { + if (width <= 20 && height <= 20) points.push([(a[0]+b[0])/2, (a[1]+b[1])/2]); + if (width >= 3 && width <= 100) bars.push({x: (a[0]+b[0])/2, y: Math.min(a[1],b[1]), width, height}); + } + } + if (name==='fill' && painted(this,'fill') && log.path.length>=4 && !log.pendingBars.length) { + const points=log.path.map(item=>item.point), xs=points.map(p=>p[0]), ys=points.map(p=>p[1]); + const left=Math.min(...xs), right=Math.max(...xs), top=Math.min(...ys), bottom=Math.max(...ys); + const corners=new Set(points.map(([x,y])=>`${x},${y}`)); + const rectangular=corners.size===4 && [[left,top],[right,top],[right,bottom],[left,bottom]].every(([x,y])=>corners.has(`${x},${y}`)); + if (rectangular && right-left>=3 && right-left<=100) log.pendingBars.push({x:(left+right)/2,y:top,width:right-left,height:bottom-top}); + } + if (['fill','stroke'].includes(name) && painted(this,name)) { + log.points.push(...log.pendingPoints); log.bars.push(...log.pendingBars); + log.pendingPoints=[]; log.pendingBars=[]; + } + if (name === 'stroke' && painted(this,'stroke')) for (let i=1; i=this.canvas.width && Math.max(a[1],b[1])>=this.canvas.height) {log.points=[];log.bars=[];log.lines=[];log.texts=[];} + } + return original.apply(this,args); + }; + } + }); + await page.goto(pathToFileURL(path.resolve('report.html')).href, {waitUntil: 'load'}); + await page.evaluate(() => document.fonts.ready); + await page.waitForTimeout(400); + if (errors.length) throw new Error(errors.join('\n')); + const data = await page.evaluate(() => { + function visible(element) { + for (let p=element; p && p.nodeType===1; p=p.parentElement) { + const s=getComputedStyle(p); + if (s.display==='none' || s.visibility==='hidden' || Number(s.opacity)===0) return false; + } + const r=element.getBoundingClientRect(); return r.width>0 && r.height>0; + } + const tables = [...document.querySelectorAll('table')].filter(visible).map(table => [...table.rows].filter(visible).map(row => [...row.cells].map(cell => visible(cell) ? cell.innerText.trim() : ''))); + const plots = [...document.querySelectorAll('svg,canvas')].map((chart,index) => { + if (!visible(chart)) return null; + const rect=chart.getBoundingClientRect(); + const result={index, width:rect.width, height:rect.height, points:[], bars:[], lines:[], texts:[]}; + if (chart.tagName.toLowerCase()==='canvas') { + const log=window.__chartAudit.get(chart) || {}; + const sx=rect.width/chart.width, sy=rect.height/chart.height; + result.points=(log.points||[]).map(([x,y])=>[x*sx,y*sy]); + result.lines=(log.lines||[]).map(([x,y,u,v])=>[x*sx,y*sy,u*sx,v*sy]); + result.bars=(log.bars||[]).map(b=>({...b,x:b.x*sx,y:b.y*sy,width:b.width*sx,height:b.height*sy})); + result.texts=(log.texts||[]).map(t=>({...t,x:t.x*sx,y:t.y*sy})); + } else { + for (const el of chart.querySelectorAll('circle,ellipse,rect,path,use,line,polyline,polygon,text')) { + if (!visible(el) || el.closest('defs')) continue; + const box=el.getBoundingClientRect(), tag=el.tagName.toLowerCase(), style=getComputedStyle(el); + const x=box.x-rect.x+box.width/2, y=box.y-rect.y+box.height/2; + if (tag==='text') { result.texts.push({text:el.textContent.trim(),x,y}); continue; } + const filled=style.fill!=='none' && style.fill!=='transparent' && Number(style.fillOpacity)>0; + const stroked=style.stroke!=='none' && style.stroke!=='transparent' && Number(style.strokeOpacity)>0 && parseFloat(style.strokeWidth)>0; + if ((filled || stroked) && box.width>0 && box.height>0 && box.width<=20 && box.height<=20) result.points.push([x,y]); + if ((filled || stroked) && ['rect','path','polygon'].includes(tag) && box.width>=3 && box.width<=100) { + let rectangular=tag==='rect'; + if (!rectangular && typeof el.getTotalLength==='function') { + const length=el.getTotalLength(), matrix=el.getScreenCTM(); + rectangular=!!matrix && Array.from({length:33},(_,i)=>el.getPointAtLength(length*i/32).matrixTransform(matrix)).every(p=>Math.min(Math.abs(p.x-box.left),Math.abs(p.x-box.right),Math.abs(p.y-box.top),Math.abs(p.y-box.bottom))<=1); + } + if (rectangular) result.bars.push({x,y:box.y-rect.y,width:box.width,height:box.height}); + } + if (['line','path','polyline'].includes(tag) && style.stroke!=='none' && Number(style.strokeOpacity)>0 && typeof el.getTotalLength==='function') { + const length=el.getTotalLength(), matrix=el.getScreenCTM(); + if (length>20 && matrix) { + const coords=[]; + for(let i=0;i<=10;i++) {const q=el.getPointAtLength(length*i/10).matrixTransform(matrix);coords.push([q.x-rect.x,q.y-rect.y]);} + for(let i=1;iMath.abs((u-x)*(b-y)-(v-y)*(a-x))/distance<1)) result.lines.push([x,y,u,v]); + } + } + } + } + return result; + }).filter(Boolean); + return {tables, plots, text:document.body.innerText}; + }); + for (const plot of data.plots) { + plot.image=`plot-${plot.index}.png`; + await page.locator('svg,canvas').nth(plot.index).screenshot({path:path.join(output,plot.image)}); + } + await page.screenshot({path:path.join(output,'report.png'),fullPage:true}); + fs.writeFileSync(path.join(output,'rendered.json'),JSON.stringify(data,null,2)); + fs.copyFileSync('report.html',path.join(output,'report.html')); + } finally { await browser.close(); } +} +main().catch(error=>{console.error(error);process.exitCode=1;}); diff --git a/task_026/tests/review_report.py b/task_026/tests/review_report.py new file mode 100644 index 0000000000000000000000000000000000000000..d959d68e375fef7b30c18e136fa0cec5053ab24b --- /dev/null +++ b/task_026/tests/review_report.py @@ -0,0 +1,55 @@ +"""Validate actual rendered analysis, not the mere occurrence of correct numbers.""" +import csv +import math +import statistics +from collections import defaultdict +from pathlib import Path +from report_contract import load_report, assert_rows, affine_scatter, survival_bars + + +def csv_rows(name): + with Path(name).open(encoding='utf-8-sig', newline='') as source: + return list(csv.DictReader(source)) + + +def pearson(xs, ys): + mx,my=statistics.mean(xs),statistics.mean(ys) + numerator=sum((x-mx)*(y-my) for x,y in zip(xs,ys)) + denominator=math.sqrt(sum((x-mx)**2 for x in xs)*sum((y-my)**2 for y in ys)) + return numerator/denominator if denominator else 0 + + +def task42(report): + lines=[line.split() for line in Path('BostonHousing.txt').read_text(encoding='utf-8-sig').splitlines() if line.strip()] + source=[dict(zip(lines[0],map(float,row))) for row in lines[1:]] + prices=sorted(row['medv'] for row in source) + def quantile(q): + p=(len(prices)-1)*q; lo,hi=math.floor(p),math.ceil(p) + return prices[lo]+(prices[hi]-prices[lo])*(p-lo) + q1,q3=quantile(.25),quantile(.75) + low,high=q1-1.5*(q3-q1),q3+1.5*(q3-q1) + clean=[row for row in source if low<=row['medv']<=high] + assert_rows(report,[[r'^metric$',r'指标'],[r'^value$',r'数值']], + [('Q1',q1),('Q3',q3),('lower',low),('upper',high),('outliers',len(source)-len(clean))],allow_extra=True) + correlations={key:pearson([r[key] for r in source],[r['medv'] for r in source]) for key in source[0] if key!='medv'} + top=sorted(correlations,key=lambda key:(-abs(correlations[key]),key))[:3] + assert_rows(report,[[r'feature',r'特征'],[r'pearson',r'^r$',r'相关系数']],[(key,correlations[key]) for key in top]) + rooms=defaultdict(list) + for row in clean: rooms[math.floor(row['rm']+.5)].append(row['medv']) + assert_rows(report,[[r'rm_rounded',r'房间组'],[r'mean',r'均值',r'平均']],[(str(k),statistics.mean(v)) for k,v in rooms.items()]) + groups=defaultdict(list) + for row in csv_rows('titanic_clean.csv'): groups[(row['sex'],row['class'])].append(float(row['survived'])) + rates={key:statistics.mean(values) for key,values in groups.items()} + assert_rows(report,[[r'^sex$',r'性别'],[r'^class$',r'舱位'],[r'rate',r'生存率']], + [(sex,category,value) for (sex,category),value in rates.items()],key_count=2) + xs=[r['rm'] for r in clean]; ys=[r['medv'] for r in clean] + mx,my=statistics.mean(xs),statistics.mean(ys) + slope=sum((x-mx)*(y-my) for x,y in zip(xs,ys))/sum((x-mx)**2 for x in xs) + affine_scatter(report,list(zip(xs,ys)),trend=(slope,my-slope*mx)) + survival_bars(report,rates) + + +if __name__ == '__main__': + report=load_report() + task42(report) + print('Visible keyed report tables and independently reconstructed chart geometry: PASS') diff --git a/task_026/tests/review_suite.py b/task_026/tests/review_suite.py new file mode 100644 index 0000000000000000000000000000000000000000..c91c6ce1049f96a78d1d606b0ce1a76ff4f7a0e3 --- /dev/null +++ b/task_026/tests/review_suite.py @@ -0,0 +1,51 @@ +"""Run the documented entry point against original and value-perturbed inputs.""" +import csv +import io +import os +import subprocess +import sys +from pathlib import Path + +TESTS = Path(__file__).resolve().parent +INPUTS = ('BostonHousing.txt', 'titanic.csv') +originals = {name: Path(name).read_bytes() for name in INPUTS} + + +def perturb(): + lines = [line.split() for line in originals[INPUTS[0]].decode('utf-8-sig').splitlines() if line.strip()] + column = lines[0].index('medv') + for row in lines[1:]: + row[column] = str(float(row[column]) + 7) + Path(INPUTS[0]).write_text('\n'.join(' '.join(row) for row in lines) + '\n') + rows = list(csv.DictReader(io.StringIO(originals[INPUTS[1]].decode('utf-8-sig')))) + selected = next(row for row in rows if row['age'].strip() and row['deck'].strip()) + selected['survived'] = str(1-int(selected['survived'])) + with Path(INPUTS[1]).open('w', newline='') as output: + writer = csv.DictWriter(output, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +try: + for case in ('original', 'perturbed'): + if case == 'perturbed': + perturb() + before = {name: Path(name).read_bytes() for name in INPUTS} + for name in ('boston_clean.csv', 'titanic_clean.csv', 'report.html'): + Path(name).unlink(missing_ok=True) + with Path('/logs/verifier/candidate.log').open('w') as log: + subprocess.run([sys.executable, 'solve.py'], check=True, timeout=60, stdout=log, stderr=subprocess.STDOUT) + assert before == {name: Path(name).read_bytes() for name in INPUTS}, 'candidate modified input' + environment = dict(os.environ, REPORT_AUDIT_DIR=f'/logs/verifier/report-{case}') + commands = [ + [sys.executable, str(TESTS/'validate_outputs.py')], + [sys.executable, str(TESTS/'validate_enhancement.py'), 'ENHANCED_CASE_1', 'ENHANCED_CASE_2', 'ENHANCED_CASE_3'], + ['node', str(TESTS/'review_report.js')], + [sys.executable, str(TESTS/'review_report.py')], + ] + for command in commands: + subprocess.run(command, env=environment, check=True, timeout=60) + print(f'{case}: PASS', flush=True) +finally: + for name, data in originals.items(): + Path(name).write_bytes(data) diff --git a/task_026/tests/test.sh b/task_026/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..05fcf38882f2b9148bd8142dfbf7aacbe778fa52 --- /dev/null +++ b/task_026/tests/test.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +mkdir -p /logs/verifier +echo 0 > /logs/verifier/reward.txt +export NODE_PATH="${NODE_PATH:-$(npm root -g)}" +if python3 "$TEST_DIR/review_suite.py"; then + echo 1 > /logs/verifier/reward.txt +fi diff --git a/task_026/tests/validate_aaav_dynamic.js b/task_026/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..2e4ed81bd174b5d56635940dd8a93a659a94c79e --- /dev/null +++ b/task_026/tests/validate_aaav_dynamic.js @@ -0,0 +1,127 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 42; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems > 0 || stats.text > 0, 'svg task should render non-empty visible content'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible > 0 && (stats.text > 0 || stats.controls > 0), 'page should render non-empty visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_026/tests/validate_enhancement.py b/task_026/tests/validate_enhancement.py new file mode 100644 index 0000000000000000000000000000000000000000..9902d5fc31f93ed55bee354162b0d0612fe0cbf9 --- /dev/null +++ b/task_026/tests/validate_enhancement.py @@ -0,0 +1,167 @@ +import csv +import math +import pathlib +import re +import sys + + +ROOT = pathlib.Path.cwd() + + +def read_csv(path): + with path.open(encoding="utf-8-sig", newline="") as handle: + return list(csv.DictReader(handle)) + + +def read_boston_fixture(path): + lines = [line.split() for line in path.read_text(encoding="utf-8-sig").splitlines() if line.strip()] + assert len(lines) > 1, "Boston fixture is empty" + header = lines[0] + rows = [dict(zip(header, values)) for values in lines[1:] if len(values) == len(header)] + assert rows, "Boston fixture contains no parseable records" + return header, rows + + +def boston_core_rows(path, fixture_header): + """Read conventional CSV or a lossless CSV export of the whitespace source.""" + rows = read_csv(path) + assert rows, "boston_clean.csv is empty" + lookup = {key.lower(): key for key in rows[0]} + if all(name.lower() in lookup for name in fixture_header): + return [ + {name: row[lookup[name.lower()]] for name in fixture_header} + for row in rows + ] + + combined_key = next( + (key for key in rows[0] if key.split() == fixture_header), + None, + ) + assert combined_key is not None, "Boston export does not preserve the fixture columns" + parsed = [] + for row in rows: + values = str(row.get(combined_key, "")).split() + assert len(values) == len(fixture_header), "Boston export contains a malformed fixture record" + parsed.append(dict(zip(fixture_header, values))) + return parsed + + +def quantile(values, fraction): + ordered = sorted(values) + position = (len(ordered) - 1) * fraction + lower, upper = math.floor(position), math.ceil(position) + if lower == upper: + return ordered[lower] + return ordered[lower] * (upper - position) + ordered[upper] * (position - lower) + + +def keyed_titanic(rows): + result = {} + for row in rows: + key = float(row["fare"]) + assert key not in result, "fixture fare values must be unique" + result[key] = row + return result + + +def titanic_rows(): + source = keyed_titanic(read_csv(ROOT / "titanic.csv")) + output = keyed_titanic(read_csv(ROOT / "titanic_clean.csv")) + assert output and set(output) <= set(source), "Titanic output must contain only fixture records" + for key, before in source.items(): + if key not in output: + assert not before.get('age', '').strip() or not before.get('deck', '').strip(), 'only missing age/deck rows may be deleted' + for key, after in output.items(): + before = source[key] + for field in ('sex', 'class', 'embarked'): + assert after[field] == before[field], f'original category changed: {field}' + for field in ('survived', 'pclass', 'sibsp', 'parch'): + assert float(after[field]) == float(before[field]), f'original field changed: {field}' + return source, output + + +def boolean_value(value): + token = re.sub(r"[^a-z0-9]+", "", str(value).lower()) + if token in {"true", "1", "yes", "y"}: + return True + if token in {"false", "0", "no", "n"}: + return False + raise AssertionError(f"is_alone is not boolean-like: {value!r}") + + +# ENHANCED_CASE_1 +def case_boston_iqr_retention(): + """IQR filtering removes the deliberately extreme row and retains every inlier.""" + header, source = read_boston_fixture(ROOT / "BostonHousing.txt") + medv = [float(row["medv"]) for row in source] + q1, q3 = quantile(medv, 0.25), quantile(medv, 0.75) + spread = q3 - q1 + low, high = q1 - 1.5 * spread, q3 + 1.5 * spread + expected = [row for row in source if low <= float(row["medv"]) <= high] + assert 0 < len(expected) < len(source), "fixture must contain both inliers and outliers" + output = boston_core_rows(ROOT / "boston_clean.csv", header) + expected_rows = sorted(tuple(float(row[name]) for name in header) for row in expected) + actual_rows = sorted(tuple(float(row[name]) for name in header) for row in output) + assert actual_rows == expected_rows, "boston_clean.csv does not retain the fixture's IQR-valid records" + + + + + + +# ENHANCED_CASE_2 +def case_titanic_missing_value_fill(): + """Titanic age/deck values are non-empty and supplied fixture values remain unchanged.""" + source, output = titanic_rows() + assert any(not row.get("deck", "").strip() for row in source.values()), "fixture must exercise deck filling" + observed_ages = [float(row["age"]) for row in source.values() if row.get("age", "").strip()] + for key, after in output.items(): + before = source[key] + assert after.get("age", "").strip(), f"age remains empty for fare={key}" + assert after.get("deck", "").strip(), f"deck remains empty for fare={key}" + age = float(after["age"]) + assert math.isfinite(age), f"age is not finite for fare={key}" + if before.get("age", "").strip(): + assert age == float(before["age"]), f"observed age changed for fare={key}" + else: + assert min(observed_ages) <= age <= max(observed_ages), f"age fill is outside the fixture range for fare={key}" + if before.get("deck", "").strip(): + assert after["deck"].strip() == before["deck"].strip(), f"observed deck changed for fare={key}" + + +# ENHANCED_CASE_3 +def case_titanic_is_alone_truth_table(): + """Titanic is_alone exactly follows sibsp + parch == 0, including both outcomes.""" + source, output = titanic_rows() + assert "is_alone" in next(iter(output.values())), "titanic_clean.csv lacks is_alone" + outcomes = set() + for key in output: + before = source[key] + expected = float(before.get("sibsp") or 0) + float(before.get("parch") or 0) == 0 + outcomes.add(expected) + assert boolean_value(output[key].get("is_alone")) is expected, f"is_alone mismatch for fare={key}" + assert outcomes, "cleaning must retain at least one record" + + +CASES = [ + ("ENHANCED_CASE_1", case_boston_iqr_retention), + ("ENHANCED_CASE_2", case_titanic_missing_value_fill), + ("ENHANCED_CASE_3", case_titanic_is_alone_truth_table), +] + + +failures = [] +requested = set(sys.argv[1:]) +known = {case_id for case_id, _ in CASES} +assert requested <= known, f"unknown case id(s): {sorted(requested - known)}" +for case_id, validator in CASES: + if requested and case_id not in requested: + continue + try: + validator() + print(f"{case_id}: PASS") + except Exception as exc: + failures.append((case_id, exc)) + print(f"{case_id}: FAIL: {exc}", file=sys.stderr) +if failures: + raise SystemExit(1) diff --git a/task_026/tests/validate_outputs.py b/task_026/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..a89c5ff73fbdd287d3624218ceb284ec92c8e573 --- /dev/null +++ b/task_026/tests/validate_outputs.py @@ -0,0 +1,13 @@ +"""Validate output presence and per-record half-up rounding without rerunning helpers.""" +import csv +import math +from pathlib import Path + +for name in ('boston_clean.csv', 'titanic_clean.csv', 'report.html'): + assert Path(name).is_file() and Path(name).stat().st_size, f'missing {name}' +with Path('boston_clean.csv').open(encoding='utf-8-sig', newline='') as source: + rows = list(csv.DictReader(source)) +assert rows, 'empty Boston output' +for row in rows: + assert float(row['rm_rounded']) == math.floor(float(row['rm']) + .5), 'incorrect half-up room rounding' +assert Path('/logs/verifier/candidate.log').read_text().strip(), 'missing processing progress log' diff --git a/task_027/acceptance_checklist.json b/task_027/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..565ad47df484df8bc7184284b62d540a8fc30813 --- /dev/null +++ b/task_027/acceptance_checklist.json @@ -0,0 +1,27 @@ +{ + "task_id": 43, + "category": "data_analysis", + "language": "python", + "acceptance_items": [ + "Output files and readable CSV", + "Independent cut statistics, exact integer counts, ranked records and bins", + "Changed price, exact 1000/5000 boundaries and empty-bin fixtures", + "Rendered distribution/mean/median/bin/top-ten associations", + "Actual painted point geometry calibrated to visible linear ticks" + ], + "input_assets": [ + "diamonds.csv" + ], + "expected_outputs": [ + "cut_price_stats.csv", + "price_bin_stats.csv", + "report.html", + "top_10_diamonds.csv" + ], + "risk_notes": [ + "Finite deterministic cases and recorded visual review are not a proof of model discrimination.", + "Report protocol specifies visible linear-axis SVG/Canvas and keyed tables; no private IDs or exact styling." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-10-08" +} diff --git a/task_027/environment/Dockerfile b/task_027/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b5c3125aadc8adae6187cdea0ad0c6d3cf3e505e --- /dev/null +++ b/task_027/environment/Dockerfile @@ -0,0 +1,7 @@ +FROM mcr.microsoft.com/playwright:v1.52.0-noble +USER root +RUN apt-get update && apt-get install -y --no-install-recommends python3-numpy python3-pil && ln -sf /usr/bin/python3 /usr/local/bin/python && rm -rf /var/lib/apt/lists/* +RUN npm install --global --prefix /usr playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules +WORKDIR /app +COPY ./code /app diff --git a/task_027/environment/code/diamonds.csv b/task_027/environment/code/diamonds.csv new file mode 100644 index 0000000000000000000000000000000000000000..197582ca4fb57c508fa0a4578df7aac8d1b87568 --- /dev/null +++ b/task_027/environment/code/diamonds.csv @@ -0,0 +1,16 @@ +carat,cut,color,clarity,depth,table,price,x,y,z +0.23,Ideal,E,SI2,61.5,55,326,3.95,3.98,2.43 +0.21,Premium,E,SI1,59.8,61,326,3.89,3.84,2.31 +0.31,Good,J,SI2,63.3,58,335,4.34,4.35,2.75 +1.01,Very Good,G,VS2,62.1,57,5600,6.43,6.39,3.98 +1.52,Ideal,D,VVS1,61.8,56,15100,7.41,7.38,4.57 +0.42,Ideal,F,VS2,61.2,56,1025,4.78,4.81,2.93 +0.55,Premium,G,SI1,60.5,58,1990,5.21,5.19,3.15 +0.68,Good,H,VS1,62.7,59,2420,5.55,5.52,3.47 +0.72,Very Good,F,VS2,61.3,57,3100,5.70,5.68,3.49 +0.91,Ideal,E,VS1,60.9,57,4850,6.15,6.18,3.75 +1.07,Premium,D,SI2,62.0,58,7350,6.50,6.54,4.04 +1.21,Good,J,SI1,63.1,59,6800,6.75,6.71,4.25 +1.36,Very Good,H,VVS1,61.5,56,9800,7.12,7.08,4.37 +1.68,Ideal,D,VS1,62.2,55,17800,7.63,7.61,4.74 +2.02,Premium,E,VVS1,61.4,58,20500,8.07,8.10,4.96 diff --git a/task_027/environment/docker-compose.yaml b/task_027/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_027/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_027/instruction.md b/task_027/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bb030455ddaefdbf8f80f608523dae8b909d710a --- /dev/null +++ b/task_027/instruction.md @@ -0,0 +1,22 @@ +# Diamond prices and market segments + +Analyze `diamonds.csv` offline. Provide a runnable Python entry script in the project root (for example `main.py` or `solve.py`). Regenerate all outputs beside the input on each run. If there is more than one root Python file and no unique `main.py` or `solve.py`, write the entry script’s filename on one line in `entrypoint.txt`. You can also use that file to select a different entry explicitly. + +## Statistics and outputs + +- Count each category in `cut`, `color`, and `clarity`. +- Write `cut_price_stats.csv` with one row per cut and its mean and median price. Counts are optional; if included, use exact counts. +- Write `top_10_diamonds.csv` with the ten highest-priced rows in descending order, keeping each diamond's `price`, `carat`, and `z` together. +- Write `price_bin_stats.csv` with all three counts, including zero-count bins: `0-1000` for price < 1000, `1000-5000` for 1000 ≤ price < 5000, and `5000+` for price ≥ 5000. + +## Report + +Create an offline `report.html` with visible tables for all three category distributions, cut statistics, the ordered top ten and all price bins. Use headers with the corresponding English or Chinese meanings: cut/切工, color/颜色, clarity/净度, count/数量/频数, mean/平均价格, median/中位价格, price_bin/价格分档, price/价格, carat/克拉 and z/深度. Keep row associations correct. Thousands separators, currency symbols, column order, equivalent decimals and styling are flexible. Preserve at least two decimal places of precision where rounding price statistics; counts are exact. + +Plot carat (x) versus price (y) in a visible SVG or Canvas scatter chart. Use all rows when there are at most 1000; larger inputs may be sampled to 1000. Use paired values from individual rows and linear scales. Label the axes “carat” or “克拉” and “price” or “价格”, with at least two distinct numeric ticks per axis. Render labels and ticks visibly using SVG `` or Canvas `fillText` or `strokeText`. Put x ticks below the plot, and y ticks to the left or right. Ticks use actual data units and may use decimals, thousands separators or scientific notation. Use visible 2–40 px marks spanning at least 50 px on each axis; do not add illustrative points to the data region. + +## Acceptance Checklist + +- CSV and visible table values agree with the source data: category counts, cut means/medians, all bin counts and descending top-ten rows with the correct price/carat/z associations. +- Rendered marks match the source's carat/price pairs under the labeled numeric scales. The plot is legible and visible offline. +- Rerunning the analysis after input values change recomputes the CSV data, displayed values and plotted points. diff --git a/task_027/quality_notes.md b/task_027/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..cf2ed3f39ecce1a25bbbd3545c5f93892fd7bd11 --- /dev/null +++ b/task_027/quality_notes.md @@ -0,0 +1,8 @@ +# Quality Notes + +- The instruction is a consolidated contract, not a literal multi-turn transcript. +- Input assets are separated from candidate outputs; do not score candidates merely for recreating input files. +- The current verifier checks rendered table associations and painted scatter positions calibrated by visible axis ticks, not circle tag counts or number occurrence. +- Optional cut-count columns are permitted; provided counts must be exact integers. CSV and HTML means/medians accept rounding to two decimal places or higher precision. +- SVG circle/ellipse/rect/path/use markers and ordinary Canvas 2D markers are supported; UI geometry and numeric formatting alternatives require runtime positive controls. +- These controls support contract correctness on tested cases, not a claim about a predetermined model ranking. diff --git a/task_027/solution/README.md b/task_027/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_027/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_027/solution/code/solve.py b/task_027/solution/code/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..a35b3217c3a8fb3a884f62d803b5df22cf4e2ce6 --- /dev/null +++ b/task_027/solution/code/solve.py @@ -0,0 +1,89 @@ +import csv, statistics +from collections import Counter +from html import escape + +rows = list(csv.DictReader(open('diamonds.csv', encoding='utf-8-sig'))) +by_cut = {} +for r in rows: + by_cut.setdefault(r.get('cut', 'Unknown'), []).append(float(r.get('price') or 0)) +with open('cut_price_stats.csv', 'w', newline='', encoding='utf-8') as f: + writer = csv.DictWriter(f, fieldnames=['cut', 'mean_price', 'median_price', 'count']) + writer.writeheader() + for cut, prices in by_cut.items(): + writer.writerow({'cut': cut, 'mean_price': round(statistics.mean(prices), 2), + 'median_price': round(statistics.median(prices), 2), 'count': len(prices)}) + +def price_bin(price): + if price < 1000: + return '0-1000' + if price < 5000: + return '1000-5000' + return '5000+' + +by_bin = {} +for r in rows: + by_bin.setdefault(price_bin(float(r.get('price') or 0)), []).append(float(r.get('price') or 0)) +with open('price_bin_stats.csv', 'w', newline='', encoding='utf-8') as f: + writer = csv.DictWriter(f, fieldnames=['price_bin', 'mean_price', 'count']) + writer.writeheader() + for name in ('0-1000','1000-5000','5000+'): + prices=by_bin.get(name,[]) + writer.writerow({'price_bin': name, 'mean_price': round(statistics.mean(prices), 2) if prices else 0, 'count': len(prices)}) + +top = sorted(rows, key=lambda r: float(r.get('price') or 0), reverse=True)[:10] +fields = list(rows[0].keys()) +with open('top_10_diamonds.csv', 'w', newline='', encoding='utf-8') as f: + writer = csv.DictWriter(f, fieldnames=fields) + writer.writeheader() + writer.writerows(top) + +# Average carat and price grouped by clarity grade. +by_clarity = {} +for r in rows: + grade = r.get('clarity', 'Unknown') + entry = by_clarity.setdefault(grade, {'carat': [], 'price': []}) + entry['carat'].append(float(r.get('carat') or 0)) + entry['price'].append(float(r.get('price') or 0)) +with open('clarity_stats.csv', 'w', newline='', encoding='utf-8') as f: + writer = csv.DictWriter(f, fieldnames=['clarity', 'mean_carat', 'mean_price', 'count']) + writer.writeheader() + for grade, vals in by_clarity.items(): + writer.writerow({ + 'clarity': grade, + 'mean_carat': round(statistics.mean(vals['carat']), 3) if vals['carat'] else 0, + 'mean_price': round(statistics.mean(vals['price']), 2) if vals['price'] else 0, + 'count': len(vals['carat']), + }) + +parts = ['Diamonds report', + '', + '

      Diamond analysis

      Fixture-derived distributions, price summaries and carat-price relationship.

      '] +for field in ('cut', 'color', 'clarity'): + parts.append(f'

      {field} distribution

      ') + for category, count in sorted(Counter(row[field] for row in rows).items()): + parts.append(f'') + parts.append('
      {field}count
      {escape(category)}{count}
      ') +parts.append('

      Cut mean and median price

      ') +for cut, prices in sorted(by_cut.items()): + parts.append(f'') +parts.append('
      cutmeanmedian
      {escape(cut)}{statistics.mean(prices):.2f}{statistics.median(prices):.2f}

      Top 10 diamonds

      ') +for row in top: + parts.append(f'') +parts.append('
      pricecaratz
      {row["price"]}{row["carat"]}{row["z"]}

      Price bins

      ') +for category in ('0-1000', '1000-5000', '5000+'): + parts.append(f'') +parts.append('
      price_bincount
      {category}{len(by_bin.get(category, []))}

      Carat versus price

      ') +max_carat = max(float(row['carat']) for row in rows) +max_price = max(float(row['price']) for row in rows) +parts.append('') +for fraction in (0,.5,1): + x=70+630*fraction + y=350-300*fraction + parts.append(f'{max_carat*fraction:.3f}') + parts.append(f'{max_price*fraction:.2f}') +parts.append('caratprice') +for row in rows: + carat, price = float(row['carat']), float(row['price']) + parts.append(f'') +parts.append('') +open('report.html', 'w', encoding='utf-8').write(''.join(parts)) diff --git a/task_027/solution/solve.sh b/task_027/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_027/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_027/task.toml b/task_027/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_027/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_027/task_meta.json b/task_027/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..cf5531f5cf343a670d32812d7c27b01be5af08d6 --- /dev/null +++ b/task_027/task_meta.json @@ -0,0 +1,27 @@ +{ + "task_id": 43, + "task_category": "data_analysis", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 2, + "language": "python", + "tool_files_from_selected_trace": [ + "cut_price_stats.csv", + "diamonds.csv", + "diamonds_analysis.py", + "price_bin_stats.csv", + "top_10_diamonds.csv" + ], + "input_assets": [ + "diamonds.csv" + ], + "expected_outputs": [ + "cut_price_stats.csv", + "price_bin_stats.csv", + "report.html", + "top_10_diamonds.csv" + ], + "source_row_id": 258, + "repair_revision": "2026-10-08", + "instruction_sha256": "8a3d01f14f200d3b9e63828d5d4196d3bf9b3765bea9c92ce655b3d3ff57449b" +} diff --git a/task_027/tests/_shared/contract_checker.js b/task_027/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_027/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_027/tests/_shared/static_enhancer.sh b/task_027/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_027/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_027/tests/analysis_entry.py b/task_027/tests/analysis_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..7a92f05bc4e7cc631c7b71ec36fc28fc5529ce25 --- /dev/null +++ b/task_027/tests/analysis_entry.py @@ -0,0 +1,36 @@ +"""Locate the declared Python analysis and run it with bounded time.""" + +import os +import subprocess +import sys +from pathlib import Path + + +def entry_script(root): + declaration = root / "entrypoint.txt" + if declaration.is_file(): + name = declaration.read_text(encoding="utf-8").strip() + assert name and not any(character in name for character in "\r\n"), "entrypoint.txt needs one filename" + entry = root / name + assert entry.parent == root and entry.suffix == ".py", "declare a root Python script" + assert entry.is_file(), f"declared script {name!r} does not exist" + else: + scripts = list(root.glob("*.py")) + conventional = [path for path in scripts if path.name in {"solve.py", "main.py"}] + options = conventional or scripts + assert len(options) == 1, "provide one unambiguous entry or declare it in entrypoint.txt" + entry = options[0] + assert entry.resolve().parent == root.resolve(), "entry script must be inside the project root" + return entry + + +def run_analysis(root): + entry = entry_script(root) + env = {name: value for name, value in os.environ.items() + if name.lower() not in {"http_proxy", "https_proxy", "all_proxy"}} + env["PYTHONHASHSEED"] = "1" + subprocess.run([sys.executable, entry.name], cwd=root, env=env, timeout=60, check=True) + + +if __name__ == "__main__": + run_analysis(Path.cwd()) diff --git a/task_027/tests/enhancement_cases.json b/task_027/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..c23c21f98b5346d3b9a32e9bd7afc7dcc2763065 --- /dev/null +++ b/task_027/tests/enhancement_cases.json @@ -0,0 +1,38 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "计算每种 cut 类型的平均价格和中位价格。", + "validator": "tests/validate_enhanced.py#enhanced_case_1", + "behavior": "Recomputes every cut's count, average and median price from diamonds.csv and accepts any output row order." + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "找出价格最高的 10 颗钻石,并查看它们的 carat 和 z(深度)。", + "validator": "tests/validate_enhanced.py#enhanced_case_2", + "behavior": "Checks the full fixture-derived top-N price/carat/z multiset and descending price order, including duplicate-safe tie handling." + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "计算每种 cut 类型的平均价格和中位价格。\n随包基准输入:diamonds.csv", + "validator": "tests/validate_enhanced.py#enhanced_case_3", + "behavior": "Reruns the candidate against an isolated diamonds.csv with one price changed by 1337, then recomputes the cut average and verifies the actual rendered report tables and calibrated scatter coordinates against the changed input." + }, + { + "case_id": "ENHANCED_CASE_4", + "instruction_evidence": "价格分档、类别分布、前十和散点图均须展示在 report.html。", + "validator": "tests/validate_enhanced.py#enhanced_case_4", + "behavior": "Checks fixture-derived price-bin counts and report content." + }, + { + "case_id": "ENHANCED_CASE_5", + "instruction_evidence": "低于 1000 为 0-1000,1000 至不足 5000 为 1000-5000。", + "validator": "tests/validate_enhanced.py#enhanced_case_5", + "behavior": "Injects prices exactly 1000 and 5000 and reruns the candidate to verify both left-closed boundaries." + }, + { + "case_id": "ENHANCED_CASE_6", + "instruction_evidence": "三个价格分档均须写出,空档计 0。", + "validator": "tests/validate_enhanced.py#enhanced_case_5(all_high=True)", + "behavior": "Moves all fixture prices above 5000 and requires the two empty bins to remain present with exact zero counts." + } +] diff --git a/task_027/tests/report_contract.py b/task_027/tests/report_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..6d7baaa4464d072dd57b5cde1c689ca700a1218e --- /dev/null +++ b/task_027/tests/report_contract.py @@ -0,0 +1,108 @@ +"""Rendered table associations and tick-calibrated, genuinely painted scatter plots.""" +import json +import math +import os +import re +from collections import Counter +from pathlib import Path +from PIL import Image +from report_values import number + +DIRECTORY=Path(os.environ.get('REPORT_REVIEW_DIR','/logs/verifier/report-review')) + +def load_report(): + return json.loads((DIRECTORY/'rendered.json').read_text()) + +def numeric(value): + return float(number(str(value))) + +def matching_rows(report,aliases): + for table in report['tables']: + for index,row in enumerate(table): + columns=[next((i for i,text in enumerate(row) if any(re.search(pattern,text.lower()) for pattern in choices)),None) for choices in aliases] + if None not in columns and len(set(columns))==len(columns): + yield [[row[i] for i in columns] for row in table[index+1:] if len(row)>max(columns)] + break + +def assert_rows(report,aliases,expected,key_count=1,tolerance=.0051): + wanted={tuple(str(key).strip().lower() for key in row[:key_count]):row[key_count:] for row in expected} + for rows in matching_rows(report,aliases): + try: + parsed={} + for row in rows: + key=tuple(cell.strip().lower() for cell in row[:key_count]) + if key not in wanted and key[0] in ('total','合计','总计'): continue + assert key not in parsed, 'duplicate category' + parsed[key]=[numeric(cell) for cell in row[key_count:]] + if set(parsed)==set(wanted) and all(len(parsed[key])==len(values) and all(abs(actual-expected)<=tolerance for actual,expected in zip(parsed[key],values)) for key,values in wanted.items()): return + except (ValueError,AssertionError): + continue + raise AssertionError(f'Visible table values are missing or misassociated: {aliases}') + +def ink(image,x,y,radius=4): + """Inspect actual pixels against the plot's dominant background, including hollow markers.""" + width,height=image.size + x,y=int(round(x)),int(round(y)); radius=int(math.ceil(min(radius,24))) + if not 0<=x4 + for u in range(max(0,x-radius),min(width,x+radius+1)) + for v in range(max(0,y-radius),min(height,y+radius+1))) + +def tick_fits(texts,axis): + """Infer scale only from visible numeric axis ticks, not from submitted point positions.""" + numeric_texts=[] + for text in texts: + try:numeric_texts.append((text,numeric(text['text']))) + except (ValueError,AssertionError):pass + fits=[] + for a,av in numeric_texts: + for b,bv in numeric_texts: + if bv<=av:continue + aligned=abs(a['y']-b['y'])<8 if axis=='x' else any(abs(a.get(anchor,a['x'])-b.get(anchor,b['x']))<8 for anchor in ('left','right','x')) + if not aligned:continue + for anchor in (('x','left','right') if axis=='x' else ('y',)): + ap=a.get(anchor,a['x']); bp=b.get(anchor,b['x']) + scale=(bp-ap)/(bv-av) + if (axis=='x' and scale<=0) or (axis=='y' and scale>=0) or abs(bp-ap)<50:continue + fits.append((scale,ap-scale*av,min(ap,bp),max(ap,bp),a,b)) + return fits + +def affine_scatter(report,expected): + expected=list(dict.fromkeys(expected)) # coincident opaque points have identical visible geometry + for plot in report['plots']: + texts=plot['texts'] + if not any(re.search(r'carat|克拉',t['text'],re.I) for t in texts):continue + if not any(re.search(r'price|价格',t['text'],re.I) for t in texts):continue + image=Image.open(DIRECTORY/plot['image']).convert('RGB') + # Deduplicate fill+stroke logs without erasing distinct data coordinates. + points=[] + for point in plot['points']: + if ink(image,*point) and not any(math.dist(point[:2],other[:2])<.1 for other in points):points.append(point) + if not len(expected)<=len(points)<=2000:continue + for sx,ox,xlo,xhi,xa,xb in tick_fits(texts,'x'): + for sy,oy,ylo,yhi,ya,yb in tick_fits(texts,'y'): + targets=[(ox+sx*x,oy+sy*y) for x,y in expected] + if max(x for x,y in targets)-min(x for x,y in targets)<50 or max(y for x,y in targets)-min(y for x,y in targets)<50:continue + # X ticks are below the data and y ticks to its left or right. + if min(xa['y'],xb['y'])min(x for x,y in targets)+8 and max(ya['x'],yb['x']) route.abort()); + const errors = []; + page.on('pageerror', error => errors.push(error.message)); + await page.addInitScript(() => { + const logs = new WeakMap(); + window.__chartAudit = logs; + const proto = CanvasRenderingContext2D.prototype; + const entry = context => { + if (!logs.has(context.canvas)) logs.set(context.canvas, {points: [], bars: [], lines: [], texts: [], path: [], pendingPoints: [], pendingBars: []}); + return logs.get(context.canvas); + }; + const xy = (context, x, y) => { const p = new DOMPoint(x, y).matrixTransform(context.getTransform()); return [p.x, p.y]; }; + const painted = (context, kind) => { + const style = context[kind + 'Style']; + const transparent = typeof style === 'string' && + (style === 'transparent' || /^rgba\(.*,\s*0(?:\.0+)?\)$/.test(style) || /\/\s*0(?:\.0+)?\)$/.test(style)); + return context.globalAlpha > 0 && !transparent; + }; + const textPaint = new Map([['fillText', 'fill'], ['strokeText', 'stroke']]); + function captureText(context, [value, rawX, rawY, maxWidth]) { + const x = Number(rawX), y = Number(rawY); + if (!Number.isFinite(x) || !Number.isFinite(y)) return null; + const text = String(value); + const metrics = context.measureText(text); + const limit = maxWidth === undefined ? metrics.width : Number(maxWidth); + if (!Number.isFinite(limit) || limit <= 0) return null; + const width = Math.min(metrics.width, limit); + const direction = context.direction === 'inherit' + ? getComputedStyle(context.canvas).direction + : context.direction; + const align = context.textAlign; + const rightAligned = align === 'right' || (align === 'start' && direction === 'rtl') || (align === 'end' && direction !== 'rtl'); + const left = x - (align === 'center' ? width / 2 : rightAligned ? width : 0); + const middleY = y + (metrics.actualBoundingBoxDescent - metrics.actualBoundingBoxAscent) / 2; + const center = xy(context, left + width / 2, middleY); + const bounds = [xy(context, left, middleY)[0], xy(context, left + width, middleY)[0]]; + return {text, x: center[0], y: center[1], left: Math.min(...bounds), right: Math.max(...bounds)}; + } + for (const name of ['beginPath', 'moveTo', 'lineTo', 'arc', 'ellipse', 'rect', 'fillRect', 'fill', 'stroke', ...textPaint.keys(), 'clearRect']) { + const original = proto[name]; + proto[name] = function(...args) { + const log = entry(this); + if (name === 'beginPath') {log.path = []; log.pendingPoints=[]; log.pendingBars=[];} + if (name === 'moveTo' || name === 'lineTo') log.path.push({move: name === 'moveTo', point: xy(this, args[0], args[1])}); + if (name === 'arc' || name === 'ellipse') { + const center=xy(this,args[0],args[1]), edge=xy(this,args[0]+args[2],args[1]); + log.pendingPoints.push([...center,Math.hypot(edge[0]-center[0],edge[1]-center[1])+2]); + } + if (name === 'rect' || name === 'fillRect') { + const a = xy(this, args[0], args[1]), b = xy(this, args[0] + args[2], args[1] + args[3]); + const width = Math.abs(b[0]-a[0]), height = Math.abs(b[1]-a[1]); + const points=name==='rect' ? log.pendingPoints : log.points; + const bars=name==='rect' ? log.pendingBars : log.bars; + if (name==='rect' || painted(this,'fill')) { + if (width <= 40 && height <= 40) points.push([(a[0]+b[0])/2, (a[1]+b[1])/2,Math.max(width,height)/2+2]); + if (width >= 3 && width <= 100) bars.push({x: (a[0]+b[0])/2, y: Math.min(a[1],b[1]), width, height}); + } + } + if (['fill','stroke'].includes(name) && painted(this,name)) {log.points.push(...log.pendingPoints);log.bars.push(...log.pendingBars);} + if (name === 'stroke' && painted(this,'stroke')) for (let i=1; i=this.canvas.width && Math.max(a[1],b[1])>=this.canvas.height) {log.points=[];log.bars=[];log.lines=[];log.texts=[];} + } + return original.apply(this,args); + }; + } + }); + await page.goto(pathToFileURL(path.resolve('report.html')).href, {waitUntil: 'load'}); + await page.evaluate(() => document.fonts.ready); + await page.waitForTimeout(400); + if (errors.length) throw new Error(errors.join('\n')); + const data = await page.evaluate(() => { + function visible(element) { + for (let p=element; p && p.nodeType===1; p=p.parentElement) { + const s=getComputedStyle(p); + if (s.display==='none' || s.visibility==='hidden' || Number(s.opacity)===0) return false; + } + const r=element.getBoundingClientRect(); return r.width>0 && r.height>0; + } + const tables = [...document.querySelectorAll('table')].filter(visible).map(table => [...table.rows].filter(visible).map(row => [...row.cells].map(cell => visible(cell) ? cell.innerText.trim() : ''))); + const plots = [...document.querySelectorAll('svg,canvas')].map((chart,index) => { + if (!visible(chart)) return null; + const rect=chart.getBoundingClientRect(); + const result={index, width:rect.width, height:rect.height, points:[], bars:[], lines:[], texts:[]}; + if (chart.tagName.toLowerCase()==='canvas') { + const log=window.__chartAudit.get(chart) || {}; + const sx=rect.width/chart.width, sy=rect.height/chart.height; + result.points=(log.points||[]).map(([x,y,r])=>[x*sx,y*sy,(r||4)*Math.max(sx,sy)]); + result.lines=(log.lines||[]).map(([x,y,u,v])=>[x*sx,y*sy,u*sx,v*sy]); + result.bars=(log.bars||[]).map(b=>({...b,x:b.x*sx,y:b.y*sy,width:b.width*sx,height:b.height*sy})); + result.texts=(log.texts||[]).map(t=>({...t,x:t.x*sx,y:t.y*sy,left:t.left*sx,right:t.right*sx})); + } else { + for (const el of chart.querySelectorAll('circle,ellipse,rect,path,use,line,polyline,polygon,text')) { + if (!visible(el) || el.closest('defs')) continue; + const box=el.getBoundingClientRect(), tag=el.tagName.toLowerCase(), style=getComputedStyle(el); + const x=box.x-rect.x+box.width/2, y=box.y-rect.y+box.height/2; + if (tag==='text') { result.texts.push({text:el.textContent.trim(),x,y,left:box.left-rect.left,right:box.right-rect.left}); continue; } + const filled=style.fill!=='none' && style.fill!=='transparent' && Number(style.fillOpacity)>0; + const stroked=style.stroke!=='none' && style.stroke!=='transparent' && Number(style.strokeOpacity)>0 && parseFloat(style.strokeWidth)>0; + if ((filled || stroked) && box.width>0 && box.height>0 && box.width<=40 && box.height<=40) result.points.push([x,y,Math.max(box.width,box.height)/2+2]); + if (tag==='rect' && filled && box.width>=3 && box.width<=100) result.bars.push({x,y:box.y-rect.y,width:box.width,height:box.height}); + if (['line','path','polyline'].includes(tag) && style.stroke!=='none' && Number(style.strokeOpacity)>0 && typeof el.getTotalLength==='function') { + const length=el.getTotalLength(), matrix=el.getScreenCTM(); + if (length>20 && matrix) { + const coords=[]; + for(let i=0;i<=10;i++) {const q=el.getPointAtLength(length*i/10).matrixTransform(matrix);coords.push([q.x-rect.x,q.y-rect.y]);} + for(let i=1;iMath.abs((u-x)*(b-y)-(v-y)*(a-x))/distance<1)) result.lines.push([x,y,u,v]); + } + } + } + } + return result; + }).filter(Boolean); + return {tables, plots, text:document.body.innerText}; + }); + for (const plot of data.plots) { + plot.image=`plot-${plot.index}.png`; + await page.locator('svg,canvas').nth(plot.index).screenshot({path:path.join(output,plot.image)}); + } + await page.screenshot({path:path.join(output,'report.png'),fullPage:true}); + fs.writeFileSync(path.join(output,'rendered.json'),JSON.stringify(data,null,2)); + fs.copyFileSync('report.html',path.join(output,'report.html')); + } finally { await browser.close(); } +} +main().catch(error=>{console.error(error);process.exitCode=1;}); diff --git a/task_027/tests/review_report.py b/task_027/tests/review_report.py new file mode 100644 index 0000000000000000000000000000000000000000..66e63247b73ec10836c90d4c1dd3e56aaaf4174b --- /dev/null +++ b/task_027/tests/review_report.py @@ -0,0 +1,26 @@ +"""Check rendered, semantically keyed Task 43 tables and scatter coordinates.""" +import csv +import statistics +from collections import Counter, defaultdict +from report_contract import load_report, assert_rows, affine_scatter +from report_values import assert_top_tables + +with open('diamonds.csv',encoding='utf-8-sig',newline='') as source: + rows=list(csv.DictReader(source)) +report=load_report() +for field,translation in [('cut','切工'),('color','颜色'),('clarity','净度')]: + counts=Counter(row[field] for row in rows) + assert_rows(report,[[rf'^{field}$',translation],[r'^count$',r'数量',r'频数']],list(counts.items()),tolerance=0) +groups=defaultdict(list) +for row in rows: groups[row['cut']].append(float(row['price'])) +assert_rows(report,[[r'^cut$',r'切工'],[r'mean',r'avg',r'average',r'平均'],[r'median',r'中位']], + [(cut,statistics.mean(prices),statistics.median(prices)) for cut,prices in groups.items()]) +for table in report['tables']: + headers=' '.join(table[0]).lower() if table else '' + if ('mean' in headers or '平均' in headers or 'avg' in headers) and ('count' in headers or '数量' in headers or '频数' in headers): + assert_rows({'tables':[table]},[[r'^cut$',r'切工'],[r'^count$',r'数量',r'频数']],[(cut,len(prices)) for cut,prices in groups.items()],tolerance=0) +bins=Counter('0-1000' if float(row['price'])<1000 else '1000-5000' if float(row['price'])<5000 else '5000+' for row in rows) +assert_rows(report,[[r'bin',r'分档'],[r'^count$',r'数量',r'频数']],[(label,bins[label]) for label in ('0-1000','1000-5000','5000+')],tolerance=0) +assert_top_tables(report['tables'], sorted(rows,key=lambda row:float(row['price']),reverse=True)[:10]) +affine_scatter(report,[(float(row['carat']),float(row['price'])) for row in rows]) +print('Visible distributions, grouped prices, price bins, top-ten association and scatter geometry: PASS') diff --git a/task_027/tests/test.sh b/task_027/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..6da54fb319c782f9b5e8c495983501c3e64a077c --- /dev/null +++ b/task_027/tests/test.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +export NODE_PATH="${NODE_PATH:-$(npm root -g 2>/dev/null)}" +export PYTHONHASHSEED=1 +unset HTTP_PROXY HTTPS_PROXY ALL_PROXY http_proxy https_proxy all_proxy +echo 0 > "$LOG_DIR/reward.txt" + +rm -f -- cut_price_stats.csv price_bin_stats.csv report.html top_10_diamonds.csv +if python3 "$TEST_DIR/analysis_entry.py" && + python3 "$TEST_DIR/validate_outputs.py" && + timeout 150s python3 "$TEST_DIR/validate_enhanced.py" && + timeout 90s node "$TEST_DIR/validate_aaav_dynamic.js" && + timeout 90s node "$TEST_DIR/review_report.js" && + python3 "$TEST_DIR/review_report.py"; then + echo 1 > "$LOG_DIR/reward.txt" +fi diff --git a/task_027/tests/validate_aaav_dynamic.js b/task_027/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..174565a8acf52136140ff8bd63143807ba8428bf --- /dev/null +++ b/task_027/tests/validate_aaav_dynamic.js @@ -0,0 +1,127 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 43; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems > 0 || stats.text > 0, 'svg task should render non-empty visible content'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible > 0 && (stats.text > 0 || stats.controls > 0), 'page should render non-empty visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_027/tests/validate_enhanced.py b/task_027/tests/validate_enhanced.py new file mode 100644 index 0000000000000000000000000000000000000000..c13891ba7c2f88fc294d312aff52a4e3c3b030e6 --- /dev/null +++ b/task_027/tests/validate_enhanced.py @@ -0,0 +1,227 @@ +"""Instruction-derived deterministic checks for Task 43.""" + +import csv +import html +import math +import os +import pathlib +import re +import shutil +import statistics +import subprocess +import tempfile +from collections import Counter +from analysis_entry import run_analysis +from report_values import assert_top_rows + + +ROOT = pathlib.Path.cwd() + + +def read_csv(name): + with (ROOT / name).open(encoding="utf-8-sig", newline="") as handle: + return list(csv.DictReader(handle)) + + +def field(row, *terms): + for name in row: + normalized = name.strip().lower().replace('_', ' ') + if any(re.search(r'(?= 0, 'count must be a nonnegative integer' + return int(number) + + +fixture = read_csv("diamonds.csv") +assert fixture, "diamonds fixture is empty" + + +# ENHANCED_CASE_1: grouped cut output must contain fixture-derived counts and +# the requested average and median prices. +def enhanced_case_1(): + cut_rows = read_csv("cut_price_stats.csv") + assert cut_rows, "cut_price_stats.csv is empty" + cut_key = field(cut_rows[0], "cut") + count_key = next((name for name in cut_rows[0] if name.lower() in ('count', '数量', '频数')), None) + mean_key = field(cut_rows[0], "mean", "avg", "average", "平均") + median_key = field(cut_rows[0], "median", "中位") + actual_cuts = {row[cut_key].strip(): row for row in cut_rows} + assert len(actual_cuts) == len(cut_rows), 'duplicate cut rows' + expected_cuts = {} + for cut in {row["cut"] for row in fixture}: + prices = [float(row["price"]) for row in fixture if row["cut"] == cut] + expected_cuts[cut] = (len(prices), statistics.mean(prices)) + assert set(actual_cuts) == set(expected_cuts), ( + f"cut groups differ: actual={set(actual_cuts)}, expected={set(expected_cuts)}" + ) + for cut, (expected_count, expected_mean) in expected_cuts.items(): + row = actual_cuts[cut] + if count_key: + assert count(row[count_key]) == expected_count, f"wrong count for cut {cut}" + assert close(row[mean_key], expected_mean), f"wrong mean price for cut {cut}" + assert close(row[median_key], statistics.median( + float(r["price"]) for r in fixture if r["cut"] == cut + )), f"wrong median price for cut {cut}" + + +def signature(row, pkey, ckey, depth_key): + return tuple(round(float(row[key]), 8) for key in (pkey, ckey, depth_key)) + + +# ENHANCED_CASE_2: validate the complete top-N result using only the fields the +# instruction asks to inspect. Counter comparison remains correct for ties and +# duplicate diamonds and does not require an unspecified identifier column. +def enhanced_case_2(): + top_rows = read_csv("top_10_diamonds.csv") + assert top_rows, "top_10_diamonds.csv is empty" + price_key = field(top_rows[0], "price", "价格") + carat_key = field(top_rows[0], "carat", "克拉") + z_key = field(top_rows[0], "z", "深度") + expected_top = sorted(fixture, key=lambda row: float(row["price"]), reverse=True)[:10] + assert len(top_rows) == len(expected_top), "top-N row count does not match the fixture" + actual_prices = [float(row[price_key]) for row in top_rows] + assert actual_prices == sorted(actual_prices, reverse=True), "top-N rows are not price-descending" + actual_signatures = Counter(signature(row, price_key, carat_key, z_key) for row in top_rows) + expected_signatures = Counter(signature(row, "price", "carat", "z") for row in expected_top) + assert actual_signatures == expected_signatures, "top-N price/carat/z values do not match the fixture" + + +# ENHANCED_CASE_3: a metamorphic fixture check rejects hard-coded cut averages. +# It changes one input price in an isolated copy, reruns the submitted program, +# and checks the affected cut average. No particular dataframe/API is assumed. +def rerun_analysis(work): + for name in ("report.html", "cut_price_stats.csv", "price_bin_stats.csv", "top_10_diamonds.csv"): + (work / name).unlink(missing_ok=True) + run_analysis(work) + + +def enhanced_case_3(): + with tempfile.TemporaryDirectory(prefix="task43_case3_") as tmp_name: + work = pathlib.Path(tmp_name) / "work" + shutil.copytree( + ROOT, + work, + ignore=shutil.ignore_patterns("tests", "logs", "*.pyc", "__pycache__"), + ) + mutated = [] + with (work / "diamonds.csv").open(encoding="utf-8-sig", newline="") as handle: + reader = csv.DictReader(handle) + names = reader.fieldnames + mutated = list(reader) + assert names and mutated, "cannot prepare mutated diamonds fixture" + changed_cut = mutated[0]["cut"] + mutated[0]["price"] = str(float(mutated[0]["price"]) + 1337.0) + with (work / "diamonds.csv").open("w", encoding="utf-8", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=names) + writer.writeheader() + writer.writerows(mutated) + + env = os.environ.copy() + for key in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"): + env.pop(key, None) + env["PYTHONHASHSEED"] = "1" + rerun_analysis(work) + with (work / "cut_price_stats.csv").open(encoding="utf-8-sig", newline="") as handle: + changed_rows = list(csv.DictReader(handle)) + assert changed_rows, "rerun did not emit cut_price_stats.csv" + cut_key = field(changed_rows[0], "cut") + mean_key = field(changed_rows[0], "mean", "avg", "average", "平均") + matches = [row for row in changed_rows if row[cut_key].strip() == changed_cut] + assert len(matches) == 1, f"rerun does not contain exactly one {changed_cut} cut row" + expected = statistics.mean( + float(row["price"]) for row in mutated if row["cut"] == changed_cut + ) + assert close(matches[0][mean_key], expected), ( + f"cut average did not follow the mutated fixture: expected {expected}" + ) + # The HTML chart and tables must follow changed data too, not just the CSV. + env['REPORT_REVIEW_DIR']='/logs/verifier/report-review-mutated' + tests=pathlib.Path(__file__).resolve().parent + subprocess.run(['node',str(tests/'review_report.js')],cwd=work,env=env,timeout=45,check=True) + subprocess.run(['python3',str(tests/'review_report.py')],cwd=work,env=env,timeout=30,check=True) + + +def enhanced_case_4(): + bins = read_csv("price_bin_stats.csv") + assert bins, "price_bin_stats.csv is empty" + bin_key = field(bins[0], "bin", "分档") + count_key = field(bins[0], "count", "数量", "频数") + expected = Counter( + "0-1000" if float(row["price"]) < 1000 else + "1000-5000" if float(row["price"]) < 5000 else "5000+" + for row in fixture + ) + for label in ('0-1000','1000-5000','5000+'): expected.setdefault(label,0) + actual = {row[bin_key].strip(): count(row[count_key]) for row in bins} + assert len(actual) == len(bins), 'duplicate price bin rows' + assert actual == expected, f"price bins mismatch: {actual} != {expected}" + + report = html.unescape((ROOT / "report.html").read_text(encoding="utf-8")).lower() + assert_top_rows(report, sorted(fixture, key=lambda item: float(item["price"]), reverse=True)[:10]) + + +# ENHANCED_CASE_5: an injected price exactly at 1000 belongs to the second, +# left-closed bin. Recompute outputs from the changed fixture, not constants. +def enhanced_case_5(all_high=False): + with tempfile.TemporaryDirectory(prefix="task43_boundary_") as tmp_name: + work = pathlib.Path(tmp_name) / "work" + shutil.copytree(ROOT, work, ignore=shutil.ignore_patterns("tests", "logs", "*.pyc", "__pycache__")) + with (work / "diamonds.csv").open(encoding="utf-8-sig", newline="") as handle: + reader = csv.DictReader(handle) + names, rows = reader.fieldnames, list(reader) + assert names and rows + rows[0]["price"] = "1000" + rows[1]["price"] = "5000" + if all_high: + for index,row in enumerate(rows): row['price']=str(6000+index) + with (work / "diamonds.csv").open("w", encoding="utf-8", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=names) + writer.writeheader() + writer.writerows(rows) + rerun_analysis(work) + with (work / "price_bin_stats.csv").open(encoding="utf-8-sig", newline="") as handle: + bins = list(csv.DictReader(handle)) + assert bins + bin_key, count_key = field(bins[0], "bin", "分档"), field(bins[0], "count", "数量", "频数") + actual = {row[bin_key].strip(): count(row[count_key]) for row in bins} + assert len(actual) == len(bins), 'duplicate price bin rows' + expected = Counter("0-1000" if float(row["price"]) < 1000 else + "1000-5000" if float(row["price"]) < 5000 else "5000+" for row in rows) + for label in ('0-1000','1000-5000','5000+'): expected.setdefault(label,0) + assert actual == expected, f"exact boundaries 1000 and 5000 must enter their left-closed bins: {actual} != {expected}" + + +all_cases = ( + ("ENHANCED_CASE_1", enhanced_case_1), + ("ENHANCED_CASE_2", enhanced_case_2), + ("ENHANCED_CASE_3", enhanced_case_3), + ("ENHANCED_CASE_4", enhanced_case_4), + ("ENHANCED_CASE_5", enhanced_case_5), + ("ENHANCED_CASE_6", lambda: enhanced_case_5(all_high=True)), +) +selected = os.environ.get("ENHANCED_CASE") +assert selected is None or selected in dict(all_cases), f"unknown ENHANCED_CASE: {selected}" +failures = [] +for case_id, validator in all_cases: + if selected and case_id != selected: + continue + try: + validator() + print(f"PASS {case_id}") + except Exception as error: # keep cases independently executable/reportable + failures.append((case_id, error)) + print(f"FAIL {case_id}: {error}") + +assert not failures, f"{len(failures)} enhanced case(s) failed" diff --git a/task_027/tests/validate_outputs.py b/task_027/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..e469a7eccc54e2f146f1a200f108a2123a73c31d --- /dev/null +++ b/task_027/tests/validate_outputs.py @@ -0,0 +1,11 @@ +"""Output presence/CSV readability only; semantic checks live in dedicated modules.""" +import csv +from pathlib import Path + +for name in ('cut_price_stats.csv','price_bin_stats.csv','top_10_diamonds.csv','report.html'): + path=Path(name) + assert path.is_file() and path.stat().st_size>0, f'missing output {name}' + if path.suffix=='.csv': + with path.open(encoding='utf-8-sig',newline='') as source: + assert list(csv.DictReader(source)), f'empty CSV {name}' +print('Output files exist and CSV tables are readable') diff --git a/task_028/acceptance_checklist.json b/task_028/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..9e58f054b2e718b4bde54e701f7251d1adeeb6d3 --- /dev/null +++ b/task_028/acceptance_checklist.json @@ -0,0 +1,22 @@ +{ + "task_id": 44, + "category": "data_analysis", + "language": "python", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Python files compile; data-analysis tasks generate the requested output files from fixture data." + ], + "input_assets": [ + "spotify_songs.csv" + ], + "expected_outputs": [ + "report.html", + "top_5_activity_songs.csv" + ], + "risk_notes": [ + "Input assets are separated from candidate outputs; do not score candidates merely for recreating input files." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_028/environment/Dockerfile b/task_028/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b5c3125aadc8adae6187cdea0ad0c6d3cf3e505e --- /dev/null +++ b/task_028/environment/Dockerfile @@ -0,0 +1,7 @@ +FROM mcr.microsoft.com/playwright:v1.52.0-noble +USER root +RUN apt-get update && apt-get install -y --no-install-recommends python3-numpy python3-pil && ln -sf /usr/bin/python3 /usr/local/bin/python && rm -rf /var/lib/apt/lists/* +RUN npm install --global --prefix /usr playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules +WORKDIR /app +COPY ./code /app diff --git a/task_028/environment/code/spotify_songs.csv b/task_028/environment/code/spotify_songs.csv new file mode 100644 index 0000000000000000000000000000000000000000..25e410c7d0e7b713176d35e727276f7f25aab076 --- /dev/null +++ b/task_028/environment/code/spotify_songs.csv @@ -0,0 +1,7 @@ +track_name,track_artist,track_album_release_date,playlist_genre,energy,danceability,valence,tempo +Morning Run,Alice,2001-03-01,pop,0.82,0.71,0.66,128 +Quiet Study,Bob,1998-09-10,jazz,0.22,0.42,0.30,80 +Workout Peak,Cara,2005-06-15,rock,0.95,0.83,0.74,140 +Late Night,Dee,2010-11-20,pop,0.45,0.64,0.51,100 +Bright Road,Eve,2020-01-05,rock,0.88,0.69,0.72,132 +Slow Rain,Finn,2018-07-17,jazz,0.31,0.55,0.44,92 diff --git a/task_028/environment/docker-compose.yaml b/task_028/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_028/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_028/instruction.md b/task_028/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7bce8fb3c04605ee5796994c2def37fbba971d76 --- /dev/null +++ b/task_028/instruction.md @@ -0,0 +1,27 @@ +# Spotify song trends and charts + +Read the supplied `spotify_songs.csv` using the Python standard library. Run with `python3 solve.py` in the project root, without network access. Write all outputs there and recompute them on each run. + +## CSV outputs + +Parse `release_year` as an integer from the first four characters of `track_album_release_date`; retain only rows from 2000 onward. + +| File | Contract | +| --- | --- | +| `filtered_songs.csv` | Keep original columns and row order; append `release_year` and `activity_score`. Calculate `activity_score = (energy + valence) / 2`, formatted to four decimal places. | +| `top_5_activity_songs.csv` | Up to five retained songs, ordered by unrounded score descending, retaining source order for ties. Include at least `track_name,track_artist,release_year,activity_score`; format scores to four decimals. | +| `annual_counts.csv` | Exact header `release_year,count`; one row per observed retained year, ascending. | +| `genre_danceability.csv` | Exact header `playlist_genre,mean_danceability`; one row per observed retained genre, in lexicographic order, with mean to four decimals. | +| `tempo_bins.csv` | Exact header `bin_start,bin_end,count`; 10 BPM bins, left-closed and right-open. Start at `floor(min(tempo)/10)*10` through the bin containing the maximum. Use integer endpoints, include empty bins, and sort ascending. | + +If no songs survive filtering, write only the headers in the CSVs. + +## Report + +Create a directly openable `report.html` listing the top song titles and artists and the filtered “Tempo mean” and “Tempo median” when data is available. Display those statistics to at least three decimal places. Label the three inline SVG charts with their subject (release year counts, mean danceability by genre and tempo distribution) and `data-chart="annual"`, `"genre"`, and `"tempo"` respectively. Use one `` per aggregate with `data-key` (year, genre or bin start), numeric `data-value` and numeric `width` and `height` attributes. Width is positive and height is proportional to value within the chart (zero for value zero). Show the corresponding numeric label as visible SVG ``. Keep bars and labels in the visible chart; colors and styles are unrestricted. + +## Acceptance Checklist + +- Filtering, tie ordering, score precision, grouped averages/counts and bin boundaries are derived from current data. An empty filtered set still produces valid header-only CSVs. +- The report visibly lists the top songs and accurate tempo statistics. All three charts have correct keyed values, proportional bars and readable value labels. +- A rerun on changed input regenerates the tables and charts without fixed rankings or decorative stand-ins. diff --git a/task_028/quality_notes.md b/task_028/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..8cb3accc74f1939924d31f3fcffbd7fb95445c25 --- /dev/null +++ b/task_028/quality_notes.md @@ -0,0 +1,5 @@ +# Quality notes — Task 44 + +- The v3.2 reference used fixed chart marks and a tempo rectangle per song, rather than yearly counts, genre means or a histogram. +- The revision publishes five data products and a small inline-SVG bar contract. The verifier independently recomputes all tables and checks chart values, order and proportional heights. +- A changed-input rerun catches fixed output artifacts; browser-level visual review remains a separate pending check. diff --git a/task_028/solution/README.md b/task_028/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_028/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_028/solution/code/solve.py b/task_028/solution/code/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..d72be288c0eab1ea12fabb0741f3ed3335fa43db --- /dev/null +++ b/task_028/solution/code/solve.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Compute Spotify summaries and render data-driven inline SVG charts.""" + +import csv +import html +import math +import statistics +from collections import Counter, defaultdict +from pathlib import Path + + +ROOT = Path(__file__).resolve().parent + + +def write_csv(name, fields, rows): + with (ROOT / name).open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields) + writer.writeheader() + writer.writerows(rows) + + +def bar_chart(kind, items, title): + width = max(420, 52 * len(items) + 50) + baseline = 145 + maximum = max((float(value) for _, value in items), default=0) or 1 + bars = [] + for i, (key, value) in enumerate(items): + height = 110 * float(value) / maximum + x = 32 + i * 52 + y = baseline - height + safe_key = html.escape(str(key), quote=True) + bars.append( + f'' + f'{float(value):.4f}' + f'{safe_key}' + ) + return ( + f'
      {html.escape(title)}
      ' + f'' + + ''.join(bars) + '
      ' + ) + + +def main(): + with (ROOT / "spotify_songs.csv").open(newline="", encoding="utf-8-sig") as handle: + reader = csv.DictReader(handle) + original_fields = list(reader.fieldnames or []) + source_rows = list(reader) + filtered = [] + for row in source_rows: + year = int(row["track_album_release_date"][:4]) + if year < 2000: + continue + score = (float(row["energy"]) + float(row["valence"])) / 2 + filtered.append((row, year, score)) + output_rows = [{**row, "release_year": year, "activity_score": f"{score:.4f}"} + for row, year, score in filtered] + write_csv("filtered_songs.csv", original_fields + ["release_year", "activity_score"], output_rows) + top = sorted(enumerate(filtered), key=lambda item: -item[1][2])[:5] + top_rows = [output_rows[index] for index, _ in top] + write_csv("top_5_activity_songs.csv", original_fields + ["release_year", "activity_score"], top_rows) + + years = Counter(year for _, year, _ in filtered) + annual = [{"release_year": year, "count": years[year]} for year in sorted(years)] + write_csv("annual_counts.csv", ["release_year", "count"], annual) + + genre_values = defaultdict(list) + for row, _, _ in filtered: + genre_values[row["playlist_genre"]].append(float(row["danceability"])) + genre = [{"playlist_genre": key, "mean_danceability": f"{statistics.mean(genre_values[key]):.4f}"} + for key in sorted(genre_values)] + write_csv("genre_danceability.csv", ["playlist_genre", "mean_danceability"], genre) + + tempos = [float(row["tempo"]) for row, _, _ in filtered] + bins = [] + if tempos: + first = math.floor(min(tempos) / 10) * 10 + last = math.floor(max(tempos) / 10) * 10 + for start in range(first, last + 1, 10): + bins.append({"bin_start": start, "bin_end": start + 10, + "count": sum(start <= tempo < start + 10 for tempo in tempos)}) + write_csv("tempo_bins.csv", ["bin_start", "bin_end", "count"], bins) + + song_list = ''.join( + f'
    1. {html.escape(row["track_name"])} — {html.escape(row["track_artist"])}
    2. ' + for row in top_rows + ) + tempo_mean = statistics.mean(tempos) if tempos else 0.0 + tempo_median = statistics.median(tempos) if tempos else 0.0 + page = ( + 'Spotify analysis' + '' + '

      Spotify release_year and activity analysis

      ' + '

      Filtered songs released in 2000 or later.

      ' + '

      Top five by activity score

        ' + song_list + '
      ' + + bar_chart("annual", [(row["release_year"], row["count"]) for row in annual], "Annual song counts") + + bar_chart("genre", [(row["playlist_genre"], row["mean_danceability"]) for row in genre], + "Average danceability by playlist_genre") + + bar_chart("tempo", [(row["bin_start"], row["count"]) for row in bins], "Tempo BPM histogram") + + f'

      tempo mean={tempo_mean:.4f}; median={tempo_median:.4f}

      ' + ) + (ROOT / "report.html").write_text(page, encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/task_028/solution/solve.sh b/task_028/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_028/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_028/task.toml b/task_028/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_028/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_028/task_meta.json b/task_028/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..0b252baecb46b8cebe228fb5e8fa4b4f96381ac9 --- /dev/null +++ b/task_028/task_meta.json @@ -0,0 +1,22 @@ +{ + "task_id": 44, + "task_category": "data_analysis", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 1, + "language": "python", + "tool_files_from_selected_trace": [ + "spotify_analysis.py", + "top_5_activity_songs.csv" + ], + "input_assets": [ + "spotify_songs.csv" + ], + "expected_outputs": [ + "report.html", + "top_5_activity_songs.csv" + ], + "source_row_id": 264, + "repair_revision": "2026-09-29", + "instruction_sha256": "4d832ca5ae6cbc8bbadabbc78948b10aeb2b730da996883f2b228a8bdce9fd4c" +} diff --git a/task_028/tests/_shared/contract_checker.js b/task_028/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_028/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_028/tests/_shared/static_enhancer.sh b/task_028/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_028/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_028/tests/enhancement_cases.json b/task_028/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..13260cd10c571f021ae5c07560d73de2e64a5ce2 --- /dev/null +++ b/task_028/tests/enhancement_cases.json @@ -0,0 +1,26 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "接着计算每首歌的“活跃度得分”(energy * 0.5 + valence * 0.5),找出得分最高的 5 首歌曲并展示其名称和艺术家;", + "validator": "tests/validate_enhanced.py#enhanced_case_1", + "behavior": "Recomputes the equal-weight score and checks the complete top-five track/artist ordering; validates a score column when supplied." + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "首先提取 track_album_release_date 的年份作为新列 release_year,并筛选 2000 年及以后的歌曲数据;", + "validator": "tests/validate_enhanced.py#enhanced_case_2", + "behavior": "Raises the pre-2000 fixture song's activity score in an isolated rerun and requires it to remain excluded. validate_contract.py additionally checks year-derived filtered rows and the annual chart." + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "最后绘制 tempo(BPM)的分布直方图,标注均值和中位数。", + "validator": "tests/validate_enhanced.py#enhanced_case_3", + "behavior": "Recomputes and independently checks labeled tempo mean and median; validate_contract.py checks all three data tables and proportional SVG chart bars." + }, + { + "case_id": "CONTRACT_AND_MUTATION", + "instruction_evidence": "filtered_songs、annual_counts、genre_danceability、tempo_bins 与三张数据驱动 SVG。", + "validator": "tests/validate_contract.py", + "behavior": "独立重算数据表及 SVG 图形,修改年份、活跃度、danceability 和 tempo 后重跑。" + } +] diff --git a/task_028/tests/test.sh b/task_028/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c583b6ae8ed38f719e43b3a497aa30e015bb949a --- /dev/null +++ b/task_028/tests/test.sh @@ -0,0 +1,78 @@ +#!/usr/bin/env bash +set -euo pipefail +set +e +TASK_ID='44' +source "$(cd "$(dirname "$0")" && pwd)/_shared/static_enhancer.sh" +LOG_DIR="/logs/verifier" +if ! mkdir -p "$LOG_DIR" 2>/dev/null; then LOG_DIR="logs/verifier"; mkdir -p "$LOG_DIR"; fi +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +if [ ! -f solve.py ]; then + echo "solve.py entrypoint missing" + exit 0 +fi +PASS=1 +CHECKS=0 +FAILS=0 + +note() { echo "[Task $TASK_ID] $*"; } +fail() { note "FAIL: $*"; PASS=0; FAILS=$((FAILS+1)); } +check() { CHECKS=$((CHECKS+1)); "$@"; local code=$?; if [ $code -ne 0 ]; then fail "$*"; fi; } +have_any() { local pattern="$1"; compgen -G "$pattern" >/dev/null 2>&1; } +grep_any() { local pattern="$1"; shift; grep -REiq -- "$pattern" "$@" 2>/dev/null; } +source_files() { find . -type f \( -name '*.html' -o -name '*.js' -o -name '*.jsx' -o -name '*.ts' -o -name '*.tsx' -o -name '*.css' -o -name '*.py' -o -name '*.go' -o -name '*.swift' -o -name '*.svg' \) ! -path './tests/*' ! -path './logs/*'; } + +note "enhanced deterministic verifier start" +static_enhance_check "${TASK_ID}" "$(pwd)" +export NODE_PATH="${NODE_PATH:-$(npm root -g 2>/dev/null)}" +rm -f -- filtered_songs.csv top_5_activity_songs.csv annual_counts.csv genre_danceability.csv tempo_bins.csv report.html +if [ ! -e 'spotify_songs.csv' ]; then + fail "benchmark input asset missing: spotify_songs.csv" +fi +mapfile -t py_files < <(find . -type f -name '*.py' ! -path './tests/*') +if [ ${#py_files[@]} -eq 0 ]; then fail "no Python source found"; fi +if command -v python3 >/dev/null 2>&1; then + for f in "${py_files[@]}"; do python3 -m py_compile "$f" >/tmp/harbor_py_compile.log 2>&1 || fail "python compile failed: $f"; done +fi +if command -v python3 >/dev/null 2>&1 && [ -f solve.py ]; then + env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy \ + PYTHONHASHSEED=1 timeout 60s python3 solve.py >/tmp/harbor_data_run.log 2>&1 \ + || fail "data script did not run successfully" +else + fail "solve.py entrypoint missing" +fi +check test -s 'report.html' +check test -s 'top_5_activity_songs.csv' + +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +if command -v python3 >/dev/null 2>&1; then + check env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy \ + PYTHONHASHSEED=1 timeout 90s python3 "$TEST_DIR/validate_outputs.py" + check env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy \ + PYTHONHASHSEED=1 timeout 150s python3 "$TEST_DIR/validate_enhanced.py" + check env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy \ + PYTHONHASHSEED=1 timeout 150s python3 "$TEST_DIR/validate_contract.py" +else + fail "python3 unavailable for output validation" +fi +# BEGIN AAAV_DYNAMIC_TEST +if [ -f "$TEST_DIR/validate_aaav_dynamic.js" ]; then + if command -v node >/dev/null 2>&1; then + GLOBAL_NODE_PATH="${NODE_PATH:-$(npm root -g 2>/dev/null)}" + check env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy \ + NODE_PATH="$GLOBAL_NODE_PATH" \ + timeout 90s node "$TEST_DIR/validate_aaav_dynamic.js" + else + fail "node is required for browser validation" + fi +fi +# END AAAV_DYNAMIC_TEST +note "checks=$CHECKS fails=$FAILS" +if [ "$PASS" -eq 1 ]; then + echo 1 > "$REWARD_FILE" + note "PASS" + exit 0 +fi +echo 0 > "$REWARD_FILE" +note "FAIL" +exit 0 diff --git a/task_028/tests/validate_aaav_dynamic.js b/task_028/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..fba684c9b51d9f22fe770f308860c0af1eae0236 --- /dev/null +++ b/task_028/tests/validate_aaav_dynamic.js @@ -0,0 +1,82 @@ +const {chromium} = require('playwright'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const {pathToFileURL} = require('node:url'); + +(async () => { + const browser = await chromium.launch({headless: true, args: ['--no-sandbox']}); + try { + const page = await browser.newPage({viewport: {width: 1100, height: 760}}); + await page.route(/^https?:/, route => route.abort()); + await page.goto(pathToFileURL(path.join(process.cwd(), 'report.html')).href); + for (const kind of ['annual', 'genre', 'tempo']) { + const chart = page.locator(`svg[data-chart="${kind}"]`); + assert(await chart.isVisible(), `${kind} chart is hidden`); + const failures = await chart.evaluate(svg => { + const bounds = svg.getBoundingClientRect(); + const failures = []; + const color = document.createElement('canvas').getContext('2d'); + const hasPaint = paint => { + if (paint === 'none') return false; + const gradientRef = /^url\(["']?#([^"')]+)["']?\)$/.exec(paint); + if (gradientRef) { + const gradient = document.getElementById(gradientRef[1]); + if (gradient?.matches('linearGradient, radialGradient')) { + const stops = [...gradient.querySelectorAll('stop')]; + if (stops.length) return stops.some(stop => { + const style = getComputedStyle(stop); + return Number(style.stopOpacity) > 0 && hasPaint(style.stopColor); + }); + } + return true; // Patterns and nested references can paint without a local stop. + } + color.fillStyle = '#000'; + color.fillStyle = paint; + color.clearRect(0, 0, 1, 1); + color.fillRect(0, 0, 1, 1); + return color.getImageData(0, 0, 1, 1).data[3] > 0; + }; + const painted = style => + (Number(style.fillOpacity) > 0 && hasPaint(style.fill)) || + (Number(style.strokeOpacity) > 0 && parseFloat(style.strokeWidth) > 0 && hasPaint(style.stroke)); + for (const bar of svg.querySelectorAll('rect[data-key]')) { + const box = bar.getBoundingClientRect(); + const label = [...svg.querySelectorAll('[data-value-label]')].find(element => element.getAttribute('data-value-label') === bar.dataset.key); + if (!label || !Number.isFinite(Number(label.textContent.trim())) || Math.abs(Number(label.textContent.trim()) - Number(bar.dataset.value)) > 0.0001) { + failures.push(`missing or incorrect numeric label ${bar.dataset.key}`); + } else { + const labelBox = label.getBoundingClientRect(); + const glyphs = [label, ...label.querySelectorAll('text, tspan, textPath')]; + const visibleInk = glyphs.some(node => { + const style = getComputedStyle(node); + return node.getClientRects().length && style.visibility === 'visible' && Number(style.opacity) > 0 && painted(style); + }); + if (labelBox.width <= 0 || labelBox.height <= 0 || !visibleInk) failures.push(`invisible label ${bar.dataset.key}`); + for (let ancestor = label; ancestor; ancestor = ancestor.parentElement) { + const style = getComputedStyle(ancestor); + if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) failures.push(`hidden label ${bar.dataset.key}`); + } + } + if (Number(bar.dataset.value) === 0) continue; + let el = bar; + while (el) { + const style = getComputedStyle(el); + if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) + failures.push(`hidden ${bar.dataset.key}`); + el = el.parentElement; + } + if (box.width <= 0 || box.height <= 0 || !painted(getComputedStyle(bar))) failures.push(`unpainted ${bar.dataset.key}`); + if (box.left < bounds.left - 1 || box.right > bounds.right + 1 || box.top < bounds.top - 1 || box.bottom > bounds.bottom + 1) + failures.push(`clipped ${bar.dataset.key}`); + } + return failures; + }); + assert.deepEqual(failures, [], `${kind} plot must paint visible data bars inside its own viewport`); + } + fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + await page.screenshot({path: `/logs/verifier/visual-audit/${process.env.SPOTIFY_SCREENSHOT || 'spotify-report'}.png`, fullPage: true}); + } finally { + await browser.close(); + } +})().catch(error => {console.error(error); process.exit(1)}); diff --git a/task_028/tests/validate_contract.py b/task_028/tests/validate_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..2310cb4b6317380702ae13be92a8989a3374d780 --- /dev/null +++ b/task_028/tests/validate_contract.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""Independently recompute Spotify tables and inspect each SVG chart.""" + +import csv +import html +import math +import os +import re +import shutil +import statistics +import subprocess +import sys +import tempfile +from collections import Counter, defaultdict +from html.parser import HTMLParser +from pathlib import Path + + +def csv_rows(path): + with path.open(newline="", encoding="utf-8-sig") as handle: + reader = csv.DictReader(handle) + return reader.fieldnames, list(reader) + + +class Charts(HTMLParser): + def __init__(self): + super().__init__() + self.current = None + self.charts = {} + + def handle_starttag(self, tag, attrs): + attrs = dict(attrs) + if tag == "svg" and "data-chart" in attrs: + assert self.current is None + self.current = attrs["data-chart"] + assert self.current not in self.charts, "duplicate chart" + self.charts[self.current] = [] + elif tag == "rect" and self.current is not None: + self.charts[self.current].append(attrs) + + def handle_endtag(self, tag): + if tag == "svg": + self.current = None + + +def check_chart(charts, kind, expected): + assert kind in charts, f"missing {kind} chart" + rects = charts[kind] + assert len(rects) == len(expected), f"{kind} bar count mismatch" + positive = [] + by_key = {str(key): value for key, value in expected} + seen = set() + for rect in rects: + key = rect.get('data-key') + assert key in by_key and key not in seen, f'{kind} key missing or duplicated' + seen.add(key) + value = by_key[key] + actual = float(rect["data-value"]) + assert abs(actual - value) <= 5e-5, f"{kind} value mismatch for {key}" + height = float(rect["height"]) + assert float(rect["width"]) > 0 and height >= 0, f"{kind} invalid bar geometry" + assert math.isfinite(height), f"{kind} bar height is not finite" + if value == 0: + assert height == 0, f"{kind} zero value has nonzero bar" + else: + assert height > 0, f"{kind} nonzero value has invisible bar" + positive.append(height / value) + if positive: + assert max(positive) - min(positive) <= 0.01 * max(positive), ( + f"{kind} bar heights are not proportional to values" + ) + + +def check(root): + fields, source = csv_rows(root / "spotify_songs.csv") + assert fields is not None + filtered = [] + for row in source: + year = int(row["track_album_release_date"][:4]) + if year >= 2000: + score = (float(row["energy"]) + float(row["valence"])) / 2 + filtered.append((row, year, score)) + out_fields, out = csv_rows(root / "filtered_songs.csv") + assert out_fields == fields + ["release_year", "activity_score"] + assert len(out) == len(filtered) + for got, (row, year, score) in zip(out, filtered): + assert all(got[key] == row[key] for key in fields), "filtered row differs from source" + assert int(got["release_year"]) == year + assert re.fullmatch(r"-?\d+\.\d{4}", got["activity_score"]) + assert abs(float(got["activity_score"]) - round(score, 4)) <= 1e-10 + + top_fields, top = csv_rows(root / "top_5_activity_songs.csv") + assert top_fields is not None and len(top) == min(5, len(filtered)) + assert {'track_name', 'track_artist', 'release_year', 'activity_score'} <= set(top_fields) + expected_top = [filtered[i] for i in sorted(range(len(filtered)), key=lambda i: -filtered[i][2])[:5]] + for got, (row, year, score) in zip(top, expected_top): + assert all(got[key] == row[key] for key in ('track_name', 'track_artist')) + assert int(got["release_year"]) == year + assert re.fullmatch(r"-?\d+\.\d{4}", got['activity_score']) + assert abs(float(got["activity_score"]) - round(score, 4)) <= 1e-10 + + years = Counter(year for _, year, _ in filtered) + annual_expected = [(year, years[year]) for year in sorted(years)] + header, annual = csv_rows(root / "annual_counts.csv") + assert header == ["release_year", "count"] + assert [(int(r["release_year"]), int(r["count"])) for r in annual] == annual_expected + + grouped = defaultdict(list) + for row, _, _ in filtered: + grouped[row["playlist_genre"]].append(float(row["danceability"])) + genre_expected = [(name, round(statistics.mean(values), 4)) for name, values in sorted(grouped.items())] + header, genre = csv_rows(root / "genre_danceability.csv") + assert header == ["playlist_genre", "mean_danceability"] + assert [(r["playlist_genre"], float(r["mean_danceability"])) for r in genre] == genre_expected + + tempos = [float(row["tempo"]) for row, _, _ in filtered] + bin_expected = [] + if tempos: + first = math.floor(min(tempos) / 10) * 10 + last = math.floor(max(tempos) / 10) * 10 + bin_expected = [(start, start + 10, sum(start <= value < start + 10 for value in tempos)) + for start in range(first, last + 1, 10)] + header, bins = csv_rows(root / "tempo_bins.csv") + assert header == ["bin_start", "bin_end", "count"] + assert [(int(r["bin_start"]), int(r["bin_end"]), int(r["count"])) for r in bins] == bin_expected + + report = (root / "report.html").read_text(encoding="utf-8") + charts = Charts() + charts.feed(report) + assert set(charts.charts) == {"annual", "genre", "tempo"} + check_chart(charts.charts, "annual", annual_expected) + check_chart(charts.charts, "genre", genre_expected) + check_chart(charts.charts, "tempo", [(start, count) for start, _, count in bin_expected]) + visible = html.unescape(re.sub(r"<[^>]*>", " ", report)) + for row, _, _ in expected_top: + assert row["track_name"] in visible and row["track_artist"] in visible, "top song missing from report" + if tempos: + mean = re.search(r"(?:tempo\s*)?(?:mean|average|均值|平均值?)\s*[:=:]?\s*(-?\d+(?:\.\d+)?)", visible, re.I) + median = re.search(r"(?:median|中位数?)\s*[:=:]?\s*(-?\d+(?:\.\d+)?)", visible, re.I) + assert mean and median, "tempo mean/median not labeled" + assert abs(float(mean.group(1)) - statistics.mean(tempos)) <= 5e-4 + assert abs(float(median.group(1)) - statistics.median(tempos)) <= 5e-4 + + +ARTIFACTS = ("filtered_songs.csv", "top_5_activity_songs.csv", "annual_counts.csv", + "genre_danceability.csv", "tempo_bins.csv", "report.html") + + +def clear_outputs(root): + for name in ARTIFACTS: + (root / name).unlink(missing_ok=True) + + +def validate_rendered_report(root, name): + verifier = Path(__file__).resolve().with_name("validate_aaav_dynamic.js") + env = {**os.environ, "SPOTIFY_SCREENSHOT": name} + subprocess.run(["node", str(verifier)], cwd=root, env=env, check=True, timeout=30) + + +def mutation(root): + with tempfile.TemporaryDirectory(prefix="task44-input-") as tmp: + work = Path(tmp) / "candidate" + shutil.copytree(root, work, ignore=shutil.ignore_patterns("tests", "logs", "__pycache__", "*.pyc")) + fields, rows = csv_rows(work / "spotify_songs.csv") + assert fields and len(rows) >= 2 + target = next(row for row in rows if int(row["track_album_release_date"][:4]) >= 2000) + target["track_album_release_date"] = "2001-01-01" + target["energy"] = "1.0" + target["valence"] = "1.0" + target["danceability"] = "0.1" + target["tempo"] = "180.0" + with (work / "spotify_songs.csv").open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields) + writer.writeheader() + writer.writerows(rows) + clear_outputs(work) + result = subprocess.run([sys.executable, "solve.py"], cwd=work, capture_output=True, + text=True, timeout=45) + assert result.returncode == 0, f"candidate failed changed input: {result.stderr}" + check(work) + validate_rendered_report(work, "spotify-report-mutated") + # The public empty-filter case must produce headers and valid empty charts. + for row in rows: + row['track_album_release_date'] = '1999-01-01' + with (work / 'spotify_songs.csv').open('w', newline='', encoding='utf-8') as handle: + writer = csv.DictWriter(handle, fieldnames=fields) + writer.writeheader() + writer.writerows(rows) + result = subprocess.run([sys.executable, 'solve.py'], cwd=work, capture_output=True, text=True, timeout=45) + assert result.returncode == 0, 'candidate failed the empty filtered dataset' + check(work) + validate_rendered_report(work, "spotify-report-empty") + + +if __name__ == "__main__": + check(Path.cwd()) + mutation(Path.cwd()) + print("Spotify data tables, charts and input mutation passed") diff --git a/task_028/tests/validate_enhanced.py b/task_028/tests/validate_enhanced.py new file mode 100644 index 0000000000000000000000000000000000000000..9cc5fdab7ef1922592239efde58a4a76e40cc306 --- /dev/null +++ b/task_028/tests/validate_enhanced.py @@ -0,0 +1,173 @@ +"""Instruction-derived deterministic checks for Task 44.""" + +import csv +import html +import os +import pathlib +import re +import shutil +import statistics +import subprocess +import tempfile + + +ROOT = pathlib.Path.cwd() + + +def read_csv(name): + with (ROOT / name).open(encoding="utf-8-sig", newline="") as handle: + return list(csv.DictReader(handle)) + + +def matching_field(row, alternatives): + for name in row: + normalized = name.strip().casefold() + if any(term in normalized for term in alternatives): + return name + raise AssertionError(f"missing column matching {alternatives}: {list(row)}") + + +def contains_rounded_value(values, target): + # Normal report rounding from 0 through 4 decimal places is accepted. + return any( + any(abs(value - round(target, places)) <= 10 ** (-(places + 2)) for places in range(5)) + for value in values + ) + + +fixture = read_csv("spotify_songs.csv") +filtered = [row for row in fixture if int(row["track_album_release_date"][:4]) >= 2000] +report_raw = (ROOT / "report.html").read_text(encoding="utf-8", errors="ignore") +report = html.unescape(report_raw).casefold() + + +# ENHANCED_CASE_1: all five songs—not merely the maximum—must be the exact +# descending ranking produced by the specified equal-weight activity formula. +def enhanced_case_1(): + top_rows = read_csv("top_5_activity_songs.csv") + assert top_rows, "top_5_activity_songs.csv is empty" + name_key = matching_field(top_rows[0], ("track_name", "track", "song", "歌曲")) + artist_key = matching_field(top_rows[0], ("artist", "歌手", "艺人")) + expected_top = sorted( + filtered, + key=lambda row: (float(row["energy"]) + float(row["valence"])) / 2, + reverse=True, + )[:5] + assert len(top_rows) == len(expected_top), "top activity row count is not min(5, filtered rows)" + actual_pairs = [(row[name_key].strip(), row[artist_key].strip()) for row in top_rows] + expected_pairs = [(row["track_name"].strip(), row["track_artist"].strip()) for row in expected_top] + assert actual_pairs == expected_pairs, ( + f"activity ranking differs: actual={actual_pairs}, expected={expected_pairs}" + ) + score_fields = [name for name in top_rows[0] if "activ" in name.casefold() or "活跃" in name] + if score_fields: + score_key = score_fields[0] + for actual, source_row in zip(top_rows, expected_top): + expected_score = (float(source_row["energy"]) + float(source_row["valence"])) / 2 + assert contains_rounded_value([float(actual[score_key])], expected_score), ( + f"wrong activity score for {source_row['track_name']}" + ) + + +# ENHANCED_CASE_2: a metamorphic check makes the sole pre-2000 song the highest +# activity row, reruns the candidate, and requires it to remain excluded. This +# validates the requested year extraction/filter. Data-driven charts are +# checked separately by validate_contract.py. +def enhanced_case_2(): + old_rows = [row for row in fixture if int(row["track_album_release_date"][:4]) < 2000] + assert old_rows, "fixture has no pre-2000 row with which to verify the filter" + excluded_pair = (old_rows[0]["track_name"].strip(), old_rows[0]["track_artist"].strip()) + py_files = sorted( + path for path in ROOT.rglob("*.py") + if "tests" not in path.parts and "logs" not in path.parts + ) + assert py_files, "no candidate Python program found" + main_py = py_files[0] + for path in py_files: + if any(token in path.name.casefold() for token in ("analysis", "example", "transform", "main")): + main_py = path + break + + with tempfile.TemporaryDirectory(prefix="task44_case2_") as tmp_name: + work = pathlib.Path(tmp_name) / "work" + shutil.copytree( + ROOT, + work, + ignore=shutil.ignore_patterns("tests", "logs", "*.pyc", "__pycache__"), + ) + with (work / "spotify_songs.csv").open(encoding="utf-8-sig", newline="") as handle: + reader = csv.DictReader(handle) + names = reader.fieldnames + mutated = list(reader) + assert names and mutated, "cannot prepare mutated Spotify fixture" + for row in mutated: + if (row["track_name"].strip(), row["track_artist"].strip()) == excluded_pair: + row["energy"] = "1.0" + row["valence"] = "1.0" + with (work / "spotify_songs.csv").open("w", encoding="utf-8", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=names) + writer.writeheader() + writer.writerows(mutated) + (work / "top_5_activity_songs.csv").unlink(missing_ok=True) + + env = os.environ.copy() + for key in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"): + env.pop(key, None) + env["PYTHONHASHSEED"] = "1" + subprocess.run( + ["python3", str(main_py.relative_to(ROOT))], cwd=work, env=env, + timeout=60, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, + ) + with (work / "top_5_activity_songs.csv").open(encoding="utf-8-sig", newline="") as handle: + changed_top = list(csv.DictReader(handle)) + assert changed_top, "isolated rerun did not emit top_5_activity_songs.csv" + name_key = matching_field(changed_top[0], ("track_name", "track", "song", "歌曲")) + artist_key = matching_field(changed_top[0], ("artist", "歌手", "艺人")) + actual_pairs = {(row[name_key].strip(), row[artist_key].strip()) for row in changed_top} + assert excluded_pair not in actual_pairs, ( + "pre-2000 song leaked into top activity output after its score was increased" + ) + assert re.search(r"release[_ -]?year|发行年|发布年|年份", report), "report does not identify the release_year analysis" + + +# ENHANCED_CASE_3: recompute the requested tempo mean and median from the +# post-2000 fixture. Both summaries must be labeled and accurate under normal +# report rounding; the histogram is checked by validate_contract.py. +def enhanced_case_3(): + tempo_values = [float(row["tempo"]) for row in filtered] + tempo_mean = statistics.mean(tempo_values) + tempo_median = statistics.median(tempo_values) + plain = re.sub(r"<[^>]+>", " ", report) + assert "tempo" in plain, "report omits the tempo analysis" + tempo_context = plain + mean_match = re.search(r"(?:mean|average|均值|平均)\s*[:=]?\s*(-?\d+(?:\.\d+)?)", tempo_context) + median_match = re.search(r"(?:median|中位(?:数)?)\s*[:=]?\s*(-?\d+(?:\.\d+)?)", tempo_context) + assert mean_match, "report does not label a tempo mean" + assert median_match, "report does not label a tempo median" + assert contains_rounded_value([float(mean_match.group(1))], tempo_mean), ( + f"wrong tempo mean: expected {tempo_mean}, got {mean_match.group(1)}" + ) + assert contains_rounded_value([float(median_match.group(1))], tempo_median), ( + f"wrong tempo median: expected {tempo_median}, got {median_match.group(1)}" + ) + + +all_cases = ( + ("ENHANCED_CASE_1", enhanced_case_1), + ("ENHANCED_CASE_2", enhanced_case_2), + ("ENHANCED_CASE_3", enhanced_case_3), +) +selected = os.environ.get("ENHANCED_CASE") +assert selected is None or selected in dict(all_cases), f"unknown ENHANCED_CASE: {selected}" +failures = [] +for case_id, validator in all_cases: + if selected and case_id != selected: + continue + try: + validator() + print(f"PASS {case_id}") + except Exception as error: # keep cases independently executable/reportable + failures.append((case_id, error)) + print(f"FAIL {case_id}: {error}") + +assert not failures, f"{len(failures)} enhanced case(s) failed" diff --git a/task_028/tests/validate_outputs.py b/task_028/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..3e65b4244d486c454a2acfb0d16a1616a964354b --- /dev/null +++ b/task_028/tests/validate_outputs.py @@ -0,0 +1,24 @@ +import csv, pathlib +from statistics import mean, median +root = pathlib.Path.cwd() +for name in ['report.html', 'top_5_activity_songs.csv']: + assert (root / name).exists() and (root / name).stat().st_size > 0, f'missing output {name}' +report = (root / 'report.html').read_text(encoding='utf-8', errors='ignore').lower() +assert report.count('= 3 and '= 2000] +expected_top = sorted(filtered, key=lambda r: float(r['energy']) * 0.5 + float(r['valence']) * 0.5, reverse=True)[:5] +top_text = '\n'.join(str(v).lower() for row in rows for v in row.values()) +assert expected_top[0]['track_name'].lower() in top_text, 'top activity song is not ranked correctly' +expected_tempo_mean = mean(float(r['tempo']) for r in filtered) +expected_tempo_median = median(float(r['tempo']) for r in filtered) +assert 'release_year' in report or '2000' in report or '年份' in report, 'report missing release_year/2000 filter' +assert 'danceability' in report or '舞蹈性' in report, 'report missing danceability analysis' +assert 'tempo' in report and any(word in report for word in ('mean', 'median', '均值', '中位')), 'report missing tempo mean/median' +assert str(round(expected_tempo_mean, 1)) in report or str(round(expected_tempo_median, 1)) in report or str(int(expected_tempo_mean)) in report, 'report missing expected tempo summary value' diff --git a/task_029/acceptance_checklist.json b/task_029/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..ae94151ece64e991b6dc32b4a0bd5e4a595bc09a --- /dev/null +++ b/task_029/acceptance_checklist.json @@ -0,0 +1,20 @@ +{ + "task_id": 45, + "category": "machine_learning", + "language": "python", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Python files compile; data-analysis tasks generate the requested output files from fixture data." + ], + "input_assets": [ + "train-images-idx3-ubyte", + "train-labels-idx1-ubyte" + ], + "expected_outputs": [ + "report.html" + ], + "risk_notes": [], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_029/environment/Dockerfile b/task_029/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b5c3125aadc8adae6187cdea0ad0c6d3cf3e505e --- /dev/null +++ b/task_029/environment/Dockerfile @@ -0,0 +1,7 @@ +FROM mcr.microsoft.com/playwright:v1.52.0-noble +USER root +RUN apt-get update && apt-get install -y --no-install-recommends python3-numpy python3-pil && ln -sf /usr/bin/python3 /usr/local/bin/python && rm -rf /var/lib/apt/lists/* +RUN npm install --global --prefix /usr playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules +WORKDIR /app +COPY ./code /app diff --git a/task_029/environment/code/README.md b/task_029/environment/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d5cc273b7af7a2f27ae08aa4bbe1316f6b87b26c --- /dev/null +++ b/task_029/environment/code/README.md @@ -0,0 +1 @@ +Tiny closed MNIST-style IDX fixture: 10 synthetic 8x8 images with labels 0/1. Use this local fixture only; do not download MNIST. diff --git a/task_029/environment/code/train-images-idx3-ubyte b/task_029/environment/code/train-images-idx3-ubyte new file mode 100644 index 0000000000000000000000000000000000000000..90bcc1acaf3c4a8dcf14d60994fcc3e4c5cf25c0 Binary files /dev/null and b/task_029/environment/code/train-images-idx3-ubyte differ diff --git a/task_029/environment/code/train-labels-idx1-ubyte b/task_029/environment/code/train-labels-idx1-ubyte new file mode 100644 index 0000000000000000000000000000000000000000..37a5472e659a07be505c0270a6b9e7847e6e85c5 Binary files /dev/null and b/task_029/environment/code/train-labels-idx1-ubyte differ diff --git a/task_029/environment/docker-compose.yaml b/task_029/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_029/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_029/instruction.md b/task_029/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f0b376573e87919a67476a2d2334986174154feb --- /dev/null +++ b/task_029/instruction.md @@ -0,0 +1,20 @@ +# Train and report a tiny MNIST classifier + +Use the supplied `train-images-idx3-ubyte` and `train-labels-idx1-ubyte`: ten synthetic 8×8 grayscale inputs with labels 0 and 1. Run `python3 solve.py` in the project root offline. Read IDX headers and verify that the image and label counts agree. + +## Training and predictions + +Normalize each image by dividing pixels by 255 and flattening to 64 values. Shuffle original indices with `random.Random(1).shuffle(indices)`; use the first 80% for training and the remainder for validation in shuffled order. Reproducibly train a 64-input MLP with 16 ReLU hidden units and two linear output logits. Update parameters by backpropagation on cross-entropy; optimizer and iteration count are unrestricted. Use actual learned weights, not a rule-based classifier, nearest-centroid classifier or prefilled predictions. + +- `model.json`: finite arrays `w1` (16×64), `b1` (16), `w2` (2×16), `b2` (2). Predict via the larger logit from `w2 * ReLU(w1*x + b1) + b2`, choosing 0 on a tie. +- `predictions.csv`: exact header `index,true_label,predicted_label`, then the two validation samples in shuffled order. Use original sample indices, actual IDX labels and the model's predictions. + +## Report + +Write directly openable `report.html` with at least two distinct source images. Use one `
      ` per preview, with 64 visible row-major `` pixels in an inline 8×8 SVG grid. Use `fill="rgb(g,g,g)"` with `g = 255 - original_pixel`, and show `index N, label M` for that source image. Identify MNIST, the MLP with 64 inputs and 16 ReLU units, normalization, and the split (for example, “80/20, seed: 1, Train: 8, Validation: 2”). Show `accuracy` and `macro F1` with the label and decimal value together in visible text, to at least five decimal places in [0,1]. Compute macro F1 by averaging the F1s for classes 0 and 1, using zero when a class has a zero denominator. There is no minimum accuracy target. + +## Acceptance Checklist + +- Running the same input reproducibly yields a trained model and the required validation rows, and changing training data can change the learned parameters. Predictions match the saved model's forward pass. +- The report identifies the split, transform and network and shows accuracy and macro F1 recomputed from its validation predictions. +- At least two distinct visible previews match original IDX labels and pixels. diff --git a/task_029/quality_notes.md b/task_029/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..5bd13e03efbde934a11315d3757d2f175b73d582 --- /dev/null +++ b/task_029/quality_notes.md @@ -0,0 +1,6 @@ +# Quality notes — Task 45 + +- The bundled IDX fixture is a tiny synthetic 8×8 binary-class dataset, not full MNIST. +- Revision requires a genuine 64→16→2 MLP and machine-readable weights, validation predictions, metrics, and sample previews. +- `tests/validate_contract.py` independently recomputes forward passes and report metrics, validates preview pixels, and reruns after changing a training label. +- The label-mutation check detects a fixed model/report but does not formally prove a particular optimizer; the published contract and artifacts make behavior auditable. diff --git a/task_029/solution/README.md b/task_029/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_029/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_029/solution/code/solve.py b/task_029/solution/code/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..9822497bf1e4ac122ec85e17e03c6c74273cd7ae --- /dev/null +++ b/task_029/solution/code/solve.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +"""Deterministic single-hidden-layer MLP for the bundled IDX exercise.""" + +import csv +import json +import math +import random +import struct +from pathlib import Path + + +ROOT = Path(__file__).resolve().parent +HIDDEN = 16 + + +def read_idx(): + raw_images = (ROOT / "train-images-idx3-ubyte").read_bytes() + raw_labels = (ROOT / "train-labels-idx1-ubyte").read_bytes() + magic, count, rows, cols = struct.unpack_from(">IIII", raw_images) + label_magic, label_count = struct.unpack_from(">II", raw_labels) + assert magic == 2051 and label_magic == 2049 and count == label_count + assert rows * cols == 64 and len(raw_images) == 16 + count * 64 + assert len(raw_labels) == 8 + count + images = [[pixel / 255 for pixel in raw_images[16 + i * 64:16 + (i + 1) * 64]] + for i in range(count)] + labels = list(raw_labels[8:]) + assert set(labels) <= {0, 1} + return images, labels + + +def init_model(): + rng = random.Random(45) + return { + "w1": [[rng.uniform(-0.15, 0.15) for _ in range(64)] for _ in range(HIDDEN)], + "b1": [0.01] * HIDDEN, + "w2": [[rng.uniform(-0.15, 0.15) for _ in range(HIDDEN)] for _ in range(2)], + "b2": [0.0, 0.0], + } + + +def forward(model, x): + hidden = [max(0.0, sum(a * b for a, b in zip(row, x)) + bias) + for row, bias in zip(model["w1"], model["b1"])] + logits = [sum(a * b for a, b in zip(row, hidden)) + bias + for row, bias in zip(model["w2"], model["b2"])] + return hidden, logits + + +def train(model, images, labels, train_indices): + rng = random.Random(1) + for _ in range(180): + order = list(train_indices) + rng.shuffle(order) + for index in order: + x, target = images[index], labels[index] + hidden, logits = forward(model, x) + shift = max(logits) + exps = [math.exp(value - shift) for value in logits] + probs = [value / sum(exps) for value in exps] + delta2 = [probs[k] - (1.0 if k == target else 0.0) for k in range(2)] + old_w2 = [row[:] for row in model["w2"]] + delta1 = [sum(delta2[k] * old_w2[k][j] for k in range(2)) + if hidden[j] > 0 else 0.0 for j in range(HIDDEN)] + rate = 0.08 + for k in range(2): + for j in range(HIDDEN): + model["w2"][k][j] -= rate * delta2[k] * hidden[j] + model["b2"][k] -= rate * delta2[k] + for j in range(HIDDEN): + for i in range(64): + model["w1"][j][i] -= rate * delta1[j] * x[i] + model["b1"][j] -= rate * delta1[j] + + +def sample_svg(x): + cells = [] + for i, value in enumerate(x): + shade = 255 - round(value * 255) + cells.append(f'') + return '' + ''.join(cells) + '' + + +def metrics(pairs): + accuracy = sum(truth == pred for truth, pred in pairs) / len(pairs) + f1s = [] + for label in (0, 1): + tp = sum(truth == label and pred == label for truth, pred in pairs) + fp = sum(truth != label and pred == label for truth, pred in pairs) + fn = sum(truth == label and pred != label for truth, pred in pairs) + f1s.append(2 * tp / (2 * tp + fp + fn) if 2 * tp + fp + fn else 0.0) + return accuracy, sum(f1s) / 2 + + +def main(): + images, labels = read_idx() + indices = list(range(len(images))) + random.Random(1).shuffle(indices) + split = int(0.8 * len(indices)) + train_indices, validation_indices = indices[:split], indices[split:] + model = init_model() + train(model, images, labels, train_indices) + (ROOT / "model.json").write_text(json.dumps(model, allow_nan=False), encoding="utf-8") + predictions = [] + for index in validation_indices: + _, logits = forward(model, images[index]) + predictions.append((index, labels[index], int(logits[1] > logits[0]))) + with (ROOT / "predictions.csv").open("w", newline="", encoding="utf-8") as handle: + writer = csv.writer(handle) + writer.writerow(["index", "true_label", "predicted_label"]) + writer.writerows(predictions) + accuracy, macro_f1 = metrics([(truth, pred) for _, truth, pred in predictions]) + previews = ''.join( + f'
      {sample_svg(images[index])}
      index {index}, label {labels[index]}
      ' + for index in indices[:4] + ) + report = ( + 'Tiny MNIST MLP report' + '' + '

      Tiny MNIST MLP classification

      seed=1; normalized pixels to [0,1]; ' + f'train={len(train_indices)}; validation={len(validation_indices)}; 80/20 split.

      ' + '

      MLP structure: 64 inputs → 16 ReLU hidden units → 2 output logits; ' + 'cross-entropy, backpropagation, 180 epochs.

      ' + f'

      accuracy={accuracy:.6f}; macro F1={macro_f1:.6f}

      ' + f'
      {previews}
      ' + ) + (ROOT / "report.html").write_text(report, encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/task_029/solution/solve.sh b/task_029/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_029/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_029/task.toml b/task_029/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_029/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_029/task_meta.json b/task_029/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..39c71e03d32a99074dbbd8c886f5c1074b0d7644 --- /dev/null +++ b/task_029/task_meta.json @@ -0,0 +1,24 @@ +{ + "task_id": 45, + "task_category": "machine_learning", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 1, + "language": "python", + "tool_files_from_selected_trace": [ + "mnist_classification.py", + "report.html", + "sample_images.txt", + "simple_mnist.py" + ], + "input_assets": [ + "train-images-idx3-ubyte", + "train-labels-idx1-ubyte" + ], + "expected_outputs": [ + "report.html" + ], + "source_row_id": 270, + "repair_revision": "2026-09-29", + "instruction_sha256": "86630b4fc921351fcd59fcc53eb8b33775445b1abc2a71c751ef54f95a97be1d" +} diff --git a/task_029/tests/_shared/contract_checker.js b/task_029/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_029/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_029/tests/_shared/static_enhancer.sh b/task_029/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_029/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_029/tests/enhancement_cases.json b/task_029/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..6db89531efb7dabf4cee5e542d230b29d6acd5dc --- /dev/null +++ b/task_029/tests/enhancement_cases.json @@ -0,0 +1,26 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "1、加载MNIST数据集(在当前 dir 底下: train-images-idx3-ubyte train-labels-idx1-ubyte)并进行简单展示;", + "validator": "tests/validate_enhanced.py#enhanced_case_1", + "behavior": "Validates both complete IDX files against their headers; validate_contract.py additionally checks at least two pixel-accurate embedded sample previews." + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "2、对数据集进行划分,80%训练集,20%验证集( 使用 seed(1));\n3、定义合适的transforms逻辑对数据进行变换;", + "validator": "tests/validate_enhanced.py#enhanced_case_2", + "behavior": "Checks observable 8/2 counts derived from the ten-image fixture, the 80/20 ratio, seed(1), and transform/normalization evidence without prescribing a library." + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "2、对数据集进行划分,80%训练集,20%验证集( 使用 seed(1));\n在 report.html 里面告诉我最终的 f1, acc。", + "validator": "tests/validate_enhanced.py#enhanced_case_3", + "behavior": "Reruns the candidate in an isolated directory with fixed PYTHONHASHSEED and cleared proxies, then requires labeled accuracy and F1 to reproduce. validate_contract.py independently checks the specified MLP forward pass, both metrics and a training-label mutation." + }, + { + "case_id": "CONTRACT_AND_MUTATION", + "instruction_evidence": "model.json、predictions.csv、真实像素预览、accuracy 和 macro F1,以及训练输入变化后重跑。", + "validator": "tests/validate_contract.py", + "behavior": "独立前向计算及指标/预览核验,并更换训练标签,确认模型参数响应输入。" + } +] diff --git a/task_029/tests/test.sh b/task_029/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8e131da871e7515e7b1b1c4bc4c4fd1c238cd5d9 --- /dev/null +++ b/task_029/tests/test.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +set -euo pipefail +set +e +TASK_ID='45' +source "$(cd "$(dirname "$0")" && pwd)/_shared/static_enhancer.sh" +LOG_DIR="/logs/verifier" +if ! mkdir -p "$LOG_DIR" 2>/dev/null; then LOG_DIR="logs/verifier"; mkdir -p "$LOG_DIR"; fi +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +if [ ! -f solve.py ]; then + echo "solve.py entrypoint missing" + exit 0 +fi +PASS=1 +CHECKS=0 +FAILS=0 + +note() { echo "[Task $TASK_ID] $*"; } +fail() { note "FAIL: $*"; PASS=0; FAILS=$((FAILS+1)); } +check() { CHECKS=$((CHECKS+1)); "$@"; local code=$?; if [ $code -ne 0 ]; then fail "$*"; fi; } +have_any() { local pattern="$1"; compgen -G "$pattern" >/dev/null 2>&1; } +grep_any() { local pattern="$1"; shift; grep -REiq -- "$pattern" "$@" 2>/dev/null; } +source_files() { find . -type f \( -name '*.html' -o -name '*.js' -o -name '*.jsx' -o -name '*.ts' -o -name '*.tsx' -o -name '*.css' -o -name '*.py' -o -name '*.go' -o -name '*.swift' -o -name '*.svg' \) ! -path './tests/*' ! -path './logs/*'; } + +note "enhanced deterministic verifier start" +static_enhance_check "${TASK_ID}" "$(pwd)" +mapfile -t py_files < <(find . -type f -name '*.py' ! -path './tests/*') +if [ ${#py_files[@]} -eq 0 ]; then fail "no Python source found"; fi +if command -v python3 >/dev/null 2>&1; then + for f in "${py_files[@]}"; do python3 -m py_compile "$f" >/tmp/harbor_py_compile.log 2>&1 || fail "python compile failed: $f"; done +fi +if command -v python3 >/dev/null 2>&1 && [ -f solve.py ]; then + env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy \ + PYTHONHASHSEED=1 timeout 60s python3 solve.py >/tmp/harbor_data_run.log 2>&1 \ + || fail "data script did not run successfully" +else + fail "solve.py entrypoint missing" +fi +check test -s 'report.html' + +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +if command -v python3 >/dev/null 2>&1; then + check env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy \ + PYTHONHASHSEED=1 timeout 90s python3 "$TEST_DIR/validate_outputs.py" + check env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy \ + PYTHONHASHSEED=1 timeout 150s python3 "$TEST_DIR/validate_enhanced.py" + check env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy \ + PYTHONHASHSEED=1 timeout 150s python3 "$TEST_DIR/validate_contract.py" +else + fail "python3 unavailable for output validation" +fi +# BEGIN AAAV_DYNAMIC_TEST +if [ -f "$TEST_DIR/validate_aaav_dynamic.js" ]; then + if command -v node >/dev/null 2>&1; then + GLOBAL_NODE_PATH="${NODE_PATH:-$(npm root -g 2>/dev/null)}" + check env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy \ + NODE_PATH="$GLOBAL_NODE_PATH" \ + timeout 90s node "$TEST_DIR/validate_aaav_dynamic.js" + else + fail "node is required for browser validation" + fi +fi +# END AAAV_DYNAMIC_TEST +note "checks=$CHECKS fails=$FAILS" +if [ "$PASS" -eq 1 ]; then + echo 1 > "$REWARD_FILE" + note "PASS" + exit 0 +fi +echo 0 > "$REWARD_FILE" +note "FAIL" +exit 0 diff --git a/task_029/tests/validate_aaav_dynamic.js b/task_029/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..024dccf97ff34614d1a1fee4980503b21624b902 --- /dev/null +++ b/task_029/tests/validate_aaav_dynamic.js @@ -0,0 +1,63 @@ +const fs = require('fs'); +const path = require('path'); +const {pathToFileURL} = require('url'); +const {chromium} = require('playwright'); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +(async () => { + const images = fs.readFileSync('train-images-idx3-ubyte'); + const labels = fs.readFileSync('train-labels-idx1-ubyte'); + const browser = await chromium.launch({headless: true}); + try { + const page = await browser.newPage({viewport: {width: 1100, height: 760}}); + const errors = []; + page.on('pageerror', error => errors.push(error.message)); + await page.goto(pathToFileURL(path.resolve('report.html')).href); + const previews = await page.locator('figure').evaluateAll(figures => figures.map(figure => { + const visible = element => { + for (let node = element; node; node = node.parentElement) { + const style = getComputedStyle(node); + if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) return false; + } + const rect = element.getBoundingClientRect(); + return rect.width > 0 && rect.height > 0; + }; + return { + text: figure.innerText, + visible: visible(figure), + pixels: [...figure.querySelectorAll('svg rect')].map(rect => { + const box = rect.getBoundingClientRect(); + return {x: box.x, y: box.y, width: box.width, height: box.height, + fill: getComputedStyle(rect).fill, visible: visible(rect)}; + }), + }; + })); + assert(previews.length >= 2, 'show at least two sample figures'); + for (const figure of previews.slice(0, 2)) { + const match = /index\s+(\d+)\s*,\s*label\s+(\d+)/i.exec(figure.text); + assert(match && figure.visible, 'sample index and label must be visible'); + const index = Number(match[1]); + assert(Number(match[2]) === labels[8 + index], 'visible sample label disagrees with IDX'); + assert(figure.pixels.length === 64, 'sample needs all 64 pixels'); + const first = figure.pixels[0]; + for (const [offset, pixel] of figure.pixels.entries()) { + const shade = 255 - images[16 + index * 64 + offset]; + assert(pixel.visible && pixel.fill === `rgb(${shade}, ${shade}, ${shade})`, 'actual rendered sample color disagrees with IDX'); + const near = (actual, expected) => Math.abs(actual - expected) <= 0.75; + assert(near(pixel.width, first.width) && near(pixel.height, first.height) + && near(pixel.x, first.x + offset % 8 * first.width) + && near(pixel.y, first.y + Math.floor(offset / 8) * first.height), + 'sample pixels must form the claimed row-major 8x8 image without overlaps or gaps'); + } + } + assert(errors.length === 0, 'browser errors: ' + errors.join(' | ')); + fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + await page.screenshot({path: '/logs/verifier/visual-audit/tiny-mlp-report.png', fullPage: true}); + } finally { + await browser.close(); + } + console.log('Rendered IDX sample images and report passed'); +})().catch(error => {console.error(error); process.exit(1);}); diff --git a/task_029/tests/validate_contract.py b/task_029/tests/validate_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..4418b53aa9840d4253bb46a00727371e1124a3d9 --- /dev/null +++ b/task_029/tests/validate_contract.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Independently check IDX -> MLP -> predictions -> report and a training mutation.""" + +import csv +import html +import json +import math +import random +import re +import shutil +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + + +def load_idx(root): + image_bytes = (root / "train-images-idx3-ubyte").read_bytes() + label_bytes = (root / "train-labels-idx1-ubyte").read_bytes() + magic, count, rows, cols = struct.unpack_from(">IIII", image_bytes) + label_magic, label_count = struct.unpack_from(">II", label_bytes) + assert (magic, label_magic) == (2051, 2049) + assert count == label_count == 10 and (rows, cols) == (8, 8) + assert len(image_bytes) == 16 + count * rows * cols + assert len(label_bytes) == 8 + label_count + images = [[pixel / 255 for pixel in image_bytes[16 + i * 64:16 + (i + 1) * 64]] + for i in range(count)] + return images, list(label_bytes[8:]) + + +def matrix(value, rows, cols, name): + assert isinstance(value, list) and len(value) == rows, f"{name} rows" + for row in value: + assert isinstance(row, list) and len(row) == cols, f"{name} columns" + assert all(type(x) in (int, float) and math.isfinite(x) for x in row), f"{name} finite values" + + +def vector(value, size, name): + assert isinstance(value, list) and len(value) == size, f"{name} size" + assert all(type(x) in (int, float) and math.isfinite(x) for x in value), f"{name} finite values" + + +def load_model(root): + model = json.loads((root / "model.json").read_text(encoding="utf-8")) + assert {"w1", "b1", "w2", "b2"} <= set(model), 'model is missing required weights' + matrix(model["w1"], 16, 64, "w1") + vector(model["b1"], 16, "b1") + matrix(model["w2"], 2, 16, "w2") + vector(model["b2"], 2, "b2") + assert any(abs(x) > 1e-9 for row in model["w1"] for x in row), "empty hidden layer" + assert any(abs(x) > 1e-9 for row in model["w2"] for x in row), "empty output layer" + return model + + +def logits(model, image): + hidden = [max(0.0, sum(w * x for w, x in zip(row, image)) + bias) + for row, bias in zip(model["w1"], model["b1"])] + return [sum(w * h for w, h in zip(row, hidden)) + bias + for row, bias in zip(model["w2"], model["b2"])] + + +def predict(model, image): + scores = logits(model, image) + return int(scores[1] > scores[0]) + + +def metrics(pairs): + accuracy = sum(truth == pred for truth, pred in pairs) / len(pairs) + scores = [] + for label in (0, 1): + tp = sum(truth == label and pred == label for truth, pred in pairs) + fp = sum(truth != label and pred == label for truth, pred in pairs) + fn = sum(truth == label and pred != label for truth, pred in pairs) + scores.append(2 * tp / (2 * tp + fp + fn) if 2 * tp + fp + fn else 0.0) + return accuracy, sum(scores) / 2 + + +def check(root): + images, labels = load_idx(root) + model = load_model(root) + indices = list(range(len(images))) + random.Random(1).shuffle(indices) + validation = indices[int(0.8 * len(indices)):] + with (root / "predictions.csv").open(newline="", encoding="utf-8") as handle: + reader = csv.DictReader(handle) + assert reader.fieldnames == ["index", "true_label", "predicted_label"] + rows = list(reader) + assert len(rows) == len(validation), "validation row count" + pairs = [] + for row, index in zip(rows, validation): + assert int(row["index"]) == index, "validation index/order mismatch" + truth, predicted = int(row["true_label"]), int(row["predicted_label"]) + assert truth == labels[index], "IDX label mismatch" + assert predicted == predict(model, images[index]), "prediction disagrees with model forward pass" + pairs.append((truth, predicted)) + accuracy, macro_f1 = metrics(pairs) + report = (root / "report.html").read_text(encoding="utf-8") + visible = html.unescape(re.sub(r'<[^>]+>', ' ', report)) + assert re.search(r"64\s*(?:inputs|输入|→|->)", visible, re.I) + assert re.search(r"16\s*(?:个\s*)?ReLU", visible, re.I) + assert re.search(r"(?:seed|种子)\s*[:=:]?\s*1", visible, re.I) + assert re.search(r"(?:train|训练(?:样本)?(?:数)?)\s*[:=:]?\s*8", visible, re.I) + assert re.search(r"(?:validation|验证(?:样本)?(?:数)?)\s*[:=:]?\s*2", visible, re.I) + for label, expected in ((r"accuracy", accuracy), (r"macro\s*f1", macro_f1)): + match = re.search(label + r"\s*[:=:]\s*(0(?:\.\d+)?|1(?:\.0+)?)", visible, re.I) + assert match, f"report missing {label} metric" + assert abs(float(match.group(1)) - expected) <= 1e-5, f"report {label} disagrees with predictions" + # Each embedded 8x8 SVG preview must actually depict a bundled sample. + figures = re.findall(r"]*>(.*?)
      ", report, flags=re.I | re.S) + assert len(figures) >= 2, "show at least two sample images" + preview_indices = set() + for figure in figures[:2]: + match = re.search(r"index\s+(\d+)\s*,\s*label\s+(\d+)", figure, re.I) + assert match, "sample preview lacks index and label" + index, label = map(int, match.groups()) + preview_indices.add(index) + assert 0 <= index < len(images) and label == labels[index] + fills = re.findall(r"fill\s*=\s*['\"]rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)['\"]", figure) + assert len(fills) == 64, "sample preview must contain all 64 pixels" + expected = [255 - round(pixel * 255) for pixel in images[index]] + assert [tuple(map(int, triplet)) for triplet in fills] == [(x, x, x) for x in expected], ( + "sample preview does not match IDX pixels" + ) + assert len(preview_indices) >= 2, 'preview at least two distinct input samples' + return model + + +def functional_change(before, after, examples): + # Compare logit differences from the actual forward pass. Training may + # change confidence even if the predicted classes all remain the same. + for example in examples: + original = logits(before, example) + updated = logits(after, example) + if not math.isclose(original[1] - original[0], updated[1] - updated[0], + rel_tol=0, abs_tol=1e-12): + return True + return False + + +def run_mutation(root, baseline_model): + with tempfile.TemporaryDirectory(prefix="task45-mutation-") as tmp: + work = Path(tmp) / "candidate" + shutil.copytree(root, work, ignore=shutil.ignore_patterns("tests", "logs", "*.pyc", "__pycache__")) + labels_path = work / "train-labels-idx1-ubyte" + data = bytearray(labels_path.read_bytes()) + indices = list(range(10)) + random.Random(1).shuffle(indices) + for affected in (indices[:1], indices[:8]): + updated = bytearray(data) + for index in affected: + updated[8 + index] = 1 - updated[8 + index] + labels_path.write_bytes(updated) + for name in ("report.html", "predictions.csv", "model.json"): + (work / name).unlink(missing_ok=True) + result = subprocess.run([sys.executable, "solve.py"], cwd=work, capture_output=True, + text=True, timeout=45) + assert result.returncode == 0, f"candidate failed modified input: {result.stderr}" + updated_model = check(work) + images, _ = load_idx(work) + if functional_change(baseline_model, updated_model, images): + return + raise AssertionError("training-label changes affected no model logit differences") + +if __name__ == "__main__": + root = Path.cwd() + baseline = check(root) + run_mutation(root, baseline) + print("MLP contract and input-mutation checks passed") diff --git a/task_029/tests/validate_enhanced.py b/task_029/tests/validate_enhanced.py new file mode 100644 index 0000000000000000000000000000000000000000..2f403f5f378abfcbfd326a49e56c99b06fba1eb7 --- /dev/null +++ b/task_029/tests/validate_enhanced.py @@ -0,0 +1,150 @@ +"""Instruction-derived deterministic checks for Task 45.""" + +import html +import os +import pathlib +import re +import shutil +import struct +import subprocess +import tempfile + + +ROOT = pathlib.Path.cwd() +IMAGE_FILE = ROOT / "train-images-idx3-ubyte" +LABEL_FILE = ROOT / "train-labels-idx1-ubyte" +report_raw = (ROOT / "report.html").read_text(encoding="utf-8", errors="ignore") +report = html.unescape(report_raw).casefold() +source = "\n".join( + path.read_text(encoding="utf-8", errors="ignore") + for path in sorted(ROOT.rglob("*.py")) + if "tests" not in path.parts and "logs" not in path.parts +).casefold() + + +def labeled_values(text, labels): + joined = "|".join(labels) + pattern = rf"(?:{joined})[^0-9]{{0,40}}(0(?:\.\d+)?|1(?:\.0+)?)" + return [float(value) for value in re.findall(pattern, text)] + + +def has_labeled_count(text, labels, value): + joined = "|".join(labels) + after = rf"(?:{joined})[^0-9]{{0,30}}{value}(?!\d)" + before = rf"(?IIII", image_header) +label_magic, label_count = struct.unpack(">II", label_header) + + +# ENHANCED_CASE_1: validate complete IDX framing. Pixel-accurate sample +# visualization and the MLP contract are checked in validate_contract.py. +def enhanced_case_1(): + assert magic == 2051 and label_magic == 2049, "invalid bundled IDX magic numbers" + assert count == label_count and count > 0, "IDX image/label counts disagree" + assert IMAGE_FILE.stat().st_size == 16 + count * rows * cols, ( + "IDX image payload length does not match its header" + ) + assert LABEL_FILE.stat().st_size == 8 + label_count, ( + "IDX label payload length does not match its header" + ) + assert "mnist" in report, "report does not identify the loaded MNIST fixture" + + +# ENHANCED_CASE_2: the fixed ten-sample fixture implies an 8/2 split. Validate +# observable report values and implementation evidence for 80/20, seed(1), and +# an applied transform without requiring a particular ML library. +def enhanced_case_2(): + expected_train = int(count * 0.8) + expected_validation = count - expected_train + assert re.search(r"80\s*(?:%|/\s*20)|0\.8|4\s*:\s*1", report), ( + "report does not state the required 80/20 split" + ) + assert has_labeled_count(report, ("train", "训练"), expected_train), ( + f"report does not state the fixture-derived training count {expected_train}" + ) + assert has_labeled_count(report, ("validation", "valid", "val", "验证"), expected_validation), ( + f"report does not state the fixture-derived validation count {expected_validation}" + ) + assert re.search(r"(?:seed|random_state)\s*(?:\(|=|:)?\s*1(?!\d)", report), ( + "implementation/report does not identify seed(1) or random_state=1" + ) + assert re.search(r"transform|normaliz|标准化|归一化|scale", report), ( + "implementation/report lacks an applied transform or normalization" + ) + + +# ENHANCED_CASE_3: seed(1) must make final reported metrics reproducible. Run +# the candidate again in a clean isolated directory and compare labeled acc/F1 +# values, without prescribing the reference's classifier or an ML framework. +def enhanced_case_3(): + baseline_accuracy = labeled_values(report, ("accuracy", "acc", "准确率")) + baseline_f1 = labeled_values(report, ("macro[ _-]?f1", "f1(?:[ _-]?score)?")) + assert baseline_accuracy and baseline_f1, "report lacks labeled final accuracy and F1 values" + + py_files = sorted( + path for path in ROOT.rglob("*.py") + if "tests" not in path.parts and "logs" not in path.parts + ) + assert py_files, "no candidate Python program found" + main_py = py_files[0] + for path in py_files: + if any(token in path.name.casefold() for token in ("analysis", "example", "transform", "main")): + main_py = path + break + + with tempfile.TemporaryDirectory(prefix="task45_case3_") as tmp_name: + work = pathlib.Path(tmp_name) / "work" + shutil.copytree( + ROOT, + work, + ignore=shutil.ignore_patterns("tests", "logs", "*.pyc", "__pycache__"), + ) + (work / "report.html").unlink(missing_ok=True) + env = os.environ.copy() + for key in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"): + env.pop(key, None) + env["PYTHONHASHSEED"] = "1" + subprocess.run( + ["python3", str(main_py.relative_to(ROOT))], cwd=work, env=env, + timeout=60, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, + ) + rerun_path = work / "report.html" + assert rerun_path.is_file() and rerun_path.stat().st_size > 0, ( + "isolated rerun did not emit report.html" + ) + rerun = html.unescape(rerun_path.read_text(encoding="utf-8", errors="ignore")).casefold() + rerun_accuracy = labeled_values(rerun, ("accuracy", "acc", "准确率")) + rerun_f1 = labeled_values(rerun, ("macro[ _-]?f1", "f1(?:[ _-]?score)?")) + assert rerun_accuracy and rerun_f1, "isolated rerun lost labeled final metrics" + assert baseline_accuracy == rerun_accuracy, ( + f"accuracy is not reproducible with seed(1): {baseline_accuracy} vs {rerun_accuracy}" + ) + assert baseline_f1 == rerun_f1, ( + f"F1 is not reproducible with seed(1): {baseline_f1} vs {rerun_f1}" + ) + + +all_cases = ( + ("ENHANCED_CASE_1", enhanced_case_1), + ("ENHANCED_CASE_2", enhanced_case_2), + ("ENHANCED_CASE_3", enhanced_case_3), +) +selected = os.environ.get("ENHANCED_CASE") +assert selected is None or selected in dict(all_cases), f"unknown ENHANCED_CASE: {selected}" +failures = [] +for case_id, validator in all_cases: + if selected and case_id != selected: + continue + try: + validator() + print(f"PASS {case_id}") + except Exception as error: # keep cases independently executable/reportable + failures.append((case_id, error)) + print(f"FAIL {case_id}: {error}") + +assert not failures, f"{len(failures)} enhanced case(s) failed" diff --git a/task_029/tests/validate_outputs.py b/task_029/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..3a037b3cfe8b38b8d793a8fa820fa33ce824f238 --- /dev/null +++ b/task_029/tests/validate_outputs.py @@ -0,0 +1,32 @@ +import pathlib +import re +import struct +root = pathlib.Path.cwd() +img_path = root / 'train-images-idx3-ubyte' +label_path = root / 'train-labels-idx1-ubyte' +assert img_path.exists(), 'missing train-images-idx3-ubyte fixture' +assert label_path.exists(), 'missing train-labels-idx1-ubyte fixture' +magic, count, rows, cols = struct.unpack('>IIII', img_path.read_bytes()[:16]) +assert (magic, count, rows, cols) == (2051, 10, 8, 8), 'unexpected tiny MNIST image header' +lmagic, lcount = struct.unpack('>II', label_path.read_bytes()[:8]) +assert (lmagic, lcount) == (2049, 10), 'unexpected tiny MNIST label header' +report_path = root / 'report.html' +assert report_path.exists() and report_path.stat().st_size > 0, 'missing report.html' +report = report_path.read_text(encoding='utf-8', errors='ignore').lower() +for token in ['mnist', 'mlp']: + assert token in report, f'report missing {token}' +assert 'f1' in report, 'report missing f1' +assert 'acc' in report or 'accuracy' in report, 'report missing accuracy/acc' +assert ( + '80/20' in report + or '4:1' in report + or ('80%' in report and '20%' in report) + or ('0.8' in report and '0.2' in report) +), 'report missing 80/20 split evidence' +numbers = [float(x) for x in re.findall(r'(?` within `report.html`, using a local file or the same image embedded as a data URL. + +Explain the data, K-Means, why you chose K, and the interpretation of the farthest 5%. Discuss whether a color-feature outlier implies a corrupt image, using the displayed samples rather than just listing filenames. + +## Acceptance Checklist + +- The center table is a valid converged K-Means solution for the current features. The ranked anomaly table has the correct count, IDs, order and distances. +- Each comparison row shows the matching source image and center. The offline report visibly displays the comparison and explains what the anomaly score means. +- Recomputing after changes to the source images or features yields corresponding artifacts. diff --git a/task_030/quality_notes.md b/task_030/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..569002e2a2f22166aad79b2875ae767eb3d71acf --- /dev/null +++ b/task_030/quality_notes.md @@ -0,0 +1,4 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. diff --git a/task_030/solution/README.md b/task_030/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_030/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_030/solution/code/solve.py b/task_030/solution/code/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..2f395828255c6bd55f60adcbf388cbfad1e2458a --- /dev/null +++ b/task_030/solution/code/solve.py @@ -0,0 +1,50 @@ +import csv +import math +from PIL import Image + +rows = list(csv.DictReader(open('cifar_tiny.csv', encoding='utf-8-sig'))) +features = [(r['image_id'], (float(r['r']), float(r['g']), float(r['b']))) for r in rows] +points = [point for _, point in features] +k = min(3, len(points)) +centers = [points[0]] +while len(centers) < k: + centers.append(max(points, key=lambda p: min(math.dist(p, c) for c in centers))) +for _ in range(50): + groups = [[] for _ in centers] + for point in points: + groups[min(range(k), key=lambda i: (math.dist(point, centers[i]), i))].append(point) + updated = [tuple(sum(p[j] for p in group) / len(group) for j in range(3)) if group else centers[i] + for i, group in enumerate(groups)] + if updated == centers: + break + centers = updated +scored = [(min(math.dist(point, center) for center in centers), image_id) for image_id, point in features] +scored.sort(key=lambda item: (-item[0], item[1])) +chosen = scored[:max(1, math.ceil(len(scored) * 0.05))] +with open('anomalies.csv', 'w', newline='', encoding='utf-8') as f: + writer = csv.writer(f); writer.writerow(['image_id', 'distance']) + for dist, image_id in chosen: writer.writerow([image_id, round(dist, 3)]) +with open('cluster_centers.csv', 'w', newline='', encoding='utf-8') as f: + writer = csv.writer(f); writer.writerow(['cluster', 'r', 'g', 'b']) + for i, center in enumerate(centers): writer.writerow([i, *[round(value, 3) for value in center]]) +by_id = {row['image_id']: row for row in rows} +grid = Image.new('RGB', (128, 64 * len(chosen))) +for index, (_, image_id) in enumerate(chosen): + row = by_id[image_id] + source = Image.open(row['path']).convert('RGB') + grid.paste(source.resize((64, 64), Image.Resampling.NEAREST), (0, 64 * index)) + point = (float(row['r']), float(row['g']), float(row['b'])) + nearest = min(centers, key=lambda center: math.dist(point, center)) + swatch = tuple(round(value) for value in nearest) + grid.paste(Image.new('RGB', (64, 64), swatch), (64, 64 * index)) +grid.save('anomaly_grid.png') +open('report.html', 'w', encoding='utf-8').write( + '

      CIFAR tiny K-Means cluster anomaly report

      ' + f'

      K={k} retains three coarse color groups with fewer clusters than samples; farthest 5% from learned cluster centers: ' + + ', '.join(image_id for _, image_id in chosen) + + '.

      The farthest sample differs in RGB color from its nearest learned center. ' + 'This color-feature distance identifies a statistical outlier, not necessarily a corrupt image; ' + 'the original image and center swatch below support that visual comparison.

      ' + 'Original anomaly images on the left; nearest RGB cluster centers on the right' + '' +) diff --git a/task_030/solution/solve.sh b/task_030/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_030/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_030/task.toml b/task_030/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_030/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_030/task_meta.json b/task_030/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..9741190c0e88d35ab73f075f5710d839872f1322 --- /dev/null +++ b/task_030/task_meta.json @@ -0,0 +1,29 @@ +{ + "task_id": 46, + "task_category": "machine_learning", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 3, + "language": "python", + "tool_files_from_selected_trace": [ + "README.md", + "cifar10_clustering.py", + "cifar10_clustering_fast.py", + "cifar10_clustering_report.md", + "cifar10_clustering_simple.py" + ], + "input_assets": [ + "README.md", + "cifar_tiny.csv", + "images/" + ], + "expected_outputs": [ + "anomalies.csv", + "anomaly_grid.png", + "cluster_centers.csv", + "report.html" + ], + "source_row_id": 276, + "repair_revision": "2026-09-29", + "instruction_sha256": "de0be6744f41a697a5798f5ea486bc668b667fdc2e6411dea9e93d4d13b4f1f7" +} diff --git a/task_030/tests/_shared/contract_checker.js b/task_030/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_030/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_030/tests/_shared/static_enhancer.sh b/task_030/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_030/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_030/tests/enhancement_cases.json b/task_030/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..e932b02fe38e8f4b1dafaf6ed34399087c3e5f1d --- /dev/null +++ b/task_030/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "找出距离聚类中心最远的 5% 图像作为异常样本", + "validator": "tests/validate_enhancements.py::case_1_top_five_percent_contract", + "behavior": "Checks that anomalies.csv contains exactly 5% of fixture rows (with the required one-row minimum), uses unique fixture image ids, and reports finite non-negative distances." + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "使用 CSV 中的 RGB features 做 K-Means clustering,选择并报告合理的 K", + "validator": "tests/validate_enhancements.py::case_2_center_table_is_well_formed", + "behavior": "Checks a non-trivial K, the required center-table fields, unique cluster ids and center rows, and finite RGB center coordinates within the valid 0..255 feature domain." + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "生成 report.html、anomalies.csv、cluster_centers.csv 和 anomaly_grid.png;确定性验证器", + "validator": "tests/validate_enhancements.py::case_3_artifacts_are_deterministic", + "behavior": "Checks that the saved visualization has a PNG header and positive canvas dimensions, then reruns with proxies cleared and PYTHONHASHSEED fixed and requires all four artifacts to be byte-identical." + } +] diff --git a/task_030/tests/test.sh b/task_030/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..716f3559954d7b52c45243d756684227f78ee79c --- /dev/null +++ b/task_030/tests/test.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +set -euo pipefail +set +e +TASK_ID='46' +source "$(cd "$(dirname "$0")" && pwd)/_shared/static_enhancer.sh" +LOG_DIR="/logs/verifier" +if ! mkdir -p "$LOG_DIR" 2>/dev/null; then LOG_DIR="logs/verifier"; mkdir -p "$LOG_DIR"; fi +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +if [ ! -f solve.py ]; then + echo "solve.py entrypoint missing" + exit 0 +fi +PASS=1 +CHECKS=0 +FAILS=0 + +note() { echo "[Task $TASK_ID] $*"; } +fail() { note "FAIL: $*"; PASS=0; FAILS=$((FAILS+1)); } +check() { CHECKS=$((CHECKS+1)); "$@"; local code=$?; if [ $code -ne 0 ]; then fail "$*"; fi; } +have_any() { local pattern="$1"; compgen -G "$pattern" >/dev/null 2>&1; } +grep_any() { local pattern="$1"; shift; grep -REiq -- "$pattern" "$@" 2>/dev/null; } +source_files() { find . -type f \( -name '*.html' -o -name '*.js' -o -name '*.jsx' -o -name '*.ts' -o -name '*.tsx' -o -name '*.css' -o -name '*.py' -o -name '*.go' -o -name '*.swift' -o -name '*.svg' \) ! -path './tests/*' ! -path './logs/*'; } + +note "enhanced deterministic verifier start" +static_enhance_check "${TASK_ID}" "$(pwd)" +mapfile -t py_files < <(find . -type f -name '*.py' ! -path './tests/*') +if [ ${#py_files[@]} -eq 0 ]; then fail "no Python source found"; fi +if command -v python3 >/dev/null 2>&1; then + for f in "${py_files[@]}"; do python3 -m py_compile "$f" >/tmp/harbor_py_compile.log 2>&1 || fail "python compile failed: $f"; done +fi +if command -v python3 >/dev/null 2>&1 && [ ${#py_files[@]} -gt 0 ]; then + timeout 60s python3 solve.py >/tmp/harbor_data_run.log 2>&1 || fail "data script did not run successfully" +fi +check test -s 'anomalies.csv' +check test -s 'anomaly_grid.png' +check test -s 'cluster_centers.csv' +check test -s 'report.html' + +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +if command -v python3 >/dev/null 2>&1; then + check python3 "$TEST_DIR/validate_outputs.py" + check python3 "$TEST_DIR/validate_enhancements.py" +else + fail "python3 unavailable for output validation" +fi +# BEGIN AAAV_DYNAMIC_TEST +if [ -f "$TEST_DIR/validate_aaav_dynamic.js" ]; then + if command -v node >/dev/null 2>&1; then + GLOBAL_NODE_PATH="${NODE_PATH:-$(npm root -g 2>/dev/null)}" + check env NODE_PATH="$GLOBAL_NODE_PATH" node "$TEST_DIR/validate_aaav_dynamic.js" + else + fail "node is required for browser validation" + fi +fi +# END AAAV_DYNAMIC_TEST +note "checks=$CHECKS fails=$FAILS" +if [ "$PASS" -eq 1 ]; then + echo 1 > "$REWARD_FILE" + note "PASS" + exit 0 +fi +echo 0 > "$REWARD_FILE" +note "FAIL" +exit 0 diff --git a/task_030/tests/validate_aaav_dynamic.js b/task_030/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..1ffeaebff87b39718aa90dd906e120617c42fef2 --- /dev/null +++ b/task_030/tests/validate_aaav_dynamic.js @@ -0,0 +1,29 @@ +const fs = require('fs'); +const path = require('path'); +const {pathToFileURL} = require('url'); +const {chromium} = require('playwright'); + +(async () => { + const browser = await chromium.launch({headless: true}); + try { + const page = await browser.newPage({viewport: {width: 1100, height: 760}}); + const errors = []; + page.on('pageerror', error => errors.push(error.message)); + await page.goto(pathToFileURL(path.resolve('report.html')).href, {waitUntil: 'load'}); + const visibleImage = await page.locator('img').evaluateAll(images => images.some(image => { + const box = image.getBoundingClientRect(); + for (let node = image; node; node = node.parentElement) { + const style = getComputedStyle(node); + if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) return false; + } + return image.complete && image.naturalWidth >= 128 && image.naturalHeight >= 64 + && box.width > 0 && box.height > 0; + })); + if (!visibleImage) throw new Error('report must visibly display its anomaly/center comparison image'); + if (errors.length) throw new Error(errors.join(' | ')); + fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + await page.screenshot({path: '/logs/verifier/visual-audit/anomaly-report.png', fullPage: true}); + } finally { + await browser.close(); + } +})().catch(error => {console.error(error); process.exit(1);}); diff --git a/task_030/tests/validate_enhancements.py b/task_030/tests/validate_enhancements.py new file mode 100644 index 0000000000000000000000000000000000000000..56431a44bc8b5ba5e368f146aa5b15383ca15961 --- /dev/null +++ b/task_030/tests/validate_enhancements.py @@ -0,0 +1,126 @@ +import csv +import math +import os +import pathlib +import struct +import subprocess +import sys + + +root = pathlib.Path.cwd() +ARTIFACTS = ("anomalies.csv", "cluster_centers.csv", "anomaly_grid.png", "report.html") + + +def clean_environment(): + env = os.environ.copy() + for name in ( + "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", + "http_proxy", "https_proxy", "all_proxy", "no_proxy", + ): + env.pop(name, None) + env["PYTHONHASHSEED"] = "0" + return env + + +def run_candidate() -> None: + scripts = [root / 'solve.py'] + assert scripts, "missing candidate Python source" + scripts.sort(key=lambda p: ("cifar" not in p.name.lower(), "anomal" not in p.name.lower(), str(p))) + failures = [] + for script in scripts[:3]: + proc = subprocess.run( + [sys.executable, str(script)], cwd=root, capture_output=True, + text=True, timeout=60, env=clean_environment(), + ) + if proc.returncode == 0 and all( + (root / name).is_file() + for name in ARTIFACTS + ): + return + failures.append(f"{script}: rc={proc.returncode}: {proc.stderr[-300:]}") + raise AssertionError("candidate did not produce required artifacts: " + " | ".join(failures)) + + +def read_csv(name: str): + with (root / name).open(encoding="utf-8-sig", newline="") as handle: + return list(csv.DictReader(handle)) + + +def case_1_top_five_percent_contract() -> None: + # ENHANCED_CASE_1: the anomaly file represents exactly the farthest 5% population. + source_rows = read_csv("cifar_tiny.csv") + anomaly_rows = read_csv("anomalies.csv") + required = max(1, math.ceil(len(source_rows) * 0.05)) + assert len(anomaly_rows) == required, ( + f"expected {required} anomaly rows for {len(source_rows)} inputs, got {len(anomaly_rows)}" + ) + source_ids = {row["image_id"] for row in source_rows} + result_ids = [row.get("image_id") for row in anomaly_rows] + assert len(set(result_ids)) == len(result_ids), "anomaly image ids must be unique" + assert set(result_ids) <= source_ids, "anomalies.csv contains an id absent from the fixture" + for row in anomaly_rows: + distance = float(row["distance"]) + assert math.isfinite(distance) and distance >= 0, "anomaly distances must be finite and non-negative" + + +def case_2_center_table_is_well_formed() -> None: + # ENHANCED_CASE_2: the chosen K and reported RGB centers form a usable center table. + source_rows = read_csv("cifar_tiny.csv") + centers = read_csv("cluster_centers.csv") + assert 2 <= len(centers) < len(source_rows), "chosen K must be non-trivial and smaller than sample count" + required_columns = {"cluster", "r", "g", "b"} + assert required_columns <= set(centers[0]), "center table must contain cluster,r,g,b columns" + cluster_ids = [row["cluster"] for row in centers] + assert len(set(cluster_ids)) == len(cluster_ids), "cluster identifiers must be unique" + center_values = [] + for index, center in enumerate(centers): + point = [] + for channel in ("r", "g", "b"): + value = float(center[channel]) + assert math.isfinite(value), f"center {index} {channel} is not finite" + assert 0 <= value <= 255, f"center {index} {channel}={value} is outside the RGB domain" + point.append(value) + center_values.append(tuple(point)) + assert len(set(center_values)) == len(center_values), "reported centers must not be duplicates" + # A well-shaped arbitrary palette is not a fitted K-Means model. At a + # converged Lloyd solution, each non-empty center is its assigned mean. + groups = [[] for _ in center_values] + for row in source_rows: + point = tuple(float(row[channel]) for channel in ('r', 'g', 'b')) + nearest = min(range(len(center_values)), key=lambda i: (math.dist(point, center_values[i]), i)) + groups[nearest].append(point) + for center, group in zip(center_values, groups): + assert group, 'reported cluster must contain at least one source image' + mean = tuple(sum(point[j] for point in group) / len(group) for j in range(3)) + assert math.dist(center, mean) <= 0.01, 'center is not the mean of its nearest-assigned images' + + +def png_size(path: pathlib.Path) -> tuple[int, int]: + data = path.read_bytes() + assert data[:8] == b"\x89PNG\r\n\x1a\n", "anomaly_grid.png is not a PNG" + assert data[12:16] == b"IHDR" and len(data) >= 24, "PNG has no valid IHDR" + return struct.unpack(">II", data[16:24]) + + +def case_3_visualization_is_concrete() -> None: + # ENHANCED_CASE_3: the saved PNG has a concrete canvas. + width, height = png_size(root / "anomaly_grid.png") + assert width > 0 and height > 0, "anomaly visualization must have a non-empty canvas" + + +run_candidate() +cases = [ + ("ENHANCED_CASE_1", case_1_top_five_percent_contract), + ("ENHANCED_CASE_2", case_2_center_table_is_well_formed), + ("ENHANCED_CASE_3", case_3_visualization_is_concrete), +] +failed = [] +for case_id, validator in cases: + try: + validator() + print(f"{case_id}: PASS") + except Exception as exc: + failed.append(case_id) + print(f"{case_id}: FAIL: {exc}", file=sys.stderr) +if failed: + raise SystemExit(1) diff --git a/task_030/tests/validate_outputs.py b/task_030/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..74a02289ecc9420fe78ebd372414ec93fa765d12 --- /dev/null +++ b/task_030/tests/validate_outputs.py @@ -0,0 +1,159 @@ +import csv +import math +import pathlib +import re +import subprocess +import sys +from PIL import Image, ImageChops + +root = pathlib.Path.cwd() + + +def _py_sources(): + _skip = {"tests", "logs", "output", "__pycache__", "node_modules", ".git"} + return [ + p + for p in root.rglob("*.py") + if p.is_file() + and not (set(p.relative_to(root).parts) & _skip) + and p.name != "validate_outputs.py" + ] + + +def run_candidate() -> None: + scripts = [root / 'solve.py'] + assert scripts, "missing candidate python source" + + # Prefer scripts that look task-specific. + scripts = sorted( + scripts, + key=lambda p: 0 if ("cifar" in p.name.lower() or "anomaly" in p.name.lower()) else 1, + ) + failures = [] + for script in scripts[:2]: + proc = subprocess.run( + [sys.executable, str(script)], + cwd=root, + capture_output=True, + text=True, + timeout=60, + ) + if proc.returncode == 0: + return + failures.append((script.name, proc.returncode, proc.stdout, proc.stderr)) + raise AssertionError( + "candidate script(s) failed to execute:\n" + + "\n".join( + f"{name}: rc={rc}\nstdout={out}\nstderr={err}" + for name, rc, out, err in failures + ) + ) + + +def validate_once() -> None: + for name in [ + "cifar_tiny.csv", + "report.html", + "anomalies.csv", + "cluster_centers.csv", + "anomaly_grid.png", + ]: + p = root / name + assert p.exists() and p.stat().st_size > 0, f"missing or empty {name}" + + rows = list(csv.DictReader((root / "cifar_tiny.csv").open(encoding="utf-8-sig"))) + assert len(rows) >= 1, "cifar_tiny.csv is empty" + + got = list(csv.DictReader((root / "anomalies.csv").open(encoding="utf-8-sig"))) + assert got, "anomalies.csv is empty" + got_ids = [r.get("image_id") for r in got] + got_ids = [g for g in got_ids if g is not None] + centers = list(csv.DictReader((root / "cluster_centers.csv").open(encoding="utf-8-sig"))) + assert centers, "cluster_centers.csv is empty" + points = [(float(c["r"]), float(c["g"]), float(c["b"])) for c in centers] + scored = [] + for row in rows: + pixel = (float(row["r"]), float(row["g"]), float(row["b"])) + scored.append((min(math.dist(pixel, center) for center in points), row["image_id"])) + scored.sort(key=lambda item: (-item[0], item[1])) + required = max(1, math.ceil(len(rows) * 0.05)) + exp = [(image_id, distance) for distance, image_id in scored[:required]] + exp_ids = [img for img, _ in exp] + assert got_ids == exp_ids, ( + f"anomaly id mismatch; expected top 5% {exp_ids}, got {got_ids}" + ) + + exp_dist = {img: d for img, d in exp} + for r in got: + img = r.get("image_id") + got_d = r.get("distance") + assert img in exp_dist, f"unexpected anomaly row {img}" + if img in exp_dist and got_d is not None: + assert abs(float(got_d) - exp_dist[img]) <= 0.01, ( + f"distance mismatch for {img}: expected {exp_dist[img]}, got {got_d}" + ) + + by_id = {row["image_id"]: row for row in rows} + with Image.open(root / "anomaly_grid.png") as raw_grid: + assert raw_grid.format == "PNG", "anomaly_grid.png is not PNG" + grid = raw_grid.convert("RGB") + alpha = raw_grid.convert("RGBA").getchannel("A") + assert grid.width >= 128 and grid.height >= 64 * len(got), ( + "anomaly_grid.png must contain a 64-pixel sample and center swatch per anomaly" + ) + for index, item in enumerate(got): + source_row = by_id[item["image_id"]] + with Image.open(root / source_row["path"]) as raw_source: + source = raw_source.convert("RGB").resize((64, 64), Image.Resampling.NEAREST) + top = index * 64 + assert alpha.crop((0, top, 128, top + 64)).getextrema() == (255, 255), ( + f"comparison row is transparent for {item['image_id']}" + ) + sample = grid.crop((0, top, 64, top + 64)) + assert ImageChops.difference(source, sample).getbbox() is None, ( + f"visualization does not show source pixels for {item['image_id']}" + ) + rgb = tuple(float(source_row[channel]) for channel in ("r", "g", "b")) + nearest = min(points, key=lambda center: math.dist(rgb, center)) + swatch = grid.crop((64, top, 128, top + 64)) + assert all(abs(extreme - expected) <= 3 + for channel, expected in zip(swatch.getextrema(), nearest) + for extreme in channel), ( + f"visualization does not show the nearest center for {item['image_id']}" + ) + + report = (root / "report.html").read_text(encoding="utf-8", errors="ignore").lower() + assert 'cifar' in report, 'report missing fixture identity' + assert any(token in report for token in ('cluster', '聚类')), 'report missing clustering discussion' + assert any(token in report for token in ('anomal', '异常')), 'report missing anomaly discussion' + assert "k-means" in report or "kmeans" in report or 'k 均值' in report, "report missing K-Means" + assert "5%" in report or "5 percent" in report or "farthest" in report or '最远' in report, ( + "report missing farthest 5 percent anomaly discussion" + ) + + + +run_candidate() +validate_once() + +# Anti-hardcode: inject a bright synthetic outlier and force re-run should change anomaly set. +fixture_path = root / "cifar_tiny.csv" +original = fixture_path.read_text(encoding="utf-8-sig") +injected_image = root / "images" / "injected.ppm" +assert not injected_image.exists(), "test injection path already exists" +mutated = ( + original.rstrip() + + "\nimg_injected_mut,images/injected.ppm,255,255,255,super_anomaly\n" +) +try: + injected_image.write_text("P3\n4 4\n255\n" + "255 255 255 " * 16 + "\n", encoding="ascii") + fixture_path.write_text(mutated + "\n", encoding="utf-8") + run_candidate() + validate_once() +finally: + fixture_path.write_text(original, encoding="utf-8") + injected_image.unlink(missing_ok=True) + run_candidate() + validate_once() + +print("validate_outputs OK: task_046 recomputes top-5% anomalies from fixture and adapts to mutated data") diff --git a/task_031/acceptance_checklist.json b/task_031/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..6619d8f9855c481eca0bce5dca38edcc9516ac6d --- /dev/null +++ b/task_031/acceptance_checklist.json @@ -0,0 +1,19 @@ +{ + "task_id": 47, + "category": "machine_learning", + "language": "python", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Python files compile; data-analysis tasks generate the requested output files from fixture data." + ], + "input_assets": [ + "Audio_Speech_Actors_01-24/" + ], + "expected_outputs": [], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_031/environment/Dockerfile b/task_031/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b5c3125aadc8adae6187cdea0ad0c6d3cf3e505e --- /dev/null +++ b/task_031/environment/Dockerfile @@ -0,0 +1,7 @@ +FROM mcr.microsoft.com/playwright:v1.52.0-noble +USER root +RUN apt-get update && apt-get install -y --no-install-recommends python3-numpy python3-pil && ln -sf /usr/bin/python3 /usr/local/bin/python && rm -rf /var/lib/apt/lists/* +RUN npm install --global --prefix /usr playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules +WORKDIR /app +COPY ./code /app diff --git a/task_031/environment/code/Audio_Speech_Actors_01-24/Actor_01/03-01-01-01-01-01-01.wav b/task_031/environment/code/Audio_Speech_Actors_01-24/Actor_01/03-01-01-01-01-01-01.wav new file mode 100644 index 0000000000000000000000000000000000000000..a7e6f14e34f1a333ed889b4d8dd34fa9a0baf9bf --- /dev/null +++ b/task_031/environment/code/Audio_Speech_Actors_01-24/Actor_01/03-01-01-01-01-01-01.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:418a59ad300dc6384983fa95a97a3ffd131b1b1293828325dfb67c46f59ebdb6 +size 1964 diff --git a/task_031/environment/code/Audio_Speech_Actors_01-24/Actor_01/03-01-01-01-01-02-01.wav b/task_031/environment/code/Audio_Speech_Actors_01-24/Actor_01/03-01-01-01-01-02-01.wav new file mode 100644 index 0000000000000000000000000000000000000000..4a52129129f958e6c0307c02ec36e87e28ffaf7c --- /dev/null +++ b/task_031/environment/code/Audio_Speech_Actors_01-24/Actor_01/03-01-01-01-01-02-01.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:812eb62c10afc8a5853b4654b3f7e6ff3b1f1cd19486e36f4f11f12102b311c7 +size 1964 diff --git a/task_031/environment/code/Audio_Speech_Actors_01-24/Actor_01/03-01-03-01-01-01-01.wav b/task_031/environment/code/Audio_Speech_Actors_01-24/Actor_01/03-01-03-01-01-01-01.wav new file mode 100644 index 0000000000000000000000000000000000000000..ae2c97ecdaa16a2a9a26341be1c612490b58455a --- /dev/null +++ b/task_031/environment/code/Audio_Speech_Actors_01-24/Actor_01/03-01-03-01-01-01-01.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:027c0b1bc6ac35700e1045e37169d67545004560b8d4a007c24b766cd499744f +size 1964 diff --git a/task_031/environment/code/Audio_Speech_Actors_01-24/Actor_01/03-01-03-01-01-02-01.wav b/task_031/environment/code/Audio_Speech_Actors_01-24/Actor_01/03-01-03-01-01-02-01.wav new file mode 100644 index 0000000000000000000000000000000000000000..38d4370c892eed732ce273d8068e569d35c576e9 --- /dev/null +++ b/task_031/environment/code/Audio_Speech_Actors_01-24/Actor_01/03-01-03-01-01-02-01.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5fd93b2f2a15c28d9f85fd9edf59288356feada2c7bd103d4b419a12560a51d5 +size 1964 diff --git a/task_031/environment/code/README.md b/task_031/environment/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..607c6b3e3583bb6a4f11bc7eedf9626581c82e0a --- /dev/null +++ b/task_031/environment/code/README.md @@ -0,0 +1 @@ +Tiny closed RAVDESS-style fixture. Emotion code 01 means neutral, code 03 means happy. Use Audio_Speech_Actors_01-24 locally; do not download external audio. diff --git a/task_031/environment/code/analyze_ravdess.py b/task_031/environment/code/analyze_ravdess.py new file mode 100644 index 0000000000000000000000000000000000000000..48131c64d4e2491bc3e75e3b5b310e0f21077324 --- /dev/null +++ b/task_031/environment/code/analyze_ravdess.py @@ -0,0 +1 @@ +# Implement the RAVDESS neutral/happy MFCC analysis here. diff --git a/task_031/environment/docker-compose.yaml b/task_031/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_031/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_031/instruction.md b/task_031/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..64ea634cc0793ca3dede180ca92423f52fac59af --- /dev/null +++ b/task_031/instruction.md @@ -0,0 +1,28 @@ +# Cepstral comparison of neutral and happy speech + +Analyze the local WAV files in `Audio_Speech_Actors_01-24/` with `python3 analyze_ravdess.py` from the project root. Do not download audio or use external services. + +## Analysis + +Traverse nested directories for WAV files. Use the third hyphen-separated filename field as the emotion code: `01` is neutral, `03` is happy. Ignore other emotions. + +For each selected file, derive a time series of 13 MFCC-style coefficients from its PCM samples: extract spectral/filterbank energies, apply a log and cosine transform, then average coefficients over time. A standard offline MFCC library or an equivalent approximation is acceptable; coefficients must reflect spectral information rather than repeat a single measure of energy. Average the per-file vectors with equal weight within each emotion, regardless of file length. Compute the absolute difference of those two mean vectors. + +## Output + +Print exactly four lines to stdout (diagnostics may go to stderr): + +```text +neutral_count: X +happy_count: Y +mfcc_diff: [d1, d2, ..., d13] +max_diff_dim: D +``` + +Counts are integers. List 13 nonnegative finite differences with exactly three decimal places. `D` is the one-based index of the largest displayed difference, breaking ties in favor of the lowest index. + +## Acceptance Checklist + +- Nested target files count toward the correct emotion; other emotion codes do not affect the result. +- Differences depend on the spectra, not just amplitude, and are invariant when the two populations are swapped. Identical populations yield zero differences. +- The four-line output has the specified format and the maximum dimension agrees with the reported values and tie rule. diff --git a/task_031/quality_notes.md b/task_031/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..569002e2a2f22166aad79b2875ae767eb3d71acf --- /dev/null +++ b/task_031/quality_notes.md @@ -0,0 +1,4 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. diff --git a/task_031/solution/README.md b/task_031/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_031/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_031/solution/code/analyze_ravdess.py b/task_031/solution/code/analyze_ravdess.py new file mode 100644 index 0000000000000000000000000000000000000000..5583d46daa625dc8e59cbd8926c98b5d4d175eb4 --- /dev/null +++ b/task_031/solution/code/analyze_ravdess.py @@ -0,0 +1,75 @@ +"""Offline, lightweight MFCC-style log-spectrum/DCT analysis of local WAVs.""" +import math +import pathlib +import wave + + +N = 256 +HOP = 128 +BANDS = 20 +WINDOW = [0.54 - 0.46 * math.cos(2 * math.pi * i / (N - 1)) for i in range(N)] +COS = [[math.cos(2 * math.pi * k * i / N) for i in range(N)] for k in range(1, N // 2 + 1)] +SIN = [[math.sin(2 * math.pi * k * i / N) for i in range(N)] for k in range(1, N // 2 + 1)] + + +def samples_from_wav(path): + with wave.open(str(path), "rb") as wav: + width = wav.getsampwidth() + channels = wav.getnchannels() + raw = wav.readframes(wav.getnframes()) + assert width in (1, 2), f"unsupported sample width in {path}" + data = [] + stride = width * channels + for offset in range(0, len(raw), stride): + channel_values = [] + for channel in range(channels): + chunk = raw[offset + channel * width:offset + (channel + 1) * width] + value = int.from_bytes(chunk, "little", signed=(width == 2)) + channel_values.append((value - 128) / 128 if width == 1 else value / 32768) + data.append(sum(channel_values) / channels) + return data + + +def feature(path): + samples = samples_from_wav(path) + starts = range(0, max(1, len(samples) - N + 1), HOP) + frames = [] + for start in starts: + frame = [(samples[start + i] if start + i < len(samples) else 0) * WINDOW[i] for i in range(N)] + powers = [] + for cosine, sine in zip(COS, SIN): + re = sum(x * c for x, c in zip(frame, cosine)) + im = sum(x * s for x, s in zip(frame, sine)) + powers.append(re * re + im * im) + # Log-spaced spectral bands approximate a mel filter bank without external libraries. + edges = [int(round(math.exp(math.log(1) + i / BANDS * math.log(len(powers))))) for i in range(BANDS + 1)] + logs = [math.log1p(sum(powers[max(0, edges[i]-1):max(edges[i], edges[i+1])])) for i in range(BANDS)] + frames.append([ + sum(value * math.cos(math.pi * coefficient * (band + .5) / BANDS) + for band, value in enumerate(logs)) / BANDS + for coefficient in range(13) + ]) + return [sum(frame[i] for frame in frames) / len(frames) for i in range(13)] + + +root = pathlib.Path("Audio_Speech_Actors_01-24") +by_emotion = {"01": [], "03": []} +for path in sorted(root.rglob("*.wav")): + parts = path.stem.split("-") + if len(parts) >= 7 and parts[2] in by_emotion: + by_emotion[parts[2]].append(feature(path)) + + +def mean_features(items): + assert items, "both target emotions need audio files" + return [sum(row[i] for row in items) / len(items) for i in range(13)] + + +neutral = mean_features(by_emotion["01"]) +happy = mean_features(by_emotion["03"]) +diff = [round(abs(a - b), 3) for a, b in zip(neutral, happy)] +max_dim = max(range(13), key=lambda index: diff[index]) + 1 +print(f'neutral_count: {len(by_emotion["01"])}') +print(f'happy_count: {len(by_emotion["03"])}') +print("mfcc_diff: [" + ", ".join(f"{value:.3f}" for value in diff) + "]") +print(f"max_diff_dim: {max_dim}") diff --git a/task_031/solution/solve.sh b/task_031/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_031/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_031/task.toml b/task_031/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_031/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_031/task_meta.json b/task_031/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..f90e2d402919b9473a785405da0a992b7d0fc65c --- /dev/null +++ b/task_031/task_meta.json @@ -0,0 +1,22 @@ +{ + "task_id": 47, + "task_category": "machine_learning", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 2, + "language": "python", + "tool_files_from_selected_trace": [ + "README.md", + "mfcc_analysis.py", + "mfcc_analysis_final.py", + "mfcc_analysis_optimized.py", + "mfcc_analysis_simple.py" + ], + "input_assets": [ + "Audio_Speech_Actors_01-24/" + ], + "expected_outputs": [], + "source_row_id": 282, + "repair_revision": "2026-09-29", + "instruction_sha256": "1b703129414b85b1368802547c62e679fd8625e912a89ab9b78ccd0e133619c5" +} diff --git a/task_031/tests/_shared/contract_checker.js b/task_031/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_031/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_031/tests/_shared/static_enhancer.sh b/task_031/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_031/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_031/tests/enhancement_cases.json b/task_031/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..05592bbe202917660d6bb015ddf319303d1af399 --- /dev/null +++ b/task_031/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "递归遍历目录 `Audio_Speech_Actors_01-24`,读取所有 `.wav` 音频文件。", + "validator": "tests/validate_enhancements.py::case_1_recursive_discovery", + "behavior": "Adds a deterministic neutral wav in an extra nested directory and verifies only neutral_count increases, exercising recursive traversal and filename label parsing." + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "从 RAVDESS 语音情绪数据集(目录:`Audio_Speech_Actors_01-24`)中提取中性(neutral)和快乐(happy)两类语音的 MFCC 特征均值", + "validator": "tests/validate_enhancements.py::case_2_non_target_emotion_is_ignored", + "behavior": "Adds a valid wav whose filename has a different emotion code and verifies the complete neutral/happy result remains unchanged." + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "对每个符合条件的音频:计算 MFCC 在时间轴上的均值,得到一个 13 维向量", + "validator": "tests/validate_enhancements.py::case_3_audio_content_changes_features", + "behavior": "Adds a deterministic high-amplitude happy wav, verifies count adaptation, requires the 13-value difference vector to respond to sample content, and checks the one-based maximum dimension." + } +] diff --git a/task_031/tests/test.sh b/task_031/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fbc78c11fb9bdf9009e1631a221f952ae2c62b7 --- /dev/null +++ b/task_031/tests/test.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +set -euo pipefail +set +e +TASK_ID='47' +source "$(cd "$(dirname "$0")" && pwd)/_shared/static_enhancer.sh" +LOG_DIR="/logs/verifier" +if ! mkdir -p "$LOG_DIR" 2>/dev/null; then LOG_DIR="logs/verifier"; mkdir -p "$LOG_DIR"; fi +REWARD_FILE="$LOG_DIR/reward.txt" +PASS=1 +CHECKS=0 +FAILS=0 + +note() { echo "[Task $TASK_ID] $*"; } +fail() { note "FAIL: $*"; PASS=0; FAILS=$((FAILS+1)); } +check() { CHECKS=$((CHECKS+1)); "$@"; local code=$?; if [ $code -ne 0 ]; then fail "$*"; fi; } +have_any() { local pattern="$1"; compgen -G "$pattern" >/dev/null 2>&1; } +grep_any() { local pattern="$1"; shift; grep -REiq -- "$pattern" "$@" 2>/dev/null; } +source_files() { find . -type f \( -name '*.html' -o -name '*.js' -o -name '*.jsx' -o -name '*.ts' -o -name '*.tsx' -o -name '*.css' -o -name '*.py' -o -name '*.go' -o -name '*.swift' -o -name '*.svg' \) ! -path './tests/*' ! -path './logs/*'; } + +note "enhanced deterministic verifier start" +static_enhance_check "${TASK_ID}" "$(pwd)" +mapfile -t py_files < <(find . -type f -name '*.py' ! -path './tests/*') +if [ ${#py_files[@]} -eq 0 ]; then fail "no Python source found"; fi +if command -v python3 >/dev/null 2>&1; then + for f in "${py_files[@]}"; do python3 -m py_compile "$f" >/tmp/harbor_py_compile.log 2>&1 || fail "python compile failed: $f"; done +fi + +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +if command -v python3 >/dev/null 2>&1; then + check python3 "$TEST_DIR/validate_outputs.py" + check python3 "$TEST_DIR/validate_enhancements.py" +else + fail "python3 unavailable for output validation" +fi +# BEGIN AAAV_DYNAMIC_TEST +if [ -f "$TEST_DIR/validate_aaav_dynamic.js" ]; then + if command -v node >/dev/null 2>&1; then + check node "$TEST_DIR/validate_aaav_dynamic.js" + else + note "AAAV dynamic validation skipped (node unavailable in this runtime)" + fi +fi +# END AAAV_DYNAMIC_TEST +note "checks=$CHECKS fails=$FAILS" +if [ "$PASS" -eq 1 ]; then + echo 1 > "$REWARD_FILE" + note "PASS" + exit 0 +fi +echo 0 > "$REWARD_FILE" +note "FAIL" +exit 0 diff --git a/task_031/tests/validate_aaav_dynamic.js b/task_031/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..a871303003ee5f1f1db8224ac7363d9c75871d27 --- /dev/null +++ b/task_031/tests/validate_aaav_dynamic.js @@ -0,0 +1,67 @@ +const fs = require('fs'); +const path = require('path'); +const child_process = require('child_process'); +const TASK_ID = 47; +const LANGUAGE = "python"; +const EXPECTED = []; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { if (!condition) throw new Error(message); } +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} +function globToRe(glob) { + return new RegExp('^' + glob.split('*').map(x => x.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') + '$'); +} +function existsPattern(files, pat) { + const re = globToRe(String(pat).replace(/\\/g, '/')); + return files.some(f => re.test(f.replace(/\\/g, '/')) || f.replace(/\\/g, '/').endsWith(String(pat).replace(/\\/g, '/'))); +} + +const files = walk(process.cwd()); +assert(files.length > 0, 'candidate workspace should contain files'); +const rel = files.map(f => path.relative(process.cwd(), f)); +const source = files.filter(f => /\.(js|jsx|ts|tsx|css|html|py|go|md|svg)$/i.test(f)); +assert(source.length > 0, 'candidate should contain source or report files'); + +if (LANGUAGE === 'go') { + const goFiles = files.filter(f => f.endsWith('.go')); + assert(goFiles.length > 0, 'go task should contain .go files'); + try { + child_process.execFileSync('go', ['test', './...'], { cwd: process.cwd(), stdio: 'pipe', timeout: 120000 }); + } catch (err) { + // The benchmark's own verifier owns task-specific Go behavior. Here we + // keep go test as an opportunistic runtime probe so local module/path + // differences do not create false negatives. + const msg = Buffer.concat([err.stdout || Buffer.alloc(0), err.stderr || Buffer.alloc(0)]).toString().slice(0, 500); + console.warn('go test ./... probe failed but is non-fatal: ' + msg); + } +} else if (LANGUAGE === 'python') { + const pyFiles = files.filter(f => f.endsWith('.py')); + assert(pyFiles.length > 0 || rel.some(f => /\.(html|csv|json|txt|md|png)$/i.test(f)), 'python/data task should contain scripts or produced artifacts'); + for (const f of pyFiles.slice(0, 20)) { + child_process.execFileSync('python', ['-m', 'py_compile', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); + } +} else { + for (const f of files.filter(f => f.endsWith('.js')).slice(0, 20)) { + child_process.execFileSync('node', ['--check', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); + } +} + +for (const pat of EXPECTED) { + assert(existsPattern(rel, pat), 'missing expected artifact pattern after verifier: ' + pat); +} + +console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); diff --git a/task_031/tests/validate_enhancements.py b/task_031/tests/validate_enhancements.py new file mode 100644 index 0000000000000000000000000000000000000000..2882e45f7a5189d5c135f987c65c7dd9dc94c7d0 --- /dev/null +++ b/task_031/tests/validate_enhancements.py @@ -0,0 +1,181 @@ +import ast +import math +import pathlib +import shutil +import subprocess +import sys +import wave + + +root = pathlib.Path.cwd() +audio_root = root / "Audio_Speech_Actors_01-24" + + +def run_candidate(): + scripts = [root / 'analyze_ravdess.py'] + assert scripts, "missing candidate analysis script" + errors = [] + for script in scripts: + proc = subprocess.run( + [sys.executable, str(script)], cwd=root, capture_output=True, + text=True, timeout=30, + ) + if proc.returncode == 0 and "neutral_count:" in proc.stdout: + return parse_output(proc.stdout) + errors.append(f"{script.name}: rc={proc.returncode}: {proc.stderr[-200:]}") + raise AssertionError("candidate did not print the required output: " + " | ".join(errors)) + + +def parse_output(text: str): + lines = [line.strip() for line in text.splitlines() if line.strip()] + assert len(lines) == 4, f"expected exactly four lines, got {lines!r}" + assert [line.split(":", 1)[0] for line in lines] == [ + "neutral_count", "happy_count", "mfcc_diff", "max_diff_dim" + ], "output labels/order do not match the requested four-line contract" + neutral = int(lines[0].split(":", 1)[1]) + happy = int(lines[1].split(":", 1)[1]) + diff = ast.literal_eval(lines[2].split(":", 1)[1].strip()) + dim = int(lines[3].split(":", 1)[1]) + assert isinstance(diff, list) and len(diff) == 13, "mfcc_diff must contain 13 values" + assert all(isinstance(v, (int, float)) and math.isfinite(float(v)) and float(v) >= 0 for v in diff), ( + "mfcc_diff values must be finite non-negative numbers" + ) + assert 1 <= dim <= 13, "max_diff_dim must use one-based dimensions 1..13" + return neutral, happy, tuple(float(v) for v in diff), dim + + +def fixture(label: str) -> pathlib.Path: + matches = sorted(p for p in audio_root.rglob("*.wav") if p.name.split("-")[2] == label) + assert matches, f"missing fixture emotion code {label}" + return matches[0] + + +def case_1_recursive_discovery() -> None: + # ENHANCED_CASE_1: recursively nested neutral audio must be discovered and classified by filename. + baseline = run_candidate() + nested_dir = audio_root / "Actor_99" / "nested" + nested_dir.mkdir(parents=True, exist_ok=True) + added = nested_dir / "03-01-01-01-01-01-99.wav" + try: + shutil.copyfile(fixture("01"), added) + changed = run_candidate() + assert changed[0] == baseline[0] + 1, "nested neutral wav did not increase neutral_count" + assert changed[1] == baseline[1], "nested neutral wav must not change happy_count" + finally: + added.unlink(missing_ok=True) + + +def case_2_non_target_emotion_is_ignored() -> None: + # ENHANCED_CASE_2: a valid wav with an emotion other than 01/03 must not affect either aggregate. + baseline = run_candidate() + added = audio_root / "Actor_01" / "03-01-05-01-01-01-99.wav" + try: + shutil.copyfile(fixture("01"), added) + changed = run_candidate() + assert changed == baseline, "non-neutral/non-happy emotion code changed the requested output" + finally: + added.unlink(missing_ok=True) + + +def write_tone(path: pathlib.Path, half_period=10, sample_count=960) -> None: + rate = 8000 + frames = bytearray() + for index in range(sample_count): + value = 26000 if (index // half_period) % 2 == 0 else -26000 + frames.extend(int(value).to_bytes(2, "little", signed=True)) + with wave.open(str(path), "wb") as output: + output.setnchannels(1) + output.setsampwidth(2) + output.setframerate(rate) + output.writeframes(bytes(frames)) + + +def case_3_audio_content_changes_features() -> None: + # ENHANCED_CASE_3: feature differences must derive from wav samples, not only file counts/names. + baseline = run_candidate() + added = audio_root / "Actor_01" / "03-01-03-01-01-01-99.wav" + try: + write_tone(added) + changed = run_candidate() + assert changed[0] == baseline[0], "happy tone must not change neutral_count" + assert changed[1] == baseline[1] + 1, "happy tone did not increase happy_count" + assert changed[2] != baseline[2], "substantially different happy audio did not change mfcc_diff" + assert len(set(changed[2])) >= 3, "MFCC-style coefficients should not be copies of one scalar energy" + expected_dim = max(range(13), key=lambda index: changed[2][index]) + 1 + assert changed[3] == expected_dim, "max_diff_dim does not identify a maximum difference" + finally: + added.unlink(missing_ok=True) + + +def case_4_frequency_and_label_invariance(): + files = sorted(path for path in audio_root.rglob('*.wav') if path.stem.split('-')[2] in ('01', '03')) + originals = {path: path.read_bytes() for path in files} + try: + for path in files: + write_tone(path, 10 if path.stem.split('-')[2] == '01' else 4) + different = run_candidate() + assert any(value > 0 for value in different[2][1:]), 'equal-amplitude different spectra must produce nontrivial cepstral differences' + for path in files: + write_tone(path, 4 if path.stem.split('-')[2] == '01' else 10) + swapped = run_candidate() + assert swapped[2] == different[2], 'absolute class differences must be invariant to swapping both populations' + for path in files: + write_tone(path, 10) + identical = run_candidate() + assert all(value == 0 for value in identical[2]), 'identical per-file audio in both classes must have zero difference' + assert identical[3] == 1, 'all-zero tie selects the smallest dimension' + finally: + for path, data in originals.items(): + path.write_bytes(data) + + +def case_5_files_have_equal_weight(): + # Keep each waveform's exact bytes fixed across two runs. In the first, + # happy contains only A and neutral only B. Replacing one of the two + # neutral files with A must halve the gap between the class means, even + # though B has six times as many samples as A. + neutral = sorted(path for path in audio_root.rglob("*.wav") if path.stem.split("-")[2] == "01") + happy = sorted(path for path in audio_root.rglob("*.wav") if path.stem.split("-")[2] == "03") + assert len(neutral) == len(happy) == 2, "equal-weight control needs two files per class" + originals = {path: path.read_bytes() for path in neutral + happy} + try: + write_tone(happy[0], half_period=10) + short = happy[0].read_bytes() + happy[1].write_bytes(short) + write_tone(neutral[0], half_period=4, sample_count=5760) + neutral[1].write_bytes(neutral[0].read_bytes()) + separate = run_candidate() + + neutral[0].write_bytes(short) + mixed = run_candidate() + + # The displayed gaps round the unrounded values to three decimals. + # Comparing twice the mixture with the original permits three half + # units of rounding error, accounting for both reported quantities. + for index, (gap, half_gap) in enumerate(zip(separate[2], mixed[2]), 1): + assert math.isclose(gap, 2 * half_gap, rel_tol=0.0, abs_tol=0.001500001), ( + f"coefficient {index}: expected half of {gap:.3f}, got {half_gap:.3f}; " + "each WAV must have equal weight regardless of duration" + ) + finally: + for path, data in originals.items(): + path.write_bytes(data) + + +cases = [ + ("ENHANCED_CASE_1", case_1_recursive_discovery), + ("ENHANCED_CASE_2", case_2_non_target_emotion_is_ignored), + ("ENHANCED_CASE_3", case_3_audio_content_changes_features), + ("ENHANCED_CASE_4", case_4_frequency_and_label_invariance), + ("ENHANCED_CASE_5", case_5_files_have_equal_weight), +] +failed = [] +for case_id, validator in cases: + try: + validator() + print(f"{case_id}: PASS") + except Exception as exc: + failed.append(case_id) + print(f"{case_id}: FAIL: {exc}", file=sys.stderr) +if failed: + raise SystemExit(1) diff --git a/task_031/tests/validate_outputs.py b/task_031/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..2ef3c7bdf5c15a112dbf360f989dd008252f765c --- /dev/null +++ b/task_031/tests/validate_outputs.py @@ -0,0 +1,44 @@ +"""Check the public stdout format and label-preserving duplication.""" +import ast +import math +import pathlib +import re +import shutil +import subprocess +import sys +import tempfile + +root = pathlib.Path.cwd() +audio_root = root / 'Audio_Speech_Actors_01-24' + + +def run_candidate(): + result = subprocess.run([sys.executable, 'analyze_ravdess.py'], cwd=root, + check=True, capture_output=True, text=True, timeout=30) + lines = result.stdout.strip().splitlines() + assert len(lines) == 4, 'print exactly four requested lines' + assert re.fullmatch(r'neutral_count: \d+', lines[0]) + assert re.fullmatch(r'happy_count: \d+', lines[1]) + assert re.fullmatch(r'mfcc_diff: \[\d+\.\d{3}(?:,\s*\d+\.\d{3}){12}\]', lines[2]), '13 nonnegative three-decimal differences required' + assert re.fullmatch(r'max_diff_dim: \d+', lines[3]) + counts = tuple(int(line.split(': ')[1]) for line in lines[:2]) + values = ast.literal_eval(lines[2].split(': ', 1)[1]) + assert all(math.isfinite(value) for value in values) + dimension = int(lines[3].split(': ')[1]) + assert dimension == max(range(13), key=lambda index: values[index]) + 1 + return counts, values + + +files = sorted(audio_root.rglob('*.wav')) +expected = tuple(sum(file.stem.split('-')[2] == label for file in files) for label in ('01', '03')) +assert all(expected), 'fixture needs both target emotions' +counts, _ = run_candidate() +assert counts == expected, 'counts disagree with filename emotion fields' +# Preserve the original seven-field filename; adding a prefix would move the +# emotion field and test a different label than the intended copied sample. +source = next(file for file in files if file.stem.split('-')[2] == '01') +with tempfile.TemporaryDirectory(prefix='duplicate-', dir=audio_root) as directory: + shutil.copyfile(source, pathlib.Path(directory) / source.name) + changed, _ = run_candidate() + assert changed == (expected[0] + 1, expected[1]), 'recursive neutral duplication must only increment neutral_count' +print('Counts, formatting, argmax and label-preserving duplication passed') diff --git a/task_032/acceptance_checklist.json b/task_032/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..c354c7a6a0b6f839d631b50973f70b00f8b2322e --- /dev/null +++ b/task_032/acceptance_checklist.json @@ -0,0 +1,25 @@ +{ + "task_id": 48, + "category": "machine_learning", + "language": "python", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Python files compile; data-analysis tasks generate the requested output files from fixture data." + ], + "input_assets": [ + "general_ocr_002.ppm", + "expected_ocr.json", + "README.md" + ], + "expected_outputs": [ + "annotated_ocr.png", + "ocr_report.md", + "ocr_results.json" + ], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_032/environment/Dockerfile b/task_032/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b5c3125aadc8adae6187cdea0ad0c6d3cf3e505e --- /dev/null +++ b/task_032/environment/Dockerfile @@ -0,0 +1,7 @@ +FROM mcr.microsoft.com/playwright:v1.52.0-noble +USER root +RUN apt-get update && apt-get install -y --no-install-recommends python3-numpy python3-pil && ln -sf /usr/bin/python3 /usr/local/bin/python && rm -rf /var/lib/apt/lists/* +RUN npm install --global --prefix /usr playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules +WORKDIR /app +COPY ./code /app diff --git a/task_032/environment/code/README.md b/task_032/environment/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..927a6dc5080d1a25a09aa0c3edfe6356a6577cf4 --- /dev/null +++ b/task_032/environment/code/README.md @@ -0,0 +1 @@ +Closed OCR fixture. Use the local PPM image instead of fetching the external URL. Return OCR text and bounding boxes in ocr_results.json and save an annotated image. diff --git a/task_032/environment/code/expected_ocr.json b/task_032/environment/code/expected_ocr.json new file mode 100644 index 0000000000000000000000000000000000000000..481c5b14cfb26945eac6beccf77864882deab70b --- /dev/null +++ b/task_032/environment/code/expected_ocr.json @@ -0,0 +1,23 @@ +{ + "image": "general_ocr_002.ppm", + "texts": [ + { + "text": "OPENAI", + "bbox": [ + 8, + 8, + 32, + 12 + ] + }, + { + "text": "HARBOR", + "bbox": [ + 42, + 15, + 70, + 19 + ] + } + ] +} \ No newline at end of file diff --git a/task_032/environment/code/general_ocr_002.ppm b/task_032/environment/code/general_ocr_002.ppm new file mode 100644 index 0000000000000000000000000000000000000000..8231c330dbdfa4277ea344f88a1cf1e4bdcc5736 --- /dev/null +++ b/task_032/environment/code/general_ocr_002.ppm @@ -0,0 +1,4 @@ +P3 +80 24 +255 +245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 245 diff --git a/task_032/environment/docker-compose.yaml b/task_032/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_032/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_032/instruction.md b/task_032/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..87116768cc9af85a5241c60b8ebfeb4829d70925 --- /dev/null +++ b/task_032/instruction.md @@ -0,0 +1,16 @@ +# Validate and annotate local OCR results + +Use the supplied `general_ocr_002.ppm` and the upstream text-and-box metadata in `expected_ocr.json`. Run `python3 solve.py` in the project root. Work offline; text recognition itself is out of scope. + +## Validation and output + +- Decode the source image and validate the metadata before writing outputs. Each region must have nonempty text and finite in-bounds coordinates with positive area. For an invalid image or an invalid box, exit nonzero with a clear diagnostic and do not emit a successful annotation. +- Write `ocr_results.json` as a list of text-region objects, or an object containing the list under `texts`. Use `text` and `bbox` for each region. The box is a flat numeric array: `[x1, y1, x2, y2]` for a rectangle or `[x1, y1, x2, y2, x3, y3, x4, y4]` for four polygon vertices. Preserve each supplied text and its region with no omissions or invented or duplicate entries. Leading and trailing whitespace may be trimmed. +- Write `annotated_ocr.png` at the source dimensions. Draw a clearly visible four-sided rectangle around each region on the real image. Preserve source pixels outside the annotated boxes. +- Write `ocr_report.md` explaining the upstream metadata source, handled image formats, invalid or low-quality input handling, and local save behavior. + +## Acceptance Checklist + +- Valid results reproduce every supplied text-region association and the source dimensions. +- Annotations outline all four sides of each box and do not alter unrelated pixels. +- Invalid image data or invalid box coordinates cause a clear failure without a valid-looking saved image. The report describes what the program actually does. diff --git a/task_032/quality_notes.md b/task_032/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..569002e2a2f22166aad79b2875ae767eb3d71acf --- /dev/null +++ b/task_032/quality_notes.md @@ -0,0 +1,4 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. diff --git a/task_032/solution/README.md b/task_032/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_032/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_032/solution/code/solve.py b/task_032/solution/code/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..d040853451596db3ba3217959df734fa6ed418fd --- /dev/null +++ b/task_032/solution/code/solve.py @@ -0,0 +1,48 @@ +"""Validate the bundled OCR metadata and draw it over the actual PPM pixels.""" +import json +from pathlib import Path + +from PIL import Image, ImageDraw, UnidentifiedImageError + + +source_path = Path("general_ocr_002.ppm") +try: + with Image.open(source_path) as loaded: + loaded.verify() + with Image.open(source_path) as loaded: + image = loaded.convert("RGB") +except (OSError, UnidentifiedImageError) as exc: + raise SystemExit(f"invalid local source image: {exc}") + +width, height = image.size +expected = json.loads(Path("expected_ocr.json").read_text(encoding="utf-8")) +assert isinstance(expected.get("texts"), list), "OCR metadata lacks texts" +items = [] +for entry in expected["texts"]: + name = entry.get("text") + box = entry.get("bbox") + assert isinstance(name, str) and name.strip(), "OCR text must be nonempty" + assert isinstance(box, list) and len(box) == 4, "OCR bbox must be a rectangle" + x1, y1, x2, y2 = map(float, box) + assert 0 <= x1 < x2 <= width and 0 <= y1 < y2 <= height, "OCR bbox is outside the source image" + items.append({"text": name.strip(), "bbox": [x1, y1, x2, y2]}) + +Path("ocr_results.json").write_text(json.dumps({ + "image": source_path.name, "format": "PPM", "width": width, "height": height, + "texts": items, +}, ensure_ascii=False, indent=2), encoding="utf-8") + +draw = ImageDraw.Draw(image) +for item in items: + draw.rectangle(item["bbox"], outline=(255, 0, 0), width=1) +image.save("annotated_ocr.png", format="PNG") + +Path("ocr_report.md").write_text( + "# OCR metadata postprocessing report\n\n" + f"- Source: local `{source_path.name}`, valid PPM image, {width}×{height} pixels.\n" + "- Text and boxes come from the supplied upstream `expected_ocr.json`; this task does not rerun OCR.\n" + f"- Valid text regions: {len(items)}; each nonempty text and in-bounds rectangle was checked.\n" + "- The original image pixels were preserved while red box outlines were drawn; output saved locally as `annotated_ocr.png`.\n" + "- Invalid/low-quality or unreadable images should produce a clear error rather than invented text; this program validates the PPM and stops on decoding errors.\n", + encoding="utf-8", +) diff --git a/task_032/solution/solve.sh b/task_032/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_032/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_032/task.toml b/task_032/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_032/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_032/task_meta.json b/task_032/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..2cce4e9cd3bc49b1a63c044345f281918a2f46dd --- /dev/null +++ b/task_032/task_meta.json @@ -0,0 +1,27 @@ +{ + "task_id": 48, + "task_category": "ocr_metadata_postprocessing", + "difficulty_note": "Uses published upstream OCR text/box metadata; evaluates validation, postprocessing, and visible source-image annotation rather than recognition accuracy.", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 2, + "language": "python", + "tool_files_from_selected_trace": [ + "ocr_text_extractor.py", + "test_image_formats.py", + "test_image_processor.py" + ], + "input_assets": [ + "general_ocr_002.ppm", + "expected_ocr.json", + "README.md" + ], + "expected_outputs": [ + "annotated_ocr.png", + "ocr_report.md", + "ocr_results.json" + ], + "source_row_id": 288, + "repair_revision": "2026-09-29", + "instruction_sha256": "11e83fa9cd3163a3712564ea4feb3f4f9c6f5f05d12e73d0f10cbb668674715f" +} diff --git a/task_032/tests/_shared/contract_checker.js b/task_032/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_032/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_032/tests/_shared/static_enhancer.sh b/task_032/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_032/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_032/tests/enhancement_cases.json b/task_032/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..2b9f64f92cb55804a88e576ea8f9d54c9ad90ce0 --- /dev/null +++ b/task_032/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "识别出图中所有文字,并标注出来文字的具体位置", + "validator": "tests/validate_enhancements.py::case_1_text_and_positions_match_fixture", + "behavior": "Matches each expected text to its exact fixture bounding rectangle while accepting either rectangle or polygon result representation." + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "识别出图中所有文字,并标注出来文字的具体位置", + "validator": "tests/validate_enhancements.py::case_2_positions_fit_source_geometry", + "behavior": "Derives the bundled PPM dimensions and checks every recognized item has non-empty text plus a finite, positive-area rectangle or polygon fully inside the source image." + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "将标注结果保存到本地;确定性验证器", + "validator": "tests/validate_enhancements.py::case_3_saved_outputs_are_deterministic", + "behavior": "Checks the saved annotation has a PNG header and positive canvas dimensions, then reruns with proxies cleared and PYTHONHASHSEED fixed and requires all three saved artifacts to be byte-identical." + } +] diff --git a/task_032/tests/test.sh b/task_032/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ea2267eb5d8d9a5df57cef22cdec9c1a1ba400b1 --- /dev/null +++ b/task_032/tests/test.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +echo 0 > "$LOG_DIR/reward.txt" +rm -f -- annotated_ocr.png ocr_results.json ocr_report.md + +if timeout 60s python3 solve.py && + python3 "$TEST_DIR/validate_outputs.py" && + python3 "$TEST_DIR/validate_enhancements.py" && + node "$TEST_DIR/validate_aaav_dynamic.js"; then + echo 1 > "$LOG_DIR/reward.txt" +fi diff --git a/task_032/tests/validate_aaav_dynamic.js b/task_032/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..3b6bd7e8d3ea91f7395da8861978fb3b0f32b25a --- /dev/null +++ b/task_032/tests/validate_aaav_dynamic.js @@ -0,0 +1,71 @@ +const fs = require('fs'); +const path = require('path'); +const child_process = require('child_process'); +const TASK_ID = 48; +const LANGUAGE = "python"; +const EXPECTED = [ + "annotated_ocr.png", + "ocr_report.md", + "ocr_results.json" +]; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { if (!condition) throw new Error(message); } +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} +function globToRe(glob) { + return new RegExp('^' + glob.split('*').map(x => x.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') + '$'); +} +function existsPattern(files, pat) { + const re = globToRe(String(pat).replace(/\\/g, '/')); + return files.some(f => re.test(f.replace(/\\/g, '/')) || f.replace(/\\/g, '/').endsWith(String(pat).replace(/\\/g, '/'))); +} + +const files = walk(process.cwd()); +assert(files.length > 0, 'candidate workspace should contain files'); +const rel = files.map(f => path.relative(process.cwd(), f)); +const source = files.filter(f => /\.(js|jsx|ts|tsx|css|html|py|go|md|svg)$/i.test(f)); +assert(source.length > 0, 'candidate should contain source or report files'); + +if (LANGUAGE === 'go') { + const goFiles = files.filter(f => f.endsWith('.go')); + assert(goFiles.length > 0, 'go task should contain .go files'); + try { + child_process.execFileSync('go', ['test', './...'], { cwd: process.cwd(), stdio: 'pipe', timeout: 120000 }); + } catch (err) { + // The benchmark's own verifier owns task-specific Go behavior. Here we + // keep go test as an opportunistic runtime probe so local module/path + // differences do not create false negatives. + const msg = Buffer.concat([err.stdout || Buffer.alloc(0), err.stderr || Buffer.alloc(0)]).toString().slice(0, 500); + console.warn('go test ./... probe failed but is non-fatal: ' + msg); + } +} else if (LANGUAGE === 'python') { + const pyFiles = files.filter(f => f.endsWith('.py')); + assert(pyFiles.length > 0 || rel.some(f => /\.(html|csv|json|txt|md|png)$/i.test(f)), 'python/data task should contain scripts or produced artifacts'); + for (const f of pyFiles.slice(0, 20)) { + child_process.execFileSync('python', ['-m', 'py_compile', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); + } +} else { + for (const f of files.filter(f => f.endsWith('.js')).slice(0, 20)) { + child_process.execFileSync('node', ['--check', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); + } +} + +for (const pat of EXPECTED) { + assert(existsPattern(rel, pat), 'missing expected artifact pattern after verifier: ' + pat); +} + +console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); diff --git a/task_032/tests/validate_enhancements.py b/task_032/tests/validate_enhancements.py new file mode 100644 index 0000000000000000000000000000000000000000..0ffd86d2ba1900131e34e2799b1b1d64016e1700 --- /dev/null +++ b/task_032/tests/validate_enhancements.py @@ -0,0 +1,207 @@ +import json +import math +import os +import pathlib +import struct +import subprocess +import sys +import shutil +import tempfile +from collections import defaultdict +from PIL import Image + + +root = pathlib.Path.cwd() +ARTIFACTS = ("ocr_results.json", "annotated_ocr.png", "ocr_report.md") + + +def clean_environment(): + env = os.environ.copy() + for name in ( + "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", + "http_proxy", "https_proxy", "all_proxy", "no_proxy", + ): + env.pop(name, None) + env["PYTHONHASHSEED"] = "0" + return env + + +def run_candidate(work): + for name in ARTIFACTS: + (work / name).unlink(missing_ok=True) + result = subprocess.run([sys.executable, "solve.py"], cwd=work, capture_output=True, + text=True, timeout=60, env=clean_environment()) + assert result.returncode == 0, f"candidate failed to annotate valid OCR metadata: {result.stderr}" + for name in ARTIFACTS: + assert (work / name).is_file(), f"candidate did not generate {name}" + + +def result_items(root): + result = json.loads((root / "ocr_results.json").read_text(encoding="utf-8")) + if isinstance(result, list): + return result + for key in ("texts", "results", "ocr_texts", "ocr_results", "items"): + if isinstance(result.get(key), list): + return result[key] + raise AssertionError("ocr_results.json has no recognized-text list") + + +def item_text(item): + return item.get("text", item.get("content", item.get("label"))) + + +def rectangle(item): + box = item.get("bbox", item.get("box")) + assert isinstance(box, list) and len(box) in (4, 8), "each OCR item needs a rectangle or polygon" + values = [float(value) for value in box] + if len(values) == 4: + return tuple(values) + return min(values[0::2]), min(values[1::2]), max(values[0::2]), max(values[1::2]) + + +def png_size(path: pathlib.Path): + data = path.read_bytes() + assert data[:8] == b"\x89PNG\r\n\x1a\n", "annotated_ocr.png is not PNG data" + assert len(data) >= 24 and data[12:16] == b"IHDR", "annotated PNG is missing IHDR" + return struct.unpack(">II", data[16:24]) + + +def ppm_size(path: pathlib.Path): + with path.open("rb") as handle: + magic = handle.readline().strip() + assert magic in (b"P3", b"P6"), "source fixture is not a supported PPM image" + tokens = [] + while len(tokens) < 2: + line = handle.readline() + assert line, "source PPM is missing dimensions" + line = line.split(b"#", 1)[0] + tokens.extend(line.split()) + return int(tokens[0]), int(tokens[1]) + + +def check_metadata(root) -> None: + # ENHANCED_CASE_2: every recognized region is non-empty and lies on the supplied image. + width, height = ppm_size(root / "general_ocr_002.ppm") + for index, item in enumerate(result_items(root)): + text = item_text(item) + assert isinstance(text, str) and text.strip(), f"OCR item {index} has empty text" + x1, y1, x2, y2 = rectangle(item) + assert all(math.isfinite(value) for value in (x1, y1, x2, y2)), ( + f"OCR item {index} has a non-finite position" + ) + assert 0 <= x1 < x2 <= width and 0 <= y1 < y2 <= height, ( + f"OCR item {index} position {(x1, y1, x2, y2)} is outside {width}x{height} source" + ) + expected = json.loads((root / "expected_ocr.json").read_text(encoding="utf-8"))["texts"] + actual = defaultdict(list) + by_text = defaultdict(list) + for item in result_items(root): + actual[item_text(item).strip()].append(rectangle(item)) + for item in expected: + by_text[item["text"].strip()].append(rectangle(item)) + assert actual.keys() == by_text.keys(), "OCR output changed the set of recognized strings" + for text, boxes in by_text.items(): + assert len(boxes) == len(actual[text]), f"wrong region count for {text!r}" + for want, got in zip(sorted(boxes), sorted(actual[text])): + assert all(abs(a - b) <= 1 for a, b in zip(want, got)), ( + f"box moved away from upstream OCR position for {text!r}" + ) + + +def check_png_dimensions(root) -> None: + # ENHANCED_CASE_3: annotation is a concrete PNG artifact matching source dimensions. + width, height = png_size(root / "annotated_ocr.png") + assert (width, height) == ppm_size(root / "general_ocr_002.ppm"), "annotated PNG geometry differs from source" + + +def check_annotation_pixels(root) -> None: + # White-canvas substitution and no-op annotations must both fail. + with Image.open(root / "general_ocr_002.ppm") as source_image: + source = source_image.convert("RGB") + with Image.open(root / "annotated_ocr.png") as annotation_image: + annotated = annotation_image.convert("RGB") + boxes = [rectangle(item) for item in result_items(root)] + assert source.size == annotated.size + changed_per_box = [0] * len(boxes) + for y in range(source.height): + for x in range(source.width): + before = source.getpixel((x, y)) + after = annotated.getpixel((x, y)) + relevant = [index for index, (x1, y1, x2, y2) in enumerate(boxes) + if x1 - 1 <= x <= x2 + 1 and y1 - 1 <= y <= y2 + 1] + if not relevant: + assert before == after, f"original pixel changed outside annotations at {(x, y)}" + elif before != after: + for index in relevant: + changed_per_box[index] += 1 + assert all(count > 0 for count in changed_per_box), "at least one OCR box was not drawn" + for box in boxes: + x1, y1, x2, y2 = map(round, box) + sides = [ + [(x, y1) for x in range(x1, min(x2 + 1, source.width))], + [(x, min(y2, source.height - 1)) for x in range(x1, min(x2 + 1, source.width))], + [(x1, y) for y in range(y1, min(y2 + 1, source.height))], + [(min(x2, source.width - 1), y) for y in range(y1, min(y2 + 1, source.height))], + ] + for side in sides: + covered = sum(any(source.getpixel((nx, ny)) != annotated.getpixel((nx, ny)) + for nx in range(max(0, x - 1), min(source.width, x + 2)) + for ny in range(max(0, y - 1), min(source.height, y + 2))) + for x, y in side) + assert covered >= len(side) * 0.8, 'each annotation must visibly outline all four box sides, not just change one pixel' + + +def work_copy(parent): + work = pathlib.Path(parent) / "candidate" + shutil.copytree(root, work, ignore=shutil.ignore_patterns( + "tests", "logs", "node_modules", "__pycache__", *ARTIFACTS)) + return work + + +def check_invalid_inputs(): + for invalid_image in (True, False): + with tempfile.TemporaryDirectory(prefix="ocr-invalid-") as directory: + work = work_copy(directory) + if invalid_image: + (work / "general_ocr_002.ppm").write_bytes(b"not an image") + else: + meta = work / "expected_ocr.json" + metadata = json.loads(meta.read_text()) + metadata["texts"][0]["bbox"] = [-10, 0, 10, 10] + meta.write_text(json.dumps(metadata)) + result = subprocess.run([sys.executable, "solve.py"], cwd=work, capture_output=True, + text=True, timeout=30, env=clean_environment()) + assert result.returncode != 0 and (result.stdout + result.stderr).strip(), ( + "invalid input must fail with a diagnostic" + ) + assert not (work / "annotated_ocr.png").exists(), ( + "invalid input must not be presented as a successful annotation" + ) + + +def check_changed_input(): + with tempfile.TemporaryDirectory(prefix="ocr-valid-") as directory: + work = work_copy(directory) + meta = work / "expected_ocr.json" + metadata = json.loads(meta.read_text()) + # Duplicate text in distinct regions is legal. Move one box while + # preserving its positive area and keep both region associations. + first, second = metadata["texts"][:2] + first["text"] = second["text"] + first["bbox"] = [value + 2 for value in first["bbox"]] + metadata["texts"].reverse() + meta.write_text(json.dumps(metadata)) + run_candidate(work) + assert json.loads(meta.read_text()) == metadata, "annotation must preserve upstream metadata" + check_metadata(work) + check_png_dimensions(work) + check_annotation_pixels(work) + + +if __name__ == "__main__": + check_metadata(root) + check_png_dimensions(root) + check_annotation_pixels(root) + check_changed_input() + check_invalid_inputs() + print("OCR associations, changed input, four-sided annotations and failure paths passed") diff --git a/task_032/tests/validate_outputs.py b/task_032/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..17395e29317dc61dd2beb74b3bce19a81ac9ad3e --- /dev/null +++ b/task_032/tests/validate_outputs.py @@ -0,0 +1,36 @@ +import json +import pathlib +from PIL import Image +root = pathlib.Path.cwd() +with Image.open(root / 'general_ocr_002.ppm') as source_image: + image_width, image_height = source_image.size +for name in ['general_ocr_002.ppm', 'expected_ocr.json', 'ocr_results.json', 'annotated_ocr.png', 'ocr_report.md']: + assert (root / name).exists() and (root / name).stat().st_size > 0, f'missing {name}' +expected = json.loads((root / 'expected_ocr.json').read_text(encoding='utf-8')) +result = json.loads((root / 'ocr_results.json').read_text(encoding='utf-8')) +if isinstance(result, list): + items = result +else: + items = (result.get('texts') or result.get('results') or result.get('ocr_texts') + or result.get('ocr_results') or result.get('items') or result) +assert isinstance(items, list) and items, 'ocr_results.json should contain a non-empty text list' +text_blob = json.dumps(items, ensure_ascii=False).lower() +for item in expected['texts']: + assert item['text'].lower() in text_blob, f"missing OCR text {item['text']}" +for item in items: + assert isinstance(item, dict), 'each OCR result should be an object with text and bbox' + assert 'text' in item or 'content' in item or 'label' in item, 'each OCR result should include recognized text' + assert 'bbox' in item or 'box' in item, 'each OCR result should include bbox/box' + box = item.get('bbox') or item.get('box') + assert isinstance(box, list) and len(box) in {4, 8}, 'bbox should be a 4-number rectangle or 8-number polygon' + assert all(isinstance(v, (int, float)) for v in box), 'bbox values should be numeric' + assert all(0 <= float(v) <= image_width for v in box[0::2]), 'bbox x coordinates should be within image width' + assert all(0 <= float(v) <= image_height for v in box[1::2]), 'bbox y coordinates should be within image height' + if len(box) == 4: + assert float(box[0]) < float(box[2]) and float(box[1]) < float(box[3]), 'bbox rectangle should have positive area' +report = (root / 'ocr_report.md').read_text(encoding='utf-8', errors='ignore').lower() +for group in [['ocr', 'paddleocr', 'easyocr', 'tesseract'], ['format', 'ppm', 'png', 'jpg', '格式'], ['invalid', 'exception', 'error', '无效', '错误', '异常'], ['save', 'local', 'annotated', '保存', '本地', '标注']]: + assert any(token in report for token in group), 'ocr report missing requirement group: ' + '|'.join(group) +# The instruction itself provides the image URL, so embedding it as a string while +# reading the local fixture is fine. Forbid ACTUAL fetching (network calls) instead +# of the bare 'https://' substring. diff --git a/task_033/acceptance_checklist.json b/task_033/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..7540ae8245ab073e9ab87721c0637a2bb0f4b440 --- /dev/null +++ b/task_033/acceptance_checklist.json @@ -0,0 +1,23 @@ +{ + "task_id": 49, + "category": "machine_learning", + "language": "python", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Python files compile; data-analysis tasks generate the requested output files from fixture data." + ], + "input_assets": [ + "train-images-idx3-ubyte", + "train-labels-idx1-ubyte" + ], + "expected_outputs": [ + "mnist_samples.png", + "report.html" + ], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_033/environment/Dockerfile b/task_033/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b5c3125aadc8adae6187cdea0ad0c6d3cf3e505e --- /dev/null +++ b/task_033/environment/Dockerfile @@ -0,0 +1,7 @@ +FROM mcr.microsoft.com/playwright:v1.52.0-noble +USER root +RUN apt-get update && apt-get install -y --no-install-recommends python3-numpy python3-pil && ln -sf /usr/bin/python3 /usr/local/bin/python && rm -rf /var/lib/apt/lists/* +RUN npm install --global --prefix /usr playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules +WORKDIR /app +COPY ./code /app diff --git a/task_033/environment/code/README.md b/task_033/environment/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d5cc273b7af7a2f27ae08aa4bbe1316f6b87b26c --- /dev/null +++ b/task_033/environment/code/README.md @@ -0,0 +1 @@ +Tiny closed MNIST-style IDX fixture: 10 synthetic 8x8 images with labels 0/1. Use this local fixture only; do not download MNIST. diff --git a/task_033/environment/code/train-images-idx3-ubyte b/task_033/environment/code/train-images-idx3-ubyte new file mode 100644 index 0000000000000000000000000000000000000000..90bcc1acaf3c4a8dcf14d60994fcc3e4c5cf25c0 Binary files /dev/null and b/task_033/environment/code/train-images-idx3-ubyte differ diff --git a/task_033/environment/code/train-labels-idx1-ubyte b/task_033/environment/code/train-labels-idx1-ubyte new file mode 100644 index 0000000000000000000000000000000000000000..37a5472e659a07be505c0270a6b9e7847e6e85c5 Binary files /dev/null and b/task_033/environment/code/train-labels-idx1-ubyte differ diff --git a/task_033/environment/docker-compose.yaml b/task_033/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_033/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_033/instruction.md b/task_033/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f05c3d8ea6a91e4b8ca372005b018ad7b60a9ba2 --- /dev/null +++ b/task_033/instruction.md @@ -0,0 +1,20 @@ +# MNIST training and source-image montage + +Build an offline Python classifier using the provided tiny IDX files `train-images-idx3-ubyte` and `train-labels-idx1-ubyte`. Run `python3 solve.py` from the project root. Load the matched 8×8 grayscale samples and labels; do not download MNIST. + +## Model and validation + +Shuffle original sample indices with `random.Random(1).shuffle(indices)` and use the first 80% for training and the remaining 20% for validation in shuffled order. Divide model input pixels by 255. Train a genuine cross-entropy MLP with 64 inputs, a 16-unit ReLU hidden layer, and two linear logits; update weights by backpropagation. Epoch count and optimizer are unrestricted. Do not substitute fixed predictions or a non-MLP classifier. No minimum score is required. + +- `model.json`: finite numeric arrays `w1` (16×64), `b1` (16), `w2` (2×16) and `b2` (2). Predict from `argmax(w2*ReLU(w1*x+b1)+b2)`, choosing 0 on a tie. +- `predictions.csv`: exact header `index,true_label,predicted_label`. Include only the validation indices in shuffled order with their IDX labels and predicted classes. + +## Visualization and report + +Save `mnist_samples.png` as a 40×8, 8-bit grayscale PNG: place the first five raw 8×8 images left to right, keeping their original byte values. Do not normalize or augment the display pixels. In `report.html`, display `` at proportional dimensions of at least 200×40 CSS pixels. Describe the dataset, normalization and network structure; show the 80/20 split and the labeled counts “Train: 8” and “Validation: 2”. Report the accuracy from the CSV as `Validation accuracy: `, not a percentage. + +## Acceptance Checklist + +- Learned parameters and predictions are generated from the current IDX input. The validation order and labels match the split, and the saved model reproduces each prediction. +- The montage preserves every raw pixel and displays legibly at the specified scale. +- Described split, transforms, network and accuracy agree with the generated artifacts. Changed training labels and image pixels yield corresponding model and montage changes. diff --git a/task_033/quality_notes.md b/task_033/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..7145281b77bf9767e1ab4682985dc196b30d1e8f --- /dev/null +++ b/task_033/quality_notes.md @@ -0,0 +1,5 @@ +# Quality notes — Task 49 + +- This task uses a tiny synthetic IDX fixture and overlaps Task 45 in topic. Treat their scores as correlated until multi-model evaluation is requested. +- The revision publishes MLP weights and validation predictions, and fixes the sample image format to a verifiable 40×8 grayscale montage. +- `tests/validate_contract.py` decodes PNG pixels, independently runs the saved network, checks report accuracy, and reruns after training-label and source-pixel mutations. diff --git a/task_033/solution/README.md b/task_033/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_033/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_033/solution/code/solve.py b/task_033/solution/code/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..ddff6b948091715bdb39eb85224ce64b09d81f56 --- /dev/null +++ b/task_033/solution/code/solve.py @@ -0,0 +1,27 @@ +import csv, json, math, random, struct, zlib +with open('train-images-idx3-ubyte','rb') as f: magic,n,rows,cols=struct.unpack('>IIII',f.read(16)); raw=f.read() +with open('train-labels-idx1-ubyte','rb') as f: lmagic,ln=struct.unpack('>II',f.read(8)); labels=list(f.read()) +assert magic==2051 and lmagic==2049 and n==ln +images=[list(raw[i*rows*cols:(i+1)*rows*cols]) for i in range(n)]; x=[[p/255 for p in im] for im in images] +order=list(range(n));random.Random(1).shuffle(order);train=order[:int(.8*n)];valid=order[int(.8*n):] +r=random.Random(7);h=16;k=max(labels)+1;w1=[[r.uniform(-.08,.08) for _ in range(h)] for _ in range(rows*cols)];b1=[0.]*h;w2=[[r.uniform(-.08,.08) for _ in range(k)] for _ in range(h)];b2=[0.]*k +def forward(v): + a=[max(0,b1[j]+sum(v[i]*w1[i][j] for i in range(len(v)))) for j in range(h)];q=[b2[c]+sum(a[j]*w2[j][c] for j in range(h)) for c in range(k)];m=max(q);e=[math.exp(t-m) for t in q];s=sum(e);return a,[t/s for t in e] +for _ in range(240): + for z in train: + a,p=forward(x[z]);dz=[p[c]-(c==labels[z]) for c in range(k)];da=[sum(w2[j][c]*dz[c] for c in range(k))*(a[j]>0) for j in range(h)] + for j in range(h): + for c in range(k):w2[j][c]-=.12*a[j]*dz[c] + for c in range(k):b2[c]-=.12*dz[c] + for i in range(rows*cols): + for j in range(h):w1[i][j]-=.12*x[z][i]*da[j] + for j in range(h):b1[j]-=.12*da[j] +def acc(ids):return sum(max(range(k),key=lambda c:forward(x[i])[1][c])==labels[i] for i in ids)/len(ids) +model={'w1':[[w1[i][j] for i in range(rows*cols)] for j in range(h)],'b1':b1,'w2':[[w2[j][c] for j in range(h)] for c in range(k)],'b2':b2} +open('model.json','w',encoding='utf8').write(json.dumps(model,allow_nan=False)) +with open('predictions.csv','w',newline='',encoding='utf8') as f: + writer=csv.writer(f);writer.writerow(['index','true_label','predicted_label']) + for i in valid:writer.writerow([i,labels[i],max(range(k),key=lambda c:forward(x[i])[1][c])]) +def chunk(t,d):return struct.pack('>I',len(d))+t+d+struct.pack('>I',zlib.crc32(t+d)&0xffffffff) +shown=images[:min(5,n)];width=cols*len(shown);scan=b''.join(b'\0'+b''.join(bytes(im[y*cols:(y+1)*cols]) for im in shown) for y in range(rows));png=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',width,rows,8,0,0,0,0))+chunk(b'IDAT',zlib.compress(scan))+chunk(b'IEND',b'');open('mnist_samples.png','wb').write(png) +open('report.html','w',encoding='utf8').write(f'

      MNIST MLP training report

      Seeded 80/20 train/validation split ({len(train)}/{len(valid)}); transform normalizes pixels to [0,1].

      Network {rows*cols}-{h}-{k} MLP, ReLU and softmax, trained 240 epochs. train accuracy={acc(train):.3f}; validation accuracy={acc(valid):.3f}.

      source MNIST samples') diff --git a/task_033/solution/solve.sh b/task_033/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_033/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_033/task.toml b/task_033/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_033/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_033/task_meta.json b/task_033/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..33009474e27b486d2e9acb3fc50315767faf89ca --- /dev/null +++ b/task_033/task_meta.json @@ -0,0 +1,27 @@ +{ + "task_id": 49, + "task_category": "machine_learning", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 5, + "language": "python", + "tool_files_from_selected_trace": [ + "mlp_network_structure.py", + "mnist_classification.py", + "simple_mnist.py", + "transforms_basic.py", + "transforms_example.py", + "transforms_simple.py" + ], + "input_assets": [ + "train-images-idx3-ubyte", + "train-labels-idx1-ubyte" + ], + "expected_outputs": [ + "mnist_samples.png", + "report.html" + ], + "source_row_id": 294, + "repair_revision": "2026-09-29", + "instruction_sha256": "1b9a718c33267d359c2eed9577b47e7ac1a8573f04d7e622f20c5c046df04798" +} diff --git a/task_033/tests/_offline/sitecustomize.py b/task_033/tests/_offline/sitecustomize.py new file mode 100644 index 0000000000000000000000000000000000000000..b56d40ca3ecdf6893c56d99c2ab48a45580aa593 --- /dev/null +++ b/task_033/tests/_offline/sitecustomize.py @@ -0,0 +1,14 @@ +"""Deterministic, network-disabled Python test runtime.""" +import random +import socket + +random.seed(0) + + +def _blocked(*_args, **_kwargs): + raise RuntimeError("network access is disabled by the verifier") + + +socket.create_connection = _blocked +socket.socket.connect = _blocked +socket.socket.connect_ex = _blocked diff --git a/task_033/tests/_shared/contract_checker.js b/task_033/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_033/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_033/tests/_shared/static_enhancer.sh b/task_033/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_033/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_033/tests/enhancement_cases.json b/task_033/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..1ac75a125c9ea0e7ce3bac55a586f7494732b85f --- /dev/null +++ b/task_033/tests/enhancement_cases.json @@ -0,0 +1,26 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "加载MNIST数据集并进行简单展示", + "validator": "tests/validate_enhanced.py::case_1_generates_png_sample_display", + "behavior": "在全新隔离副本中运行候选程序,确认它生成非空、具有 PNG 签名且 IHDR 尺寸为正数的 mnist_samples.png。" + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "将数据划分为 80% train / 20% validation,定义简单 transform pipeline(如 normalization,可选 horizontal flip)", + "validator": "tests/validate_enhanced.py::case_2_report_explains_split_and_transforms", + "behavior": "在独立运行产生的 HTML 可见文本中验证 80/20 划分和 transform 说明,同时接受中英文表述。" + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "定义简单 MLP/network,保存样例可视化为 `mnist_samples.png`,并写 `report.html` 说明划分、transforms 和 network。", + "validator": "tests/validate_enhanced.py::case_3_report_identifies_mnist_network", + "behavior": "在另一次独立运行产生的 report.html 可见文本中验证 MNIST 以及 MLP/network 分类网络说明。" + }, + { + "case_id": "CONTRACT_AND_MUTATION", + "instruction_evidence": "model.json、predictions.csv 与前五张原始输入拼接的 40×8 灰度 PNG;输入变化后重跑。", + "validator": "tests/validate_contract.py", + "behavior": "独立解码 PNG、计算模型前向与准确率,并变更训练标签和输入像素以排除固定产物。" + } +] diff --git a/task_033/tests/test.sh b/task_033/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..377fd40ee889be96c3239680dd3bc551edfcef07 --- /dev/null +++ b/task_033/tests/test.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +set -euo pipefail +set +e +TASK_ID='49' +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +source "$TEST_DIR/_shared/static_enhancer.sh" +OFFLINE_PYTHONPATH="$TEST_DIR/_offline${PYTHONPATH:+:$PYTHONPATH}" +RUN_ENV=(env PYTHONHASHSEED=0 PYTHONPATH="$OFFLINE_PYTHONPATH" HF_DATASETS_OFFLINE=1 TRANSFORMERS_OFFLINE=1 WANDB_MODE=offline NO_PROXY='' HTTP_PROXY='http://127.0.0.1:9' HTTPS_PROXY='http://127.0.0.1:9' ALL_PROXY='http://127.0.0.1:9') +LOG_DIR="/logs/verifier" +if ! mkdir -p "$LOG_DIR" 2>/dev/null; then LOG_DIR="logs/verifier"; mkdir -p "$LOG_DIR"; fi +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +if [ ! -f solve.py ]; then + echo "solve.py entrypoint missing" + exit 0 +fi +PASS=1 +CHECKS=0 +FAILS=0 + +note() { echo "[Task $TASK_ID] $*"; } +fail() { note "FAIL: $*"; PASS=0; FAILS=$((FAILS+1)); } +check() { CHECKS=$((CHECKS+1)); "$@"; local code=$?; if [ $code -ne 0 ]; then fail "$*"; fi; } +have_any() { local pattern="$1"; compgen -G "$pattern" >/dev/null 2>&1; } +grep_any() { local pattern="$1"; shift; grep -REiq -- "$pattern" "$@" 2>/dev/null; } +source_files() { find . -type f \( -name '*.html' -o -name '*.js' -o -name '*.jsx' -o -name '*.ts' -o -name '*.tsx' -o -name '*.css' -o -name '*.py' -o -name '*.go' -o -name '*.swift' -o -name '*.svg' \) ! -path './tests/*' ! -path './logs/*'; } + +note "enhanced deterministic verifier start" +static_enhance_check "${TASK_ID}" "$(pwd)" +mapfile -t py_files < <(find . -type f -name '*.py' ! -path './tests/*') +if [ ${#py_files[@]} -eq 0 ]; then fail "no Python source found"; fi +if command -v python3 >/dev/null 2>&1; then + for f in "${py_files[@]}"; do timeout 30s "${RUN_ENV[@]}" python3 -m py_compile "$f" >/tmp/harbor_py_compile.log 2>&1 || fail "python compile failed: $f"; done +fi +if command -v python3 >/dev/null 2>&1 && [ -f solve.py ]; then + timeout 60s "${RUN_ENV[@]}" python3 solve.py >/tmp/harbor_data_run.log 2>&1 || fail "data script did not run successfully" +else + fail "solve.py entrypoint missing" +fi +check test -s 'mnist_samples.png' +check test -s 'report.html' + +if command -v python3 >/dev/null 2>&1; then + check timeout 180s "${RUN_ENV[@]}" python3 "$TEST_DIR/validate_outputs.py" + check timeout 180s "${RUN_ENV[@]}" python3 "$TEST_DIR/validate_enhanced.py" + check timeout 180s "${RUN_ENV[@]}" python3 "$TEST_DIR/validate_contract.py" +else + fail "python3 unavailable for output validation" +fi +# BEGIN AAAV_DYNAMIC_TEST +if [ -f "$TEST_DIR/validate_aaav_dynamic.js" ]; then + if command -v node >/dev/null 2>&1; then + GLOBAL_NODE_PATH="${NODE_PATH:-$(npm root -g 2>/dev/null)}" + check timeout 90s "${RUN_ENV[@]}" env NODE_PATH="$GLOBAL_NODE_PATH" node "$TEST_DIR/validate_aaav_dynamic.js" + else + fail "node is required for browser validation" + fi +fi +# END AAAV_DYNAMIC_TEST +note "checks=$CHECKS fails=$FAILS" +if [ "$PASS" -eq 1 ]; then + echo 1 > "$REWARD_FILE" + note "PASS" + exit 0 +fi +echo 0 > "$REWARD_FILE" +note "FAIL" +exit 0 diff --git a/task_033/tests/validate_aaav_dynamic.js b/task_033/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..aed0f93784296e928bfa820a3cf5ace7beeb5bc6 --- /dev/null +++ b/task_033/tests/validate_aaav_dynamic.js @@ -0,0 +1,28 @@ +const fs = require('fs'); +const path = require('path'); +const {pathToFileURL} = require('url'); +const {chromium} = require('playwright'); + +(async () => { + const browser = await chromium.launch({headless: true}); + try { + const page = await browser.newPage({viewport: {width: 1100, height: 760}}); + const errors = []; + page.on('pageerror', error => errors.push(error.message)); + await page.goto(pathToFileURL(path.resolve('report.html')).href, {waitUntil: 'load'}); + const displayed = await page.locator('img[src="mnist_samples.png"]').evaluateAll(images => images.some(image => { + const box = image.getBoundingClientRect(); + for (let node = image; node; node = node.parentElement) { + const style = getComputedStyle(node); + if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) return false; + } + return image.complete && image.naturalWidth === 40 && image.naturalHeight === 8 && box.width >= 200 && box.height >= 40 && Math.abs(box.width / box.height - 5) < 0.01; + })); + if (!displayed) throw new Error('source montage must actually load and be visible in the report'); + if (errors.length) throw new Error(errors.join(' | ')); + fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + await page.screenshot({path: '/logs/verifier/visual-audit/mnist-report.png', fullPage: true}); + } finally { + await browser.close(); + } +})().catch(error => {console.error(error); process.exit(1);}); diff --git a/task_033/tests/validate_contract.py b/task_033/tests/validate_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..66c483c319dc6dace9edbbf6da4a18bf8a1b5a79 --- /dev/null +++ b/task_033/tests/validate_contract.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""Check the sample PNG pixels and serialized MLP predictions independently.""" + +import csv +import json +import math +import random +import re +import shutil +import struct +import subprocess +import sys +import tempfile +from html import unescape +from PIL import Image +from pathlib import Path + + +def idx(root): + raw = (root / "train-images-idx3-ubyte").read_bytes() + label_raw = (root / "train-labels-idx1-ubyte").read_bytes() + magic, count, rows, cols = struct.unpack_from(">IIII", raw) + label_magic, label_count = struct.unpack_from(">II", label_raw) + assert (magic, label_magic, count, label_count, rows, cols) == (2051, 2049, 10, 10, 8, 8) + assert len(raw) == 16 + count * 64 and len(label_raw) == 8 + count + return [list(raw[16 + i * 64:16 + (i + 1) * 64]) for i in range(count)], list(label_raw[8:]) + + +def read_png(path): + with Image.open(path) as image: + assert image.format == 'PNG' and image.mode == 'L' and image.size == (40, 8), 'expected a 40x8 8-bit grayscale PNG' + image.load() + return [[image.getpixel((x, y)) for x in range(40)] for y in range(8)] + + +def finite_vector(value, length): + assert isinstance(value, list) and len(value) == length + assert all(type(v) in (int, float) and math.isfinite(v) for v in value) + + +def logits(model, pixels): + x = [value / 255 for value in pixels] + hidden = [max(0.0, sum(w * v for w, v in zip(row, x)) + bias) + for row, bias in zip(model["w1"], model["b1"])] + return [sum(w * v for w, v in zip(row, hidden)) + bias + for row, bias in zip(model["w2"], model["b2"])] + + +def model_predict(model, pixels): + scores = logits(model, pixels) + return int(scores[1] > scores[0]) + + +def check(root): + images, labels = idx(root) + rows = read_png(root / "mnist_samples.png") + for y in range(8): + assert rows[y] == [value for image in images[:5] for value in image[y * 8:(y + 1) * 8]], ( + "sample PNG pixels differ from source IDX images" + ) + model = json.loads((root / "model.json").read_text(encoding="utf-8")) + assert {"w1", "b1", "w2", "b2"} <= set(model) + assert len(model["w1"]) == 16 and len(model["w2"]) == 2 + for row in model["w1"]: + finite_vector(row, 64) + for row in model["w2"]: + finite_vector(row, 16) + finite_vector(model["b1"], 16) + finite_vector(model["b2"], 2) + assert any(abs(v) > 1e-9 for row in model["w1"] for v in row) + assert any(abs(v) > 1e-9 for row in model["w2"] for v in row) + order = list(range(10)) + random.Random(1).shuffle(order) + validation = order[8:] + with (root / "predictions.csv").open(newline="", encoding="utf-8") as handle: + reader = csv.DictReader(handle) + assert reader.fieldnames == ["index", "true_label", "predicted_label"] + predictions = list(reader) + assert len(predictions) == 2 + for row, sample in zip(predictions, validation): + assert int(row["index"]) == sample and int(row["true_label"]) == labels[sample] + assert int(row["predicted_label"]) == model_predict(model, images[sample]) + accuracy = sum(int(row["true_label"]) == int(row["predicted_label"]) for row in predictions) / 2 + report = (root / "report.html").read_text(encoding="utf-8") + assert re.search(r']+src=["\']mnist_samples\.png["\']', report, re.I) + text = unescape(re.sub(r'<[^>]+>', ' ', report)) + assert re.search(r"80\s*/\s*20|80\s*%[^;]*20\s*%", text) + assert re.search(r"\b8\s*/\s*2\b|(?:train|训练)(?:\s*(?:samples|样本数?))?\s*[:=:]\s*8.*(?:validation|验证)(?:\s*(?:samples|样本数?))?\s*[:=:]\s*2", text, re.I | re.S) + assert re.search(r"MLP|network|网络", text, re.I) + match = re.search(r"(?:validation\s+accuracy|验证准确率)\s*[:=:]\s*(0(?:\.\d+)?|1(?:\.0+)?)", text, re.I) + assert match and abs(float(match.group(1)) - accuracy) <= 5e-4, "report accuracy mismatch" + return model, rows + + +def functional_change(before, after, examples): + # Compare logit differences from the actual forward pass. Training may + # change confidence even if the predicted classes all remain the same. + for example in examples: + original = logits(before, example) + updated = logits(after, example) + if not math.isclose(original[1] - original[0], updated[1] - updated[0], + rel_tol=0, abs_tol=1e-12): + return True + return False + + +def mutation(root, baseline_model, baseline_png): + with tempfile.TemporaryDirectory(prefix="task49-mutated-") as tmp: + work = Path(tmp) / "candidate" + shutil.copytree(root, work, ignore=shutil.ignore_patterns("tests", "logs", "__pycache__", "*.pyc")) + order = list(range(10)) + random.Random(1).shuffle(order) + labels_path = work / "train-labels-idx1-ubyte" + label_bytes = bytearray(labels_path.read_bytes()) + image_path = work / "train-images-idx3-ubyte" + image_bytes = bytearray(image_path.read_bytes()) + # Change a validation image that appears in the montage. The training + # inputs remain identical while the label response is measured. + offset = 16 + order[8] * 64 + image_bytes[offset] = 255 - image_bytes[offset] + image_path.write_bytes(image_bytes) + originals, _ = idx(root) + for affected in (order[:1], order[:8]): + updated_label_bytes = bytearray(label_bytes) + for index in affected: + updated_label_bytes[8 + index] = 1 - updated_label_bytes[8 + index] + labels_path.write_bytes(updated_label_bytes) + for name in ("model.json", "predictions.csv", "mnist_samples.png", "report.html"): + (work / name).unlink(missing_ok=True) + result = subprocess.run([sys.executable, "solve.py"], cwd=work, capture_output=True, + text=True, timeout=45) + assert result.returncode == 0, f"candidate failed changed input: {result.stderr}" + updated_model, updated_png = check(work) + assert updated_png != baseline_png, "sample PNG did not respond to changed input pixel" + if functional_change(baseline_model, updated_model, originals): + return + raise AssertionError("training-label changes affected no model logit differences") + +if __name__ == "__main__": + root = Path.cwd() + model, png = check(root) + mutation(root, model, png) + print("MLP, PNG and changed-input checks passed") diff --git a/task_033/tests/validate_enhanced.py b/task_033/tests/validate_enhanced.py new file mode 100644 index 0000000000000000000000000000000000000000..bb89caa0c96e5f678555ea524185d6e08dd1e6f6 --- /dev/null +++ b/task_033/tests/validate_enhanced.py @@ -0,0 +1,141 @@ +import contextlib +import os +import pathlib +import shutil +import struct +import subprocess +import sys +import tempfile +from html.parser import HTMLParser + +ROOT = pathlib.Path.cwd() +SKIP_PARTS = {"tests", "logs", "__pycache__", ".git", "node_modules"} + + +class _TextOnly(HTMLParser): + def __init__(self): + super().__init__() + self.parts = [] + + def handle_data(self, data): + self.parts.append(data) + + +def _copy_candidate(destination: pathlib.Path) -> None: + for source in ROOT.iterdir(): + if source.name in SKIP_PARTS: + continue + target = destination / source.name + if source.is_dir(): + shutil.copytree(source, target, ignore=shutil.ignore_patterns(*SKIP_PARTS)) + else: + shutil.copy2(source, target) + + +def _offline_env(workspace: pathlib.Path): + guard = workspace / ".test_guard" + guard.mkdir(exist_ok=True) + (guard / "sitecustomize.py").write_text( + "import random, socket\n" + "random.seed(0)\n" + "def blocked(*args, **kwargs):\n" + " raise RuntimeError('network disabled by deterministic validator')\n" + "socket.create_connection = blocked\n" + "socket.socket.connect = blocked\n" + "socket.socket.connect_ex = blocked\n", + encoding="utf-8", + ) + env = os.environ.copy() + env.update({ + "PYTHONHASHSEED": "0", + "PYTHONPATH": str(guard), + "HF_DATASETS_OFFLINE": "1", + "TRANSFORMERS_OFFLINE": "1", + "WANDB_MODE": "offline", + }) + return env + + +def _run_candidate(workspace: pathlib.Path) -> None: + scripts = [workspace / 'solve.py'] + assert scripts, "missing candidate Python source" + failures = [] + for script in scripts: + for output in ("mnist_samples.png", "report.html"): + (workspace / output).unlink(missing_ok=True) + proc = subprocess.run( + [sys.executable, str(script)], + cwd=workspace, + env=_offline_env(workspace), + capture_output=True, + text=True, + timeout=60, + ) + if proc.returncode == 0 and all((workspace / p).is_file() for p in ("mnist_samples.png", "report.html")): + return + failures.append(f"{script.name}: rc={proc.returncode} stderr={proc.stderr[-500:]}") + raise AssertionError("no candidate script generated both outputs: " + " | ".join(failures)) + + +@contextlib.contextmanager +def _generated_workspace(): + with tempfile.TemporaryDirectory(prefix="task049-enhanced-") as tmp: + workspace = pathlib.Path(tmp) + _copy_candidate(workspace) + _run_candidate(workspace) + yield workspace + + +def _visible_report_text(workspace: pathlib.Path) -> str: + report = workspace / "report.html" + assert report.is_file() and report.stat().st_size > 0, "missing report.html" + parser = _TextOnly() + parser.feed(report.read_text(encoding="utf-8", errors="ignore")) + return " ".join(parser.parts).lower() + + +# ENHANCED_CASE_1: running the candidate must create the requested PNG MNIST sample display. +def case_1_generates_png_sample_display() -> None: + with _generated_workspace() as workspace: + path = workspace / "mnist_samples.png" + assert path.is_file() and path.stat().st_size > 0, "missing mnist_samples.png" + payload = path.read_bytes() + assert payload.startswith(b"\x89PNG\r\n\x1a\n"), "mnist_samples.png lacks the PNG signature" + assert len(payload) >= 24 and payload[12:16] == b"IHDR", "mnist_samples.png lacks an IHDR chunk" + width, height = struct.unpack(">II", payload[16:24]) + image_header = (workspace / "train-images-idx3-ubyte").read_bytes()[:16] + _, _, rows, cols = struct.unpack(">IIII", image_header) + assert width >= cols and height >= rows, "sample display is smaller than one source image" + + +# ENHANCED_CASE_2: the report must explain the explicitly required split and transforms. +def case_2_report_explains_split_and_transforms() -> None: + with _generated_workspace() as workspace: + text = _visible_report_text(workspace) + assert "80" in text and "20" in text, "report does not explain the 80%/20% split" + transform_terms = ("transform", "normalize", "normalization", "flip", "变换", "归一化", "翻转") + assert any(word in text for word in transform_terms), "report omits transforms" + + +# ENHANCED_CASE_3: the report must identify the requested MNIST classification network. +def case_3_report_identifies_mnist_network() -> None: + with _generated_workspace() as workspace: + text = _visible_report_text(workspace) + assert "mnist" in text, "report does not identify the MNIST dataset" + assert any(word in text for word in ("mlp", "network", "neural", "网络")), "report omits the MLP/network" + + +failures = [] +for case in ( + case_1_generates_png_sample_display, + case_2_report_explains_split_and_transforms, + case_3_report_identifies_mnist_network, +): + try: + case() + print(f"{case.__name__}: PASS") + except Exception as error: + failures.append(f"{case.__name__}: {error}") + print(f"{case.__name__}: FAIL: {error}") +if failures: + raise AssertionError("enhanced cases failed:\n" + "\n".join(failures)) diff --git a/task_033/tests/validate_outputs.py b/task_033/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..a5d26b53777602cbe77d4a5c4426327205a4960a --- /dev/null +++ b/task_033/tests/validate_outputs.py @@ -0,0 +1,68 @@ +import pathlib +import struct +import subprocess +import sys + +root = pathlib.Path.cwd() + + +def _py_sources(): + _skip = {"tests", "logs", "output", "__pycache__", "node_modules", ".git"} + return [ + p + for p in root.rglob("*.py") + if p.is_file() + and not (set(p.relative_to(root).parts) & _skip) + and p.name != "validate_outputs.py" + ] + + +def run_candidate() -> None: + scripts = [root / 'solve.py'] + assert scripts, "missing candidate python source (e.g. solve.py)" + failures = [] + for script in scripts[:2]: + proc = subprocess.run( + [sys.executable, str(script)], + cwd=root, + capture_output=True, + text=True, + timeout=60, + ) + if proc.returncode == 0: + return + failures.append((script.name, proc.returncode, proc.stdout, proc.stderr)) + raise AssertionError( + "candidate script(s) failed to execute:\n" + + "\n".join( + f"{name}: rc={rc}\nstdout={out}\nstderr={err}" for name, rc, out, err in failures + ) + ) + + +def validate_outputs() -> None: + report_path = root / "report.html" + sample_path = root / "mnist_samples.png" + for p in (report_path, sample_path): + assert p.exists() and p.stat().st_size > 0, f"missing {p.name}" + + img_path = root / "train-images-idx3-ubyte" + label_path = root / "train-labels-idx1-ubyte" + magic, count, rows, cols = struct.unpack(">IIII", img_path.read_bytes()[:16]) + lmagic, lcount = struct.unpack(">II", label_path.read_bytes()[:8]) + assert (magic, count, rows, cols) == (2051, 10, 8, 8), "unexpected tiny MNIST header" + assert (lmagic, lcount) == (2049, 10), "unexpected tiny label header" + assert count == lcount == 10, "image count and label count should match" + + report = report_path.read_text(encoding="utf-8", errors="ignore").lower() + assert "mnist" in report, "report missing mnist" + assert "mlp" in report or "network" in report, "report missing mlp/network" + assert "80" in report and "20" in report, "report should mention 80/20 split" + assert any(word in report for word in ('transform', 'normalize', 'flip', '变换', '归一化')), "report missing transform discussion" + assert any(word in report for word in ('layer', 'hidden', 'network', '隐层', '网络')), "report missing network structure discussion" + + +run_candidate() +validate_outputs() + +print("validate_outputs OK: task_049 checks the packaged IDX fixture and MNIST task outputs") diff --git a/task_034/acceptance_checklist.json b/task_034/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..19a6406e3c8facf37155dc9243ac3c6da8169a7d --- /dev/null +++ b/task_034/acceptance_checklist.json @@ -0,0 +1,23 @@ +{ + "task_id": 50, + "category": "machine_learning", + "language": "python", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Python files compile; data-analysis tasks generate the requested output files from fixture data." + ], + "input_assets": [ + "input.ppm" + ], + "expected_outputs": [ + "transform_report.txt", + "transformed_image.png" + ], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns.", + "Input assets are separated from candidate outputs; do not score candidates merely for recreating input files." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_034/environment/Dockerfile b/task_034/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b5c3125aadc8adae6187cdea0ad0c6d3cf3e505e --- /dev/null +++ b/task_034/environment/Dockerfile @@ -0,0 +1,7 @@ +FROM mcr.microsoft.com/playwright:v1.52.0-noble +USER root +RUN apt-get update && apt-get install -y --no-install-recommends python3-numpy python3-pil && ln -sf /usr/bin/python3 /usr/local/bin/python && rm -rf /var/lib/apt/lists/* +RUN npm install --global --prefix /usr playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules +WORKDIR /app +COPY ./code /app diff --git a/task_034/environment/code/input.ppm b/task_034/environment/code/input.ppm new file mode 100644 index 0000000000000000000000000000000000000000..844df99f5413b1e0759eada9644e04eca0888583 --- /dev/null +++ b/task_034/environment/code/input.ppm @@ -0,0 +1,11 @@ +P3 +8 8 +255 +255 0 0 255 0 0 0 255 0 0 255 0 0 0 255 0 0 255 0 255 255 255 255 255 +255 0 0 255 0 0 0 255 0 0 255 0 0 0 255 0 0 255 0 255 255 255 255 255 +0 255 0 0 255 0 255 255 0 255 255 0 0 0 255 0 0 255 255 0 255 255 0 255 +0 255 0 0 255 0 255 255 0 255 255 0 0 0 255 0 0 255 255 0 255 255 0 255 +0 0 255 0 0 255 255 0 255 255 0 255 255 255 0 255 255 0 0 255 255 0 255 255 +0 0 255 0 0 255 255 0 255 255 0 255 255 255 0 255 255 0 0 255 255 0 255 255 +255 255 255 255 255 255 128 128 128 128 128 128 64 64 64 64 64 64 0 0 0 0 0 0 +255 255 255 255 255 255 128 128 128 128 128 128 64 64 64 64 64 64 0 0 0 0 0 0 diff --git a/task_034/environment/docker-compose.yaml b/task_034/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_034/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_034/instruction.md b/task_034/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..49423b630bc0990ace36ece06b8054e2295e5919 --- /dev/null +++ b/task_034/instruction.md @@ -0,0 +1,19 @@ +# Deterministic image transformation pipeline + +Write `solve.py` to transform the local RGB image in `input.ppm`, run as `python3 solve.py` in the project root. Work offline using the supplied Python, NumPy and Pillow as needed; do not require installing Albumentations. + +## Pipeline + +For any valid RGB input at least 4×4, apply these operations in order: + +1. Crop a centered 4×4 region starting at `((width-4)//2, (height-4)//2)`. +2. Flip the crop horizontally. +3. Blur each channel with a 3×3 mean kernel, replicating edge pixels for padding. Round each channel to an integer. +4. Compute grayscale as `0.299R + 0.587G + 0.114B` and round to the nearest integer. Equivalent rounding may differ by at most three gray levels. + +Save `transformed_image.png` as a 4×4 grayscale PNG or RGB PNG with equal channels. In `transform_report.txt`, describe all four operations in Chinese or English. + +## Acceptance Checklist + +- Running the script produces a valid 4×4 grayscale transformation and a report describing the actual sequence. +- Pixel values follow the specified crop, flip, edge-replicated blur and grayscale, including for inputs with different dimensions, colors and asymmetric patterns. diff --git a/task_034/quality_notes.md b/task_034/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..2ef6090b0119048acd6aef0e3e8f39d848014b73 --- /dev/null +++ b/task_034/quality_notes.md @@ -0,0 +1,4 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. +- Input assets are separated from candidate outputs; do not score candidates merely for recreating input files. \ No newline at end of file diff --git a/task_034/solution/README.md b/task_034/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_034/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_034/solution/code/solve.py b/task_034/solution/code/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..5dc95238de05a40c3e4c6d0e925be9a04baf9257 --- /dev/null +++ b/task_034/solution/code/solve.py @@ -0,0 +1,21 @@ +# albumentations CenterCrop HorizontalFlip Blur ToGray equivalent pipeline +from PIL import Image +import numpy as np + +def box_blur_3x3(img): + padded = np.pad(img.astype(np.float32), ((1, 1), (1, 1), (0, 0)), mode='edge') + out = np.zeros_like(img, dtype=np.float32) + for y in range(img.shape[0]): + for x in range(img.shape[1]): + out[y, x] = padded[y:y+3, x:x+3].mean(axis=(0, 1)) + return np.rint(out).astype(np.uint8) + +src = np.array(Image.open('input.ppm').convert('RGB')) +top, left = (src.shape[0] - 4) // 2, (src.shape[1] - 4) // 2 +crop = src[top:top+4, left:left+4, :] +flipped = crop[:, ::-1, :] +blurred = box_blur_3x3(flipped) +gray = np.rint(0.299 * blurred[:, :, 0] + 0.587 * blurred[:, :, 1] + 0.114 * blurred[:, :, 2]).astype(np.uint8) +expected = np.repeat(gray[:, :, None], 3, axis=2) +Image.fromarray(expected).save('transformed_image.png') +open('transform_report.txt', 'w', encoding='utf-8').write('CenterCrop HorizontalFlip Blur ToGray gray pipeline applied with albumentations-compatible semantics.\n') diff --git a/task_034/solution/solve.sh b/task_034/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_034/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_034/task.toml b/task_034/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_034/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_034/task_meta.json b/task_034/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..0290e21e5dce810db0d32a4630cabd7168c1f799 --- /dev/null +++ b/task_034/task_meta.json @@ -0,0 +1,24 @@ +{ + "task_id": 50, + "task_category": "machine_learning", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 2, + "language": "python", + "tool_files_from_selected_trace": [ + "README.md", + "flip.py", + "image_transform_example.py", + "transforms.py" + ], + "input_assets": [ + "input.ppm" + ], + "expected_outputs": [ + "transform_report.txt", + "transformed_image.png" + ], + "source_row_id": 300, + "repair_revision": "2026-09-29", + "instruction_sha256": "b4084f25049b12381ce0e65076a6615d819946bff86d851cedf5c92a7872e786" +} diff --git a/task_034/tests/_offline/sitecustomize.py b/task_034/tests/_offline/sitecustomize.py new file mode 100644 index 0000000000000000000000000000000000000000..b56d40ca3ecdf6893c56d99c2ab48a45580aa593 --- /dev/null +++ b/task_034/tests/_offline/sitecustomize.py @@ -0,0 +1,14 @@ +"""Deterministic, network-disabled Python test runtime.""" +import random +import socket + +random.seed(0) + + +def _blocked(*_args, **_kwargs): + raise RuntimeError("network access is disabled by the verifier") + + +socket.create_connection = _blocked +socket.socket.connect = _blocked +socket.socket.connect_ex = _blocked diff --git a/task_034/tests/_shared/contract_checker.js b/task_034/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_034/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_034/tests/_shared/static_enhancer.sh b/task_034/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_034/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_034/tests/enhancement_cases.json b/task_034/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..260ce3befa791ea7d27230371d1b8fe32839bc0d --- /dev/null +++ b/task_034/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "CenterCrop(height=4, width=4)", + "validator": "tests/validate_enhanced.py::case_1_center_crop_dimensions", + "behavior": "解码 transformed_image.png 并验证中心裁剪规定的 4×4 输出尺寸。" + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "`ToGray(p=1.0)` 或等价 grayscale transform", + "validator": "tests/validate_enhanced.py::case_2_grayscale_output", + "behavior": "验证输出 RGB 三通道逐像素相等,且图像不是单色占位结果。" + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "HorizontalFlip(p=1.0)", + "validator": "tests/validate_enhanced.py::case_3_horizontal_flip_on_asymmetric_input", + "behavior": "在隔离副本中使用中心列从左到右严格增大的合法 8×8 灰度输入重跑程序,验证 p=1 水平翻转后输出的水平强度方向反转,不限定模糊边界模式或灰度算法。" + } +] diff --git a/task_034/tests/test.sh b/task_034/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e1f46797c6b1adb3dad5c2f46a9da9abe8fa9965 --- /dev/null +++ b/task_034/tests/test.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +set -euo pipefail +set +e +TASK_ID='50' +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +source "$TEST_DIR/_shared/static_enhancer.sh" +OFFLINE_PYTHONPATH="$TEST_DIR/_offline${PYTHONPATH:+:$PYTHONPATH}" +RUN_ENV=(env PYTHONHASHSEED=0 PYTHONPATH="$OFFLINE_PYTHONPATH" HF_DATASETS_OFFLINE=1 TRANSFORMERS_OFFLINE=1 WANDB_MODE=offline NO_PROXY='' HTTP_PROXY='http://127.0.0.1:9' HTTPS_PROXY='http://127.0.0.1:9' ALL_PROXY='http://127.0.0.1:9') +LOG_DIR="/logs/verifier" +if ! mkdir -p "$LOG_DIR" 2>/dev/null; then LOG_DIR="logs/verifier"; mkdir -p "$LOG_DIR"; fi +REWARD_FILE="$LOG_DIR/reward.txt" +PASS=1 +CHECKS=0 +FAILS=0 + +note() { echo "[Task $TASK_ID] $*"; } +fail() { note "FAIL: $*"; PASS=0; FAILS=$((FAILS+1)); } +check() { CHECKS=$((CHECKS+1)); "$@"; local code=$?; if [ $code -ne 0 ]; then fail "$*"; fi; } +have_any() { local pattern="$1"; compgen -G "$pattern" >/dev/null 2>&1; } +grep_any() { local pattern="$1"; shift; grep -REiq -- "$pattern" "$@" 2>/dev/null; } +source_files() { find . -type f \( -name '*.html' -o -name '*.js' -o -name '*.jsx' -o -name '*.ts' -o -name '*.tsx' -o -name '*.css' -o -name '*.py' -o -name '*.go' -o -name '*.swift' -o -name '*.svg' \) ! -path './tests/*' ! -path './logs/*'; } + +note "enhanced deterministic verifier start" +static_enhance_check "${TASK_ID}" "$(pwd)" +if [ ! -e 'input.ppm' ]; then + fail "benchmark input asset missing: input.ppm" +fi +mapfile -t py_files < <(find . -type f -name '*.py' ! -path './tests/*') +if [ ${#py_files[@]} -eq 0 ]; then fail "no Python source found"; fi +if command -v python3 >/dev/null 2>&1; then + for f in "${py_files[@]}"; do timeout 30s "${RUN_ENV[@]}" python3 -m py_compile "$f" >/tmp/harbor_py_compile.log 2>&1 || fail "python compile failed: $f"; done +fi +if command -v python3 >/dev/null 2>&1 && [ ${#py_files[@]} -gt 0 ]; then + timeout 60s "${RUN_ENV[@]}" python3 solve.py >/tmp/harbor_data_run.log 2>&1 || fail "data script did not run successfully" +fi +check test -s 'transform_report.txt' +check test -s 'transformed_image.png' + +if command -v python3 >/dev/null 2>&1; then + check timeout 180s "${RUN_ENV[@]}" python3 "$TEST_DIR/validate_outputs.py" + check timeout 180s "${RUN_ENV[@]}" python3 "$TEST_DIR/validate_enhanced.py" +else + fail "python3 unavailable for output validation" +fi +# BEGIN AAAV_DYNAMIC_TEST +if [ -f "$TEST_DIR/validate_aaav_dynamic.js" ]; then + if command -v node >/dev/null 2>&1; then + check timeout 90s "${RUN_ENV[@]}" node "$TEST_DIR/validate_aaav_dynamic.js" + else + note "AAAV dynamic validation skipped (node unavailable in this runtime)" + fi +fi +# END AAAV_DYNAMIC_TEST +note "checks=$CHECKS fails=$FAILS" +if [ "$PASS" -eq 1 ]; then + echo 1 > "$REWARD_FILE" + note "PASS" + exit 0 +fi +echo 0 > "$REWARD_FILE" +note "FAIL" +exit 0 diff --git a/task_034/tests/validate_aaav_dynamic.js b/task_034/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..c7f44dd59df0a59180930bb511bae795653e55ec --- /dev/null +++ b/task_034/tests/validate_aaav_dynamic.js @@ -0,0 +1,70 @@ +const fs = require('fs'); +const path = require('path'); +const child_process = require('child_process'); +const TASK_ID = 50; +const LANGUAGE = "python"; +const EXPECTED = [ + "transform_report.txt", + "transformed_image.png" +]; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { if (!condition) throw new Error(message); } +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} +function globToRe(glob) { + return new RegExp('^' + glob.split('*').map(x => x.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') + '$'); +} +function existsPattern(files, pat) { + const re = globToRe(String(pat).replace(/\\/g, '/')); + return files.some(f => re.test(f.replace(/\\/g, '/')) || f.replace(/\\/g, '/').endsWith(String(pat).replace(/\\/g, '/'))); +} + +const files = walk(process.cwd()); +assert(files.length > 0, 'candidate workspace should contain files'); +const rel = files.map(f => path.relative(process.cwd(), f)); +const source = files.filter(f => /\.(js|jsx|ts|tsx|css|html|py|go|md|svg)$/i.test(f)); +assert(source.length > 0, 'candidate should contain source or report files'); + +if (LANGUAGE === 'go') { + const goFiles = files.filter(f => f.endsWith('.go')); + assert(goFiles.length > 0, 'go task should contain .go files'); + try { + child_process.execFileSync('go', ['test', './...'], { cwd: process.cwd(), stdio: 'pipe', timeout: 120000 }); + } catch (err) { + // The benchmark's own verifier owns task-specific Go behavior. Here we + // keep go test as an opportunistic runtime probe so local module/path + // differences do not create false negatives. + const msg = Buffer.concat([err.stdout || Buffer.alloc(0), err.stderr || Buffer.alloc(0)]).toString().slice(0, 500); + console.warn('go test ./... probe failed but is non-fatal: ' + msg); + } +} else if (LANGUAGE === 'python') { + const pyFiles = files.filter(f => f.endsWith('.py')); + assert(pyFiles.length > 0 || rel.some(f => /\.(html|csv|json|txt|md|png)$/i.test(f)), 'python/data task should contain scripts or produced artifacts'); + for (const f of pyFiles.slice(0, 20)) { + child_process.execFileSync('python3', ['-m', 'py_compile', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); + } +} else { + for (const f of files.filter(f => f.endsWith('.js')).slice(0, 20)) { + child_process.execFileSync('node', ['--check', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); + } +} + +for (const pat of EXPECTED) { + assert(existsPattern(rel, pat), 'missing expected artifact pattern after verifier: ' + pat); +} + +console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); diff --git a/task_034/tests/validate_enhanced.py b/task_034/tests/validate_enhanced.py new file mode 100644 index 0000000000000000000000000000000000000000..24c10d5e6290199ffb58d3cae8b81025b6aa1658 --- /dev/null +++ b/task_034/tests/validate_enhanced.py @@ -0,0 +1,133 @@ +import os +import pathlib +import shutil +import subprocess +import sys +import tempfile + +import numpy as np +from PIL import Image + + +ROOT = pathlib.Path.cwd() +SKIP_PARTS = {"tests", "logs", "__pycache__", ".git", "node_modules"} + + +def _copy_candidate(destination): + for source in ROOT.iterdir(): + if source.name in SKIP_PARTS: + continue + target = destination / source.name + if source.is_dir(): + shutil.copytree(source, target, ignore=shutil.ignore_patterns(*SKIP_PARTS)) + else: + shutil.copy2(source, target) + + +def _offline_env(workspace): + guard = workspace / ".test_guard" + guard.mkdir(exist_ok=True) + (guard / "sitecustomize.py").write_text( + "import random, socket\n" + "random.seed(0)\n" + "def blocked(*args, **kwargs): raise RuntimeError('network disabled by validator')\n" + "socket.create_connection = blocked\n" + "socket.socket.connect = blocked\n" + "socket.socket.connect_ex = blocked\n", + encoding="utf-8", + ) + env = os.environ.copy() + env.update({"PYTHONHASHSEED": "0", "PYTHONPATH": str(guard), "HF_DATASETS_OFFLINE": "1", "TRANSFORMERS_OFFLINE": "1"}) + return env + + +def _run_candidate(workspace): + scripts = [workspace / 'solve.py'] + assert scripts, "missing candidate Python source" + failures = [] + for script in scripts: + (workspace / "transformed_image.png").unlink(missing_ok=True) + (workspace / "transform_report.txt").unlink(missing_ok=True) + proc = subprocess.run( + [sys.executable, str(script)], cwd=workspace, env=_offline_env(workspace), + capture_output=True, text=True, timeout=60, + ) + if proc.returncode == 0 and (workspace / "transformed_image.png").is_file(): + return + failures.append(f"{script.name}: rc={proc.returncode} stderr={proc.stderr[-500:]}") + raise AssertionError("no candidate script produced transformed_image.png: " + " | ".join(failures)) + + +# ENHANCED_CASE_1: CenterCrop(height=4, width=4) fixes the observable output size. +def case_1_center_crop_dimensions() -> None: + with Image.open(ROOT / "transformed_image.png") as image: + image.verify() + with Image.open(ROOT / "transformed_image.png") as image: + assert image.size == (4, 4), f"CenterCrop output must be 4x4, got {image.size}" + + +# ENHANCED_CASE_2: ToGray must make every RGB channel equal while preserving image data. +def case_2_grayscale_output() -> None: + with Image.open(ROOT / "transformed_image.png") as image: + pixels = np.array(image.convert("RGB")) + assert np.array_equal(pixels[:, :, 0], pixels[:, :, 1]), "red and green channels differ after grayscale" + assert np.array_equal(pixels[:, :, 1], pixels[:, :, 2]), "green and blue channels differ after grayscale" + assert np.unique(pixels[:, :, 0]).size > 1, "transformed output is a uniform placeholder" + + +# ENHANCED_CASE_3: an asymmetric legal input must be observably flipped without fixing blur internals. +def case_3_horizontal_flip_on_asymmetric_input() -> None: + with tempfile.TemporaryDirectory(prefix="task050-enhanced-") as tmp: + workspace = pathlib.Path(tmp) + _copy_candidate(workspace) + # The four center columns increase sharply left-to-right. Every normal + # 3x3 blur preserves that direction, so the required p=1 flip reverses + # it without tying the test to an OpenCV border mode or gray formula. + columns = np.array([250, 250, 20, 60, 120, 200, 0, 0], dtype=np.uint8) + source = np.repeat(columns[None, :, None], 8, axis=0) + source = np.repeat(source, 3, axis=2) + Image.fromarray(source, "RGB").save(workspace / "input.ppm") + _run_candidate(workspace) + with Image.open(workspace / "transformed_image.png") as image: + actual = np.array(image.convert("RGB")) + assert actual.shape == (4, 4, 3), f"variant output has wrong shape: {actual.shape}" + profile = actual[:, :, 0].astype(np.float64).mean(axis=0) + assert np.all(np.diff(profile) <= 0), f"output does not have the flipped right-to-left profile: {profile.tolist()}" + assert profile[0] - profile[-1] >= 40, f"flip signal was lost or output is a placeholder: {profile.tolist()}" + + +def case_4_changed_geometry_and_color(): + with tempfile.TemporaryDirectory(prefix='task050-geometry-') as directory: + workspace = pathlib.Path(directory) + _copy_candidate(workspace) + source = np.fromfunction(lambda y, x, c: (37*y + 53*x + 79*c + 11*x*y) % 256, (9, 11, 3), dtype=int).astype(np.uint8) + Image.fromarray(source, 'RGB').save(workspace / 'input.ppm') + _run_candidate(workspace) + top, left = (source.shape[0] - 4) // 2, (source.shape[1] - 4) // 2 + crop = source[top:top+4, left:left+4][:, ::-1].astype(float) + expected = np.zeros((4, 4)) + for y in range(4): + for x in range(4): + samples = [crop[min(3, max(0, y+dy)), min(3, max(0, x+dx))] + for dy in (-1, 0, 1) for dx in (-1, 0, 1)] + rgb = np.rint(np.mean(samples, axis=0)) + expected[y, x] = np.rint(np.dot(rgb, [0.299, 0.587, 0.114])) + with Image.open(workspace / 'transformed_image.png') as image: + actual = np.array(image.convert('RGB')).astype(float) + assert actual.shape == (4, 4, 3) + assert np.max(np.abs(actual - expected[:, :, None])) <= 3, 'changed-size/color input must follow the full crop, flip, blur and grayscale pipeline' + + +failures = [] +for case in (case_1_center_crop_dimensions, case_2_grayscale_output, case_3_horizontal_flip_on_asymmetric_input, case_4_changed_geometry_and_color): + try: + case() + print(f"{case.__name__}: PASS") + except Exception as error: + failures.append(f"{case.__name__}: {error}") + print(f"{case.__name__}: FAIL: {error}") +if failures: + raise AssertionError("enhanced cases failed:\n" + "\n".join(failures)) +visual = pathlib.Path('/logs/verifier/visual-audit') +visual.mkdir(parents=True, exist_ok=True) +shutil.copyfile(ROOT / 'transformed_image.png', visual / 'transformed-image.png') diff --git a/task_034/tests/validate_outputs.py b/task_034/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..5b618f678b21be5dbe17277bf54c478a77973ec0 --- /dev/null +++ b/task_034/tests/validate_outputs.py @@ -0,0 +1,31 @@ +import pathlib +import numpy as np +from PIL import Image +root = pathlib.Path.cwd() +image_path = root / 'transformed_image.png' +report_path = root / 'transform_report.txt' +assert image_path.exists() and image_path.stat().st_size > 0, 'missing transformed_image.png' +assert report_path.exists() and report_path.stat().st_size > 0, 'missing transform_report.txt' +img = Image.open(image_path) +assert img.width > 0 and img.height > 0, 'transformed image has invalid dimensions' +def box_blur_3x3(img): + padded = np.pad(img.astype(np.float32), ((1, 1), (1, 1), (0, 0)), mode='edge') + out = np.zeros_like(img, dtype=np.float32) + for y in range(img.shape[0]): + for x in range(img.shape[1]): + out[y, x] = padded[y:y+3, x:x+3].mean(axis=(0, 1)) + return np.rint(out).astype(np.uint8) +src = np.array(Image.open(root / 'input.ppm').convert('RGB')) +top, left = (src.shape[0] - 4) // 2, (src.shape[1] - 4) // 2 +crop = src[top:top+4, left:left+4, :] +flipped = crop[:, ::-1, :] +blurred = box_blur_3x3(flipped) +gray = np.rint(0.299 * blurred[:, :, 0] + 0.587 * blurred[:, :, 1] + 0.114 * blurred[:, :, 2]).astype(np.uint8) +expected = np.repeat(gray[:, :, None], 3, axis=2) +out = np.array(img.convert('RGB')) +assert out.shape == expected.shape, f'expected 4x4 RGB output, got {out.shape}' +diff = np.abs(out.astype(np.int16) - expected.astype(np.int16)) +assert diff.max() <= 3, f'output pixels differ from expected pipeline; max diff {diff.max()}' +report = report_path.read_text(encoding='utf-8', errors='ignore').lower() +for alternatives in [('centercrop', 'center crop', '中心裁剪'), ('horizontalflip', 'horizontal_flip', 'horizontal flip', '水平翻转'), ('blur', '模糊'), ('gray', 'grey', '灰度')]: + assert any(token in report for token in alternatives), f'report missing operation {alternatives}' diff --git a/task_035/acceptance_checklist.json b/task_035/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..4fe6619ca53c0d540c257a41b34c6f1ac34bd5d3 --- /dev/null +++ b/task_035/acceptance_checklist.json @@ -0,0 +1,22 @@ +{ + "task_id": 51, + "category": "machine_learning", + "language": "python", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Python files compile; data-analysis tasks generate the requested output files from fixture data." + ], + "input_assets": [ + "test.csv" + ], + "expected_outputs": [ + "threshold_report.txt" + ], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns.", + "Input assets are separated from candidate outputs; do not score candidates merely for recreating input files." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_035/environment/Dockerfile b/task_035/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b5c3125aadc8adae6187cdea0ad0c6d3cf3e505e --- /dev/null +++ b/task_035/environment/Dockerfile @@ -0,0 +1,7 @@ +FROM mcr.microsoft.com/playwright:v1.52.0-noble +USER root +RUN apt-get update && apt-get install -y --no-install-recommends python3-numpy python3-pil && ln -sf /usr/bin/python3 /usr/local/bin/python && rm -rf /var/lib/apt/lists/* +RUN npm install --global --prefix /usr playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules +WORKDIR /app +COPY ./code /app diff --git a/task_035/environment/code/test.csv b/task_035/environment/code/test.csv new file mode 100644 index 0000000000000000000000000000000000000000..d8cfc8052be2eea8416496bed2d78ee5382ef12d --- /dev/null +++ b/task_035/environment/code/test.csv @@ -0,0 +1,9 @@ +url,score,label +img001.jpg,0.95,clear +img002.jpg,0.88,clear +img003.jpg,0.74,clear +img004.jpg,0.61,blurry +img005.jpg,0.52,blurry +img006.jpg,0.43,blurry +img007.jpg,0.35,blurry +img008.jpg,0.20,blurry diff --git a/task_035/environment/docker-compose.yaml b/task_035/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_035/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_035/instruction.md b/task_035/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2c438cbceda7bfe6ed89697d3d134b260f411886 --- /dev/null +++ b/task_035/instruction.md @@ -0,0 +1,15 @@ +# Optimize an F1 threshold + +Write `solve.py` to choose the clarity-score threshold that maximizes binary F1 on the supplied dataset. Run `python3 solve.py` from the project root. Read `test.csv` on every run; its columns are `url` (identifier only), `score` (finite real number), and `label` (`clear` or `blurry`). Do not fetch images or use the network. + +## Threshold and output + +Consider the distinct scores in the current file as candidate thresholds. At threshold `t`, predict `clear` for `score >= t` and `blurry` otherwise, so rows with tied scores receive the same prediction. Treat `clear` as positive. Compute F1 as `2*TP / (2*TP + FP + FN)`, or zero when the denominator is zero. Select any candidate achieving the maximum; scores are not restricted to [0,1]. + +- Write `threshold_metrics.json` with finite numeric `threshold` and `f1` fields. Keep the selected score unrounded and report its actual F1. +- Write `threshold_report.txt` with clearly labeled `threshold:` and `F1 score:` values at no fewer than three decimal places, consistent with the JSON. + +## Acceptance Checklist + +- The threshold comes from the current scores and achieves their maximum attainable F1. The JSON and formatted report agree. +- New score distributions, tied scores and inputs with only one class are handled without fixed thresholds, downloads or errors. diff --git a/task_035/quality_notes.md b/task_035/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..2ef6090b0119048acd6aef0e3e8f39d848014b73 --- /dev/null +++ b/task_035/quality_notes.md @@ -0,0 +1,4 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. +- Input assets are separated from candidate outputs; do not score candidates merely for recreating input files. \ No newline at end of file diff --git a/task_035/solution/README.md b/task_035/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_035/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_035/solution/code/solve.py b/task_035/solution/code/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..35b31f5ad11f2840b2aa83f89ae0d28fad699126 --- /dev/null +++ b/task_035/solution/code/solve.py @@ -0,0 +1,22 @@ +import csv + +rows = list(csv.DictReader(open('test.csv', encoding='utf-8-sig'))) +def f1_at(threshold): + tp = fp = fn = 0 + for row in rows: + pred_clear = float(row['score']) >= threshold + actual_clear = row['label'].strip().lower() == 'clear' + tp += bool(pred_clear and actual_clear) + fp += bool(pred_clear and not actual_clear) + fn += bool((not pred_clear) and actual_clear) + precision = tp / (tp + fp) if tp + fp else 0 + recall = tp / (tp + fn) if tp + fn else 0 + return 2 * precision * recall / (precision + recall) if precision + recall else 0 +thresholds = sorted({float(r['score']) for r in rows}) +best_threshold, best_f1 = max(((t, f1_at(t)) for t in thresholds), key=lambda x: x[1]) +open('threshold_report.txt', 'w', encoding='utf-8').write( + f'Optimal threshold: {best_threshold:.3f}\nF1 score: {best_f1:.3f}\n' +) + +import json +open('threshold_metrics.json','w').write(json.dumps({'threshold':best_threshold,'f1':best_f1})) diff --git a/task_035/solution/solve.sh b/task_035/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_035/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_035/task.toml b/task_035/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_035/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_035/task_meta.json b/task_035/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..785de6a32e56c1181aa0fcb6d9d56142e327b4ab --- /dev/null +++ b/task_035/task_meta.json @@ -0,0 +1,22 @@ +{ + "task_id": 51, + "task_category": "machine_learning", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 2, + "language": "python", + "tool_files_from_selected_trace": [ + "find_optimal_threshold.py", + "simple_threshold_analysis.py", + "test.csv" + ], + "input_assets": [ + "test.csv" + ], + "expected_outputs": [ + "threshold_report.txt" + ], + "source_row_id": 306, + "repair_revision": "2026-09-29", + "instruction_sha256": "81e5a77830c552223d0c1c070786a5f9db92021415550797cb40cb2749aac575" +} diff --git a/task_035/tests/_offline/sitecustomize.py b/task_035/tests/_offline/sitecustomize.py new file mode 100644 index 0000000000000000000000000000000000000000..b56d40ca3ecdf6893c56d99c2ab48a45580aa593 --- /dev/null +++ b/task_035/tests/_offline/sitecustomize.py @@ -0,0 +1,14 @@ +"""Deterministic, network-disabled Python test runtime.""" +import random +import socket + +random.seed(0) + + +def _blocked(*_args, **_kwargs): + raise RuntimeError("network access is disabled by the verifier") + + +socket.create_connection = _blocked +socket.socket.connect = _blocked +socket.socket.connect_ex = _blocked diff --git a/task_035/tests/_shared/contract_checker.js b/task_035/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_035/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_035/tests/_shared/static_enhancer.sh b/task_035/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_035/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_035/tests/enhancement_cases.json b/task_035/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..bc31a4ef4818beb94b1d8057ca6f1bb33066a281 --- /dev/null +++ b/task_035/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "Choose a reasonable threshold that maximizes the final F1 score.", + "validator": "tests/validate_enhanced.py::case_1_fixture_optimum_is_real", + "behavior": "Independently compute F1 for every candidate score in test.csv and verify that the reported threshold attains and reports the maximum F1." + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "test.csv contains url, score, and clear/blurry label columns; choose a threshold that maximizes F1.", + "validator": "tests/validate_enhanced.py::case_2_alternate_score_distribution", + "behavior": "Write a valid CSV with a different score distribution in an isolated directory, rerun the candidate, and verify the new optimum to prevent a hard-coded answer." + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "Choose a reasonable threshold that maximizes the final F1 score.", + "validator": "tests/validate_enhanced.py::case_3_tied_scores_are_evaluated_together", + "behavior": "Use a legal boundary case with duplicate scores and conflicting labels, then verify that equal-score samples are classified consistently and the selected threshold still maximizes F1." + } +] diff --git a/task_035/tests/review_hard.py b/task_035/tests/review_hard.py new file mode 100644 index 0000000000000000000000000000000000000000..063c9a34ec91349cd2c9605e437ad068a2554cd3 --- /dev/null +++ b/task_035/tests/review_hard.py @@ -0,0 +1,42 @@ +"""Exercise legal three-column datasets without changing the original workspace.""" +import csv +import json +import math +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +root = Path(sys.argv[1]).resolve() +cases = [ + [(0.1, 'clear'), (0.7, 'blurry'), (0.9, 'clear')], + [(0.2, 'blurry'), (0.2, 'clear'), (0.8, 'clear'), (0.8, 'blurry')], + [(0.1, 'blurry'), (0.9, 'blurry')], + [(-100, 'clear'), (-2, 'clear'), (500, 'clear')], +] +for batch in cases: + with tempfile.TemporaryDirectory(prefix='threshold-contract-') as directory: + workspace = Path(directory) / 'candidate' + shutil.copytree(root, workspace, ignore=shutil.ignore_patterns('tests', 'logs', '__pycache__', 'node_modules')) + for name in ('threshold_report.txt', 'threshold_metrics.json'): + (workspace / name).unlink(missing_ok=True) + with (workspace / 'test.csv').open('w', newline='', encoding='utf-8') as handle: + writer = csv.writer(handle) + writer.writerow(['url', 'score', 'label']) + writer.writerows((f'{index}.jpg', score, label) for index, (score, label) in enumerate(batch)) + result = subprocess.run([sys.executable, 'solve.py'], cwd=workspace, capture_output=True, text=True, timeout=30) + assert result.returncode == 0, result.stderr + got = json.loads((workspace / 'threshold_metrics.json').read_text()) + threshold = got['threshold'] + assert threshold in {score for score, _ in batch} + + def f1(candidate): + tp = sum(score >= candidate and label == 'clear' for score, label in batch) + fp = sum(score >= candidate and label != 'clear' for score, label in batch) + fn = sum(score < candidate and label == 'clear' for score, label in batch) + return 2 * tp / (2 * tp + fp + fn) if 2 * tp + fp + fn else 0 + + assert math.isclose(got['f1'], f1(threshold), abs_tol=1e-12) + assert math.isclose(got['f1'], max(f1(score) for score, _ in batch), abs_tol=1e-12) +print('Threshold class-balance, ties and legal schema checks passed') diff --git a/task_035/tests/review_legacy.sh b/task_035/tests/review_legacy.sh new file mode 100644 index 0000000000000000000000000000000000000000..ac172291d0d1eab8750a7f111ecd702456cf6e92 --- /dev/null +++ b/task_035/tests/review_legacy.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +set -euo pipefail +set +e +TASK_ID='51' +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +source "$TEST_DIR/_shared/static_enhancer.sh" +OFFLINE_PYTHONPATH="$TEST_DIR/_offline${PYTHONPATH:+:$PYTHONPATH}" +RUN_ENV=(env PYTHONHASHSEED=0 PYTHONPATH="$OFFLINE_PYTHONPATH" HF_DATASETS_OFFLINE=1 TRANSFORMERS_OFFLINE=1 WANDB_MODE=offline NO_PROXY='' HTTP_PROXY='http://127.0.0.1:9' HTTPS_PROXY='http://127.0.0.1:9' ALL_PROXY='http://127.0.0.1:9') +LOG_DIR="/logs/verifier" +if ! mkdir -p "$LOG_DIR" 2>/dev/null; then LOG_DIR="logs/verifier"; mkdir -p "$LOG_DIR"; fi +REWARD_FILE="$LOG_DIR/reward.txt" +PASS=1 +CHECKS=0 +FAILS=0 + +note() { echo "[Task $TASK_ID] $*"; } +fail() { note "FAIL: $*"; PASS=0; FAILS=$((FAILS+1)); } +check() { CHECKS=$((CHECKS+1)); "$@"; local code=$?; if [ $code -ne 0 ]; then fail "$*"; fi; } +have_any() { local pattern="$1"; compgen -G "$pattern" >/dev/null 2>&1; } +grep_any() { local pattern="$1"; shift; grep -REiq -- "$pattern" "$@" 2>/dev/null; } +source_files() { find . -type f \( -name '*.html' -o -name '*.js' -o -name '*.jsx' -o -name '*.ts' -o -name '*.tsx' -o -name '*.css' -o -name '*.py' -o -name '*.go' -o -name '*.swift' -o -name '*.svg' \) ! -path './tests/*' ! -path './logs/*'; } + +note "enhanced deterministic verifier start" +static_enhance_check "${TASK_ID}" "$(pwd)" +if [ ! -e 'test.csv' ]; then + fail "benchmark input asset missing: test.csv" +fi +mapfile -t py_files < <(find . -type f -name '*.py' ! -path './tests/*') +if [ ${#py_files[@]} -eq 0 ]; then fail "no Python source found"; fi +if command -v python3 >/dev/null 2>&1; then + for f in "${py_files[@]}"; do timeout 30s "${RUN_ENV[@]}" python3 -m py_compile "$f" >/tmp/harbor_py_compile.log 2>&1 || fail "python compile failed: $f"; done +fi +if command -v python3 >/dev/null 2>&1; then + check test -s solve.py + timeout 60s "${RUN_ENV[@]}" python3 solve.py >/tmp/harbor_data_run.log 2>&1 || fail "solve.py did not run successfully" +fi +check test -s 'threshold_report.txt' + +if command -v python3 >/dev/null 2>&1; then + check timeout 180s "${RUN_ENV[@]}" python3 "$TEST_DIR/validate_outputs.py" + check timeout 180s "${RUN_ENV[@]}" python3 "$TEST_DIR/validate_enhanced.py" +else + fail "python3 unavailable for output validation" +fi +# BEGIN AAAV_DYNAMIC_TEST +if [ -f "$TEST_DIR/validate_aaav_dynamic.js" ]; then + if command -v node >/dev/null 2>&1; then + check timeout 90s "${RUN_ENV[@]}" node "$TEST_DIR/validate_aaav_dynamic.js" + else + note "AAAV dynamic validation skipped (node unavailable in this runtime)" + fi +fi +# END AAAV_DYNAMIC_TEST +note "checks=$CHECKS fails=$FAILS" +if [ "$PASS" -eq 1 ]; then + echo 1 > "$REWARD_FILE" + note "PASS" + exit 0 +fi +echo 0 > "$REWARD_FILE" +note "FAIL" +exit 0 diff --git a/task_035/tests/test.sh b/task_035/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56b0776f3ccad7f2da017c3b6e7cd69a9a1454e6 --- /dev/null +++ b/task_035/tests/test.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -uo pipefail +bash /tests/review_legacy.sh +CORE=$(cat /logs/verifier/reward.txt 2>/dev/null || echo 0) +mkdir -p /logs/verifier +python3 /tests/review_hard.py /app 2>&1 | tee /logs/verifier/review_hard.log +RC=${PIPESTATUS[0]} +if [ "$RC" -ne 0 ]; then echo "REVIEW_HARD failed with exit code $RC"; fi +if [ "$RC" -eq 0 ]; then echo "$CORE"; else echo 0; fi > /logs/verifier/reward.txt +exit 0 diff --git a/task_035/tests/validate_aaav_dynamic.js b/task_035/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..7479cf2883fd951872eed48b7faf26d8dd3f2295 --- /dev/null +++ b/task_035/tests/validate_aaav_dynamic.js @@ -0,0 +1,69 @@ +const fs = require('fs'); +const path = require('path'); +const child_process = require('child_process'); +const TASK_ID = 51; +const LANGUAGE = "python"; +const EXPECTED = [ + "threshold_report.txt" +]; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { if (!condition) throw new Error(message); } +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} +function globToRe(glob) { + return new RegExp('^' + glob.split('*').map(x => x.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') + '$'); +} +function existsPattern(files, pat) { + const re = globToRe(String(pat).replace(/\\/g, '/')); + return files.some(f => re.test(f.replace(/\\/g, '/')) || f.replace(/\\/g, '/').endsWith(String(pat).replace(/\\/g, '/'))); +} + +const files = walk(process.cwd()); +assert(files.length > 0, 'candidate workspace should contain files'); +const rel = files.map(f => path.relative(process.cwd(), f)); +const source = files.filter(f => /\.(js|jsx|ts|tsx|css|html|py|go|md|svg)$/i.test(f)); +assert(source.length > 0, 'candidate should contain source or report files'); + +if (LANGUAGE === 'go') { + const goFiles = files.filter(f => f.endsWith('.go')); + assert(goFiles.length > 0, 'go task should contain .go files'); + try { + child_process.execFileSync('go', ['test', './...'], { cwd: process.cwd(), stdio: 'pipe', timeout: 120000 }); + } catch (err) { + // The benchmark's own verifier owns task-specific Go behavior. Here we + // keep go test as an opportunistic runtime probe so local module/path + // differences do not create false negatives. + const msg = Buffer.concat([err.stdout || Buffer.alloc(0), err.stderr || Buffer.alloc(0)]).toString().slice(0, 500); + console.warn('go test ./... probe failed but is non-fatal: ' + msg); + } +} else if (LANGUAGE === 'python') { + const pyFiles = files.filter(f => f.endsWith('.py')); + assert(pyFiles.length > 0 || rel.some(f => /\.(html|csv|json|txt|md|png)$/i.test(f)), 'python/data task should contain scripts or produced artifacts'); + for (const f of pyFiles.slice(0, 20)) { + child_process.execFileSync('python3', ['-m', 'py_compile', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); + } +} else { + for (const f of files.filter(f => f.endsWith('.js')).slice(0, 20)) { + child_process.execFileSync('node', ['--check', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); + } +} + +for (const pat of EXPECTED) { + assert(existsPattern(rel, pat), 'missing expected artifact pattern after verifier: ' + pat); +} + +console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); diff --git a/task_035/tests/validate_enhanced.py b/task_035/tests/validate_enhanced.py new file mode 100644 index 0000000000000000000000000000000000000000..a06f1c040cee3962b68431b69f8dfbde0c195be8 --- /dev/null +++ b/task_035/tests/validate_enhanced.py @@ -0,0 +1,164 @@ +import csv +import json +import math +import os +import pathlib +import re +import shutil +import subprocess +import sys +import tempfile + + +ROOT = pathlib.Path.cwd() +SKIP_PARTS = {"tests", "logs", "__pycache__", ".git", "node_modules"} +NUMBER_RE = re.compile(r"(?= threshold + actual_clear = row["label"].strip().lower() == "clear" + tp += int(predicted_clear and actual_clear) + fp += int(predicted_clear and not actual_clear) + fn += int(not predicted_clear and actual_clear) + return 2 * tp / (2 * tp + fp + fn) if (2 * tp + fp + fn) else 0.0 + + +def _assert_optimal_report(workspace): + rows = _rows(workspace / "test.csv") + text = (workspace / "threshold_report.txt").read_text(encoding="utf-8", errors="ignore") + metrics = json.loads((workspace / "threshold_metrics.json").read_text(encoding="utf-8")) + threshold, reported_f1 = metrics["threshold"], metrics["f1"] + assert type(threshold) in (int, float) and math.isfinite(threshold), "JSON threshold must be finite numeric" + assert type(reported_f1) in (int, float) and math.isfinite(reported_f1), "JSON f1 must be finite numeric" + values = [float(value) for value in NUMBER_RE.findall(text)] + assert values, "threshold_report.txt contains no numeric threshold/F1 values" + candidates = sorted({float(row["score"]) for row in rows}) + best_f1 = max(_f1(rows, threshold) for threshold in candidates) + assert threshold in candidates, "JSON threshold is not a score candidate" + assert math.isclose(_f1(rows, threshold), best_f1, abs_tol=1e-12), "JSON threshold is not optimal" + assert math.isclose(reported_f1, best_f1, abs_tol=1e-12), "JSON f1 is not the optimum" + number = r'([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)' + threshold_match = re.search(r'threshold\s*[:=]\s*' + number, text, re.I) + f1_match = re.search(r'f1(?:\s*score)?\s*[:=]\s*' + number, text, re.I) + assert threshold_match and abs(float(threshold_match.group(1)) - threshold) <= max(0.0005, abs(threshold) * 1e-6), 'report threshold field disagrees with JSON' + assert f1_match and abs(float(f1_match.group(1)) - best_f1) <= 0.0005, 'report F1 field disagrees with JSON' + + +def _copy_candidate(destination): + for source in ROOT.iterdir(): + if source.name in SKIP_PARTS: + continue + target = destination / source.name + if source.is_dir(): + shutil.copytree(source, target, ignore=shutil.ignore_patterns(*SKIP_PARTS)) + else: + shutil.copy2(source, target) + + +def _offline_env(workspace): + guard = workspace / ".test_guard" + guard.mkdir(exist_ok=True) + (guard / "sitecustomize.py").write_text( + "import random, socket\n" + "random.seed(0)\n" + "def blocked(*args, **kwargs): raise RuntimeError('network disabled by validator')\n" + "socket.create_connection = blocked\n" + "socket.socket.connect = blocked\n" + "socket.socket.connect_ex = blocked\n", + encoding="utf-8", + ) + env = os.environ.copy() + env.update({"PYTHONHASHSEED": "0", "PYTHONPATH": str(guard), "HF_DATASETS_OFFLINE": "1", "TRANSFORMERS_OFFLINE": "1"}) + return env + + +def _run_with_rows(rows): + holder = tempfile.TemporaryDirectory(prefix="task051-enhanced-") + workspace = pathlib.Path(holder.name) + _copy_candidate(workspace) + with (workspace / "test.csv").open("w", encoding="utf-8", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=["url", "score", "label"]) + writer.writeheader() + writer.writerows(rows) + script = workspace / "solve.py" + assert script.is_file(), "missing public solve.py entrypoint" + (workspace / "threshold_report.txt").unlink(missing_ok=True) + (workspace / "threshold_metrics.json").unlink(missing_ok=True) + proc = subprocess.run( + [sys.executable, str(script)], cwd=workspace, env=_offline_env(workspace), + capture_output=True, text=True, timeout=60, + ) + if proc.returncode == 0 and (workspace / "threshold_report.txt").is_file() and (workspace / "threshold_metrics.json").is_file(): + return holder, workspace + holder.cleanup() + raise AssertionError(f"solve.py failed or did not generate outputs: rc={proc.returncode} stderr={proc.stderr[-500:]}") + + +# ENHANCED_CASE_1: the reported threshold must actually attain the fixture's maximum F1. +def case_1_fixture_optimum_is_real() -> None: + _assert_optimal_report(ROOT) + + +# ENHANCED_CASE_2: a different valid score ordering must produce its own optimum, not a fixture constant. +def case_2_alternate_score_distribution() -> None: + rows = [ + {"url": "a.jpg", "score": "0.91", "label": "clear"}, + {"url": "b.jpg", "score": "0.80", "label": "blurry"}, + {"url": "c.jpg", "score": "0.67", "label": "clear"}, + {"url": "d.jpg", "score": "0.45", "label": "blurry"}, + ] + holder, workspace = _run_with_rows(rows) + try: + _assert_optimal_report(workspace) + finally: + holder.cleanup() + + +# ENHANCED_CASE_3: duplicate scores with conflicting labels are a legal threshold boundary case. +def case_3_tied_scores_are_evaluated_together() -> None: + rows = [ + {"url": "tie-a.jpg", "score": "0.90", "label": "clear"}, + {"url": "tie-b.jpg", "score": "0.50", "label": "clear"}, + {"url": "tie-c.jpg", "score": "0.50", "label": "blurry"}, + {"url": "tie-d.jpg", "score": "0.10", "label": "blurry"}, + ] + holder, workspace = _run_with_rows(rows) + try: + _assert_optimal_report(workspace) + finally: + holder.cleanup() + + +def case_4_all_negative_and_non_normalized_scores() -> None: + rows = [ + {"url": "a.jpg", "score": "-3.25", "label": "blurry"}, + {"url": "b.jpg", "score": "10.5", "label": "blurry"}, + {"url": "c.jpg", "score": "10.5", "label": "blurry"}, + ] + holder, workspace = _run_with_rows(rows) + try: + _assert_optimal_report(workspace) + finally: + holder.cleanup() + + +failures = [] +for case in (case_1_fixture_optimum_is_real, case_2_alternate_score_distribution, case_3_tied_scores_are_evaluated_together, case_4_all_negative_and_non_normalized_scores): + try: + case() + print(f"{case.__name__}: PASS") + except Exception as error: + failures.append(f"{case.__name__}: {error}") + print(f"{case.__name__}: FAIL: {error}") +if failures: + raise AssertionError("enhanced cases failed:\n" + "\n".join(failures)) diff --git a/task_035/tests/validate_outputs.py b/task_035/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..c248110008bcec81be7288081456618264b433d1 --- /dev/null +++ b/task_035/tests/validate_outputs.py @@ -0,0 +1,5 @@ +"""The enhanced validator independently recomputes the optimum; check presence here.""" +from pathlib import Path + +for name in ('threshold_report.txt', 'threshold_metrics.json'): + assert Path(name).is_file() and Path(name).stat().st_size, f'missing {name}' diff --git a/task_036/acceptance_checklist.json b/task_036/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..4282b916c03f4daee82944755d1a83fd409dcdb5 --- /dev/null +++ b/task_036/acceptance_checklist.json @@ -0,0 +1,30 @@ +{ + "task_id": 52, + "category": "machine_learning", + "language": "python", + "acceptance_items": [ + "valid JPEG and complete-pair discovery", + "six-pair shards with exact original bytes", + "score numerator and denominator", + "batch loader and two/three-rank partition", + "new pair, orphan samples, caption edit, stale shard" + ], + "input_assets": [ + "data/dataset/000001.jpg … 000018.jpg and matching .txt", + "data/dataset/000019.jpg", + "data/dataset/000020.txt" + ], + "expected_outputs": [ + "solve.py", + "dataloader_demo.py", + "distributed_demo.py", + "score.txt", + "shards/dataset-*.tar" + ], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns.", + "Input assets are separated from candidate outputs; do not score candidates merely for recreating input files." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-30" +} diff --git a/task_036/environment/Dockerfile b/task_036/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b5c3125aadc8adae6187cdea0ad0c6d3cf3e505e --- /dev/null +++ b/task_036/environment/Dockerfile @@ -0,0 +1,7 @@ +FROM mcr.microsoft.com/playwright:v1.52.0-noble +USER root +RUN apt-get update && apt-get install -y --no-install-recommends python3-numpy python3-pil && ln -sf /usr/bin/python3 /usr/local/bin/python && rm -rf /var/lib/apt/lists/* +RUN npm install --global --prefix /usr playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules +WORKDIR /app +COPY ./code /app diff --git a/task_036/environment/code/data/dataset/000001.jpg b/task_036/environment/code/data/dataset/000001.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7a128d965c2c7bfbc7f9351219c58225dac51480 --- /dev/null +++ b/task_036/environment/code/data/dataset/000001.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:677368831b98442b5da4c2306c6d8e8bc036f0ebf0335031ae1ef1964cea93b9 +size 2527 diff --git a/task_036/environment/code/data/dataset/000001.txt b/task_036/environment/code/data/dataset/000001.txt new file mode 100644 index 0000000000000000000000000000000000000000..6765c928870e195434c3df465e73483ab30b1e71 --- /dev/null +++ b/task_036/environment/code/data/dataset/000001.txt @@ -0,0 +1 @@ +A blue circle on a pale canvas; sample 01. diff --git a/task_036/environment/code/data/dataset/000002.jpg b/task_036/environment/code/data/dataset/000002.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0eb3ad4acd9d1658a1846eddf508fea1a55b2fc1 --- /dev/null +++ b/task_036/environment/code/data/dataset/000002.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb161f124ecb971d5348949c849df651d0b18d8d2b6e5e844bb3440397cbd8a4 +size 2483 diff --git a/task_036/environment/code/data/dataset/000002.txt b/task_036/environment/code/data/dataset/000002.txt new file mode 100644 index 0000000000000000000000000000000000000000..fb1b730b421cd6b7f518485d1d44c72a6f24a64f --- /dev/null +++ b/task_036/environment/code/data/dataset/000002.txt @@ -0,0 +1 @@ +A red circle on a pale canvas; sample 02. diff --git a/task_036/environment/code/data/dataset/000003.jpg b/task_036/environment/code/data/dataset/000003.jpg new file mode 100644 index 0000000000000000000000000000000000000000..65ec8d6dc5d731cea3d6377996f0a9644e37d25f --- /dev/null +++ b/task_036/environment/code/data/dataset/000003.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5a99aad7dcbde2c0b675506aaed3bdc713577c8dcffe535273d2b5fde045dfaf +size 2398 diff --git a/task_036/environment/code/data/dataset/000003.txt b/task_036/environment/code/data/dataset/000003.txt new file mode 100644 index 0000000000000000000000000000000000000000..9220fbf08a8f8409d4ea3df80b8fe687c1b97267 --- /dev/null +++ b/task_036/environment/code/data/dataset/000003.txt @@ -0,0 +1 @@ +A green circle on a pale canvas; sample 03. diff --git a/task_036/environment/code/data/dataset/000004.jpg b/task_036/environment/code/data/dataset/000004.jpg new file mode 100644 index 0000000000000000000000000000000000000000..95a6db591a4475187240b6fdbed99485a551cd30 --- /dev/null +++ b/task_036/environment/code/data/dataset/000004.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e959863baf72552dcdf6e9a8f9320f6ef722c11337b20f33cde6af94f7f21a10 +size 2339 diff --git a/task_036/environment/code/data/dataset/000004.txt b/task_036/environment/code/data/dataset/000004.txt new file mode 100644 index 0000000000000000000000000000000000000000..a814276870888c55d639f3501c298bcfbef48e9d --- /dev/null +++ b/task_036/environment/code/data/dataset/000004.txt @@ -0,0 +1 @@ +A amber circle on a pale canvas; sample 04. diff --git a/task_036/environment/code/data/dataset/000005.jpg b/task_036/environment/code/data/dataset/000005.jpg new file mode 100644 index 0000000000000000000000000000000000000000..424bd4882d6a19aac79c70d10bc6f86ab407d72d --- /dev/null +++ b/task_036/environment/code/data/dataset/000005.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:172bc5922de930781fb1d4536e9db51cba306e311317b493f127ce7a386df0d5 +size 2438 diff --git a/task_036/environment/code/data/dataset/000005.txt b/task_036/environment/code/data/dataset/000005.txt new file mode 100644 index 0000000000000000000000000000000000000000..2c1bce376a9e8a0d044f19b9059a6b1837bb74b6 --- /dev/null +++ b/task_036/environment/code/data/dataset/000005.txt @@ -0,0 +1 @@ +A violet circle on a pale canvas; sample 05. diff --git a/task_036/environment/code/data/dataset/000006.jpg b/task_036/environment/code/data/dataset/000006.jpg new file mode 100644 index 0000000000000000000000000000000000000000..86932dd5673b0130485bf3a27b4a534301dbeb7b --- /dev/null +++ b/task_036/environment/code/data/dataset/000006.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b37d0eb98c04f92d59c66a0c4d2ef32847b783bf85d49f5cced3c28d32605d38 +size 2491 diff --git a/task_036/environment/code/data/dataset/000006.txt b/task_036/environment/code/data/dataset/000006.txt new file mode 100644 index 0000000000000000000000000000000000000000..ed10c9481bfc633b8fb95ebb85196f7ea1c8bdde --- /dev/null +++ b/task_036/environment/code/data/dataset/000006.txt @@ -0,0 +1 @@ +A teal circle on a pale canvas; sample 06. diff --git a/task_036/environment/code/data/dataset/000007.jpg b/task_036/environment/code/data/dataset/000007.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0fa1fa7d4319aab05049db5ccb8b0b75ad236fe8 --- /dev/null +++ b/task_036/environment/code/data/dataset/000007.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af41c8e0c09dfaee685192e5588a7f5eea773941de5bcf1e1d82be2a95c17221 +size 2568 diff --git a/task_036/environment/code/data/dataset/000007.txt b/task_036/environment/code/data/dataset/000007.txt new file mode 100644 index 0000000000000000000000000000000000000000..c756589a98441bb6a1719828888880bcee1ac770 --- /dev/null +++ b/task_036/environment/code/data/dataset/000007.txt @@ -0,0 +1 @@ +A blue triangle on a pale canvas; sample 07. diff --git a/task_036/environment/code/data/dataset/000008.jpg b/task_036/environment/code/data/dataset/000008.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f50bce51b690943af5e84fe344ecfe4a79b08c96 --- /dev/null +++ b/task_036/environment/code/data/dataset/000008.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b2c9e86e7eff48542d19deac6efca77ae707a2268160a38eeda173257c133624 +size 2503 diff --git a/task_036/environment/code/data/dataset/000008.txt b/task_036/environment/code/data/dataset/000008.txt new file mode 100644 index 0000000000000000000000000000000000000000..c1e822451c0a1284a5229cf8bdd39dc93aea787a --- /dev/null +++ b/task_036/environment/code/data/dataset/000008.txt @@ -0,0 +1 @@ +A red triangle on a pale canvas; sample 08. diff --git a/task_036/environment/code/data/dataset/000009.jpg b/task_036/environment/code/data/dataset/000009.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6b6d5905a50b2c777732f854f4eec881a18118b6 --- /dev/null +++ b/task_036/environment/code/data/dataset/000009.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:faf9c36eb50a8aeb121216f2b986c73da13c08be178cfc92efe299d5a0a93a26 +size 2424 diff --git a/task_036/environment/code/data/dataset/000009.txt b/task_036/environment/code/data/dataset/000009.txt new file mode 100644 index 0000000000000000000000000000000000000000..2ac1b87d8810adf1bf602571c0c48e1d54538b7a --- /dev/null +++ b/task_036/environment/code/data/dataset/000009.txt @@ -0,0 +1 @@ +A green triangle on a pale canvas; sample 09. diff --git a/task_036/environment/code/data/dataset/000010.jpg b/task_036/environment/code/data/dataset/000010.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f2a34b5715258eecbc663267b731e3c2de511aa7 --- /dev/null +++ b/task_036/environment/code/data/dataset/000010.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b0b0cf31aedd9a744e16fef918e308e0c4d491f4819b79e9c1dd241edc66a8d5 +size 2343 diff --git a/task_036/environment/code/data/dataset/000010.txt b/task_036/environment/code/data/dataset/000010.txt new file mode 100644 index 0000000000000000000000000000000000000000..28caf30042167790d0e48c684e6f01d878b42d02 --- /dev/null +++ b/task_036/environment/code/data/dataset/000010.txt @@ -0,0 +1 @@ +A amber triangle on a pale canvas; sample 10. diff --git a/task_036/environment/code/data/dataset/000011.jpg b/task_036/environment/code/data/dataset/000011.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e5b480136fe5f45de26917e99698d2c05482849e --- /dev/null +++ b/task_036/environment/code/data/dataset/000011.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ec87438c3f193e3106315b69cd3cb00590ed50aec56a31535ecd0eb71c990e7 +size 2434 diff --git a/task_036/environment/code/data/dataset/000011.txt b/task_036/environment/code/data/dataset/000011.txt new file mode 100644 index 0000000000000000000000000000000000000000..6c9bf5427b33250852e372d0cce7e1815005ac35 --- /dev/null +++ b/task_036/environment/code/data/dataset/000011.txt @@ -0,0 +1 @@ +A violet triangle on a pale canvas; sample 11. diff --git a/task_036/environment/code/data/dataset/000012.jpg b/task_036/environment/code/data/dataset/000012.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5166cd592a10f6a1ec9199497d50492089f029b8 --- /dev/null +++ b/task_036/environment/code/data/dataset/000012.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0bd898a9df93938f80d8d94b12c5bdcd3f4208a83d11f46e1f8af55fef7f9fc8 +size 2483 diff --git a/task_036/environment/code/data/dataset/000012.txt b/task_036/environment/code/data/dataset/000012.txt new file mode 100644 index 0000000000000000000000000000000000000000..1635a47ac6a215dab504fbbe7af45d08115b90a7 --- /dev/null +++ b/task_036/environment/code/data/dataset/000012.txt @@ -0,0 +1 @@ +A teal triangle on a pale canvas; sample 12. diff --git a/task_036/environment/code/data/dataset/000013.jpg b/task_036/environment/code/data/dataset/000013.jpg new file mode 100644 index 0000000000000000000000000000000000000000..54188e792dcd6893c777a29bed6b8de3e83c92bd --- /dev/null +++ b/task_036/environment/code/data/dataset/000013.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64b8c7138f07d1d7284cffeacb5b67f4f203febd803c05bb3ba39b3cf08a2d4d +size 1824 diff --git a/task_036/environment/code/data/dataset/000013.txt b/task_036/environment/code/data/dataset/000013.txt new file mode 100644 index 0000000000000000000000000000000000000000..3489f528f95d5599dbd5ebf93688efb5899ed1c1 --- /dev/null +++ b/task_036/environment/code/data/dataset/000013.txt @@ -0,0 +1 @@ +A blue square on a pale canvas; sample 13. diff --git a/task_036/environment/code/data/dataset/000014.jpg b/task_036/environment/code/data/dataset/000014.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e38fb86ea66cf0f1e77cac0ff3d239cafd93ed8b --- /dev/null +++ b/task_036/environment/code/data/dataset/000014.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6a29353274c9b568bb45ee968bda274c1cf5e1cf83e67a5bc6b23db2e91eb27d +size 1793 diff --git a/task_036/environment/code/data/dataset/000014.txt b/task_036/environment/code/data/dataset/000014.txt new file mode 100644 index 0000000000000000000000000000000000000000..fec06a65f3231b56cbc0cb75b90d96203ffc0414 --- /dev/null +++ b/task_036/environment/code/data/dataset/000014.txt @@ -0,0 +1 @@ +A red square on a pale canvas; sample 14. diff --git a/task_036/environment/code/data/dataset/000015.jpg b/task_036/environment/code/data/dataset/000015.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f914406551d4eb1f08792d89663976eb7ffd5beb --- /dev/null +++ b/task_036/environment/code/data/dataset/000015.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c1c7c2bab8e169f7212ddc16d2a0305f8c612d979c8556e8ec07a5b7b0f70699 +size 1752 diff --git a/task_036/environment/code/data/dataset/000015.txt b/task_036/environment/code/data/dataset/000015.txt new file mode 100644 index 0000000000000000000000000000000000000000..0065a50f418f3a1347632392cc881e758807fad5 --- /dev/null +++ b/task_036/environment/code/data/dataset/000015.txt @@ -0,0 +1 @@ +A green square on a pale canvas; sample 15. diff --git a/task_036/environment/code/data/dataset/000016.jpg b/task_036/environment/code/data/dataset/000016.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d09fdf522a504b3a593a8eca42caa59b83eadaa6 --- /dev/null +++ b/task_036/environment/code/data/dataset/000016.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fed13d3a998f72f3abf18718fe601e09cfeee308aab6183e3813b1a150469436 +size 1748 diff --git a/task_036/environment/code/data/dataset/000016.txt b/task_036/environment/code/data/dataset/000016.txt new file mode 100644 index 0000000000000000000000000000000000000000..66b952b0fd1eda85fd488c848a96f93d58d05c69 --- /dev/null +++ b/task_036/environment/code/data/dataset/000016.txt @@ -0,0 +1 @@ +A amber square on a pale canvas; sample 16. diff --git a/task_036/environment/code/data/dataset/000017.jpg b/task_036/environment/code/data/dataset/000017.jpg new file mode 100644 index 0000000000000000000000000000000000000000..451ea0809a813bb3ca84359aaafe17725ac8c38a --- /dev/null +++ b/task_036/environment/code/data/dataset/000017.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2944705575a7af225ba890000e02e1442ac17e66d102bf4e61bcd802678236d6 +size 1772 diff --git a/task_036/environment/code/data/dataset/000017.txt b/task_036/environment/code/data/dataset/000017.txt new file mode 100644 index 0000000000000000000000000000000000000000..b5256bdf26a60ea90871e12aba6f0fe4d18a75ac --- /dev/null +++ b/task_036/environment/code/data/dataset/000017.txt @@ -0,0 +1 @@ +A violet square on a pale canvas; sample 17. diff --git a/task_036/environment/code/data/dataset/000018.jpg b/task_036/environment/code/data/dataset/000018.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3d3bd3f945e12d326eee808499a582411af77689 --- /dev/null +++ b/task_036/environment/code/data/dataset/000018.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a8605a3f37db1700fc73b100ad83af99df0115d01100062fdae597e264359197 +size 1803 diff --git a/task_036/environment/code/data/dataset/000018.txt b/task_036/environment/code/data/dataset/000018.txt new file mode 100644 index 0000000000000000000000000000000000000000..dce0a0536643ef8d2d5d871414ec8efaafe5facd --- /dev/null +++ b/task_036/environment/code/data/dataset/000018.txt @@ -0,0 +1 @@ +A teal square on a pale canvas; sample 18. diff --git a/task_036/environment/code/data/dataset/000019.jpg b/task_036/environment/code/data/dataset/000019.jpg new file mode 100644 index 0000000000000000000000000000000000000000..8cd70baba070150c2a650232b2b8a2445ac0f973 --- /dev/null +++ b/task_036/environment/code/data/dataset/000019.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4d1b3c260bf87d56eb5f79ad8d48cc708966001fb241516d9099d61301405b0f +size 1011 diff --git a/task_036/environment/code/data/dataset/000020.txt b/task_036/environment/code/data/dataset/000020.txt new file mode 100644 index 0000000000000000000000000000000000000000..a2010e2c32fc02cd1e87273f4006a7ad9a2ede8a --- /dev/null +++ b/task_036/environment/code/data/dataset/000020.txt @@ -0,0 +1 @@ +Caption without an image. diff --git a/task_036/environment/docker-compose.yaml b/task_036/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_036/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_036/instruction.md b/task_036/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..12f7421d8f08139054cb73764f74e0b26cb76f55 --- /dev/null +++ b/task_036/instruction.md @@ -0,0 +1,19 @@ +# Package and read an image–caption dataset + +Build an offline Python standard-library workflow. Read top-level files in `data/dataset/` with six-digit sample keys and `.jpg` or `.txt` extensions. A key with both is a complete pair. Preserve the supplied inputs, including valid JPEGs. + +## Outputs + +- `python3 solve.py` generates `shards/dataset-000000.tar`, `shards/dataset-000001.tar`, and so on, and `score.txt`. +- `python3 dataloader_demo.py --batch-size B` prints one JSON array of sample keys per line, with positive batch size `B`. +- `python3 distributed_demo.py --rank R --world-size N` prints one sample key per line and no other stdout. Use positive `N` and a zero-based rank `0 <= R < N`. + +Local Python helpers are allowed; do not require additional packages or network access. + +## Acceptance Checklist + +- Discover complete pairs from the current inputs and skip incomplete pairs. Sort the keys lexicographically and put consecutive groups of six in contiguous zero-based shards; the last group may be shorter. Remove stale `dataset-*.tar` outputs. +- Each archive contains only the original bytes and filenames of the two files for each assigned key, with no duplicates. Ordering of members within the tar is unrestricted. +- `score.txt` contains `x/y`, where `x` counts complete pairs and `y` counts keys with either extension. Shards and score reflect input changes rather than fixed fixture counts. +- With only the shards available, the batch reader emits all keys in global sorted order, with a final short batch when needed. +- With only the shards available, each distributed rank emits sorted keys whose **global sample index** modulo `N` is `R`. Outputs are disjoint and collectively complete; a single rank reads everything and an empty rank prints nothing. diff --git a/task_036/quality_notes.md b/task_036/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..0dc1ba171196fe290e4f9c5d996274b8874d7784 --- /dev/null +++ b/task_036/quality_notes.md @@ -0,0 +1,10 @@ +# Quality notes — harbor_052 + +2026-09-30 人工反馈修订。题面、解答与可执行 verifier 已按同一公开约定同步。 + +验证重点: +- valid JPEG and complete-pair discovery(tests/validate_outputs.py) +- six-pair shards with exact original bytes(tests/validate_outputs.py) +- score numerator and denominator(tests/validate_outputs.py) +- batch loader and two/three-rank partition(tests/validate_outputs.py) +- new pair, orphan samples, caption edit, stale shard(tests/validate_enhanced.py) diff --git a/task_036/solution/README.md b/task_036/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fd92b0534a6718f72f672ceda001b978d94b7ebb --- /dev/null +++ b/task_036/solution/README.md @@ -0,0 +1,6 @@ +# Reference implementation — task 52 + +`solve.py` packs complete JPEG/caption pairs into six-pair tar shards and writes +the paired/observed-key score. `dataloader_demo.py` and `distributed_demo.py` +read every shard using the standard library; they provide runnable batch and +rank-partition examples for verifier calibration. diff --git a/task_036/solution/code/dataloader_demo.py b/task_036/solution/code/dataloader_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..58a52c145173f89768b24758f55df9aefc8f33fa --- /dev/null +++ b/task_036/solution/code/dataloader_demo.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +"""Read all tar shards and print globally ordered sample-key batches.""" + +import argparse +import json +from pathlib import Path +import tarfile + + +def sample_keys(): + keys = [] + for path in sorted(Path("shards").glob("dataset-*.tar")): + with tarfile.open(path) as archive: + names = {member.name for member in archive.getmembers() if member.isfile()} + for key in sorted({name[:-4] for name in names if name.endswith(".jpg")}): + if f"{key}.txt" in names: + assert archive.extractfile(f"{key}.jpg").read() + assert archive.extractfile(f"{key}.txt").read().strip() + keys.append(key) + return sorted(keys) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--batch-size", type=int, default=4) + args = parser.parse_args() + if args.batch_size < 1: + parser.error("batch size must be positive") + keys = sample_keys() + for offset in range(0, len(keys), args.batch_size): + print(json.dumps(keys[offset:offset + args.batch_size])) + + +if __name__ == "__main__": + main() diff --git a/task_036/solution/code/distributed_demo.py b/task_036/solution/code/distributed_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..603d2f301b955cd60bccf19df17476a0fb860548 --- /dev/null +++ b/task_036/solution/code/distributed_demo.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 +"""Assign globally sorted tar sample keys to a distributed rank.""" + +import argparse +from dataloader_demo import sample_keys + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--rank", type=int, required=True) + parser.add_argument("--world-size", type=int, required=True) + args = parser.parse_args() + if args.world_size < 1 or not 0 <= args.rank < args.world_size: + parser.error("rank must be in [0, world-size)") + for index, key in enumerate(sample_keys()): + if index % args.world_size == args.rank: + print(key) + + +if __name__ == "__main__": + main() diff --git a/task_036/solution/code/solve.py b/task_036/solution/code/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..a240144a7136b52bbe1128a6673281ce4ff033a7 --- /dev/null +++ b/task_036/solution/code/solve.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +"""Pack complete JPEG/caption pairs into reproducible six-pair tar shards.""" + +from pathlib import Path +import tarfile + + +DATASET = Path("data/dataset") +OUT = Path("shards") +SHARD_SIZE = 6 + + +def complete_pairs(): + images = {path.stem for path in DATASET.glob("*.jpg")} + captions = {path.stem for path in DATASET.glob("*.txt")} + return sorted(images & captions), len(images | captions) + + +def add_bytes(archive, path): + info = tarfile.TarInfo(path.name) + info.size = path.stat().st_size + info.mode = 0o644 + info.mtime = 0 + with path.open("rb") as source: + archive.addfile(info, source) + + +def main(): + pairs, discovered = complete_pairs() + OUT.mkdir(exist_ok=True) + for stale in OUT.glob("dataset-*.tar"): + stale.unlink() + for offset in range(0, len(pairs), SHARD_SIZE): + shard = OUT / f"dataset-{offset // SHARD_SIZE:06d}.tar" + with tarfile.open(shard, "w") as archive: + for key in pairs[offset:offset + SHARD_SIZE]: + add_bytes(archive, DATASET / f"{key}.jpg") + add_bytes(archive, DATASET / f"{key}.txt") + Path("score.txt").write_text(f"{len(pairs)}/{discovered} complete image-caption pairs\n", encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/task_036/solution/solve.sh b/task_036/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_036/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_036/task.toml b/task_036/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_036/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_036/task_meta.json b/task_036/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..ad0b52ba6bfc33de0ff3a95fb19468e6783bb58d --- /dev/null +++ b/task_036/task_meta.json @@ -0,0 +1,35 @@ +{ + "task_id": 52, + "task_category": "machine_learning", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 2, + "language": "python", + "tool_files_from_selected_trace": [ + "README.md", + "create_shards.py", + "dataset_index.json", + "demo_pipeline.py", + "distributed_dataloader.py", + "requirements.txt", + "test_dataloader_minimal.py", + "test_dataloader_simple.py", + "test_pipeline.py", + "train_diffusion.py" + ], + "input_assets": [ + "data/dataset/000001.jpg … 000018.jpg and matching .txt", + "data/dataset/000019.jpg", + "data/dataset/000020.txt" + ], + "expected_outputs": [ + "solve.py", + "dataloader_demo.py", + "distributed_demo.py", + "score.txt", + "shards/dataset-*.tar" + ], + "source_row_id": 312, + "repair_revision": "2026-09-30", + "instruction_sha256": "9fa11d69e3e32c4bb36a036954f812355451bce0941b90278c8097a7b042f3f6" +} diff --git a/task_036/tests/_offline/sitecustomize.py b/task_036/tests/_offline/sitecustomize.py new file mode 100644 index 0000000000000000000000000000000000000000..b56d40ca3ecdf6893c56d99c2ab48a45580aa593 --- /dev/null +++ b/task_036/tests/_offline/sitecustomize.py @@ -0,0 +1,14 @@ +"""Deterministic, network-disabled Python test runtime.""" +import random +import socket + +random.seed(0) + + +def _blocked(*_args, **_kwargs): + raise RuntimeError("network access is disabled by the verifier") + + +socket.create_connection = _blocked +socket.socket.connect = _blocked +socket.socket.connect_ex = _blocked diff --git a/task_036/tests/_shared/contract_checker.js b/task_036/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_036/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_036/tests/_shared/static_enhancer.sh b/task_036/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_036/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_036/tests/enhancement_cases.json b/task_036/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..903de85fbf0f00e7fe7187171783ca2e0dda8468 --- /dev/null +++ b/task_036/tests/enhancement_cases.json @@ -0,0 +1,32 @@ +[ + { + "case_id": "CASE_1", + "instruction_evidence": "valid JPEG and complete-pair discovery", + "validator": "tests/validate_outputs.py", + "behavior": "valid JPEG and complete-pair discovery" + }, + { + "case_id": "CASE_2", + "instruction_evidence": "six-pair shards with exact original bytes", + "validator": "tests/validate_outputs.py", + "behavior": "six-pair shards with exact original bytes" + }, + { + "case_id": "CASE_3", + "instruction_evidence": "score numerator and denominator", + "validator": "tests/validate_outputs.py", + "behavior": "score numerator and denominator" + }, + { + "case_id": "CASE_4", + "instruction_evidence": "batch loader and one/two/three-rank partition", + "validator": "tests/validate_outputs.py", + "behavior": "batch loader and one/two/three-rank partition" + }, + { + "case_id": "CASE_5", + "instruction_evidence": "new pair, orphan samples, caption edit, stale shard", + "validator": "tests/validate_enhanced.py", + "behavior": "new pair, orphan samples, caption edit, stale shard" + } +] diff --git a/task_036/tests/review_ranks.py b/task_036/tests/review_ranks.py new file mode 100644 index 0000000000000000000000000000000000000000..547a2ea640c4c80bd8bbb00aa29923333dcdcd9c --- /dev/null +++ b/task_036/tests/review_ranks.py @@ -0,0 +1,5 @@ +from validate_outputs import check_workspace +from pathlib import Path + +check_workspace(Path.cwd()) +print("rank partition review passed") diff --git a/task_036/tests/test.sh b/task_036/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..26dcebef0d4445da210290b5c59914a84224a556 --- /dev/null +++ b/task_036/tests/test.sh @@ -0,0 +1,87 @@ +#!/usr/bin/env bash +set -euo pipefail +set +e +TASK_ID='52' +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +source "$TEST_DIR/_shared/static_enhancer.sh" +OFFLINE_PYTHONPATH="$TEST_DIR/_offline${PYTHONPATH:+:$PYTHONPATH}" +RUN_ENV=(env PYTHONHASHSEED=0 PYTHONPATH="$OFFLINE_PYTHONPATH" HF_DATASETS_OFFLINE=1 TRANSFORMERS_OFFLINE=1 WANDB_MODE=offline NO_PROXY='' HTTP_PROXY='http://127.0.0.1:9' HTTPS_PROXY='http://127.0.0.1:9' ALL_PROXY='http://127.0.0.1:9') +LOG_DIR="/logs/verifier" +if ! mkdir -p "$LOG_DIR" 2>/dev/null; then LOG_DIR="logs/verifier"; mkdir -p "$LOG_DIR"; fi +REWARD_FILE="$LOG_DIR/reward.txt" +PASS=1 +CHECKS=0 +FAILS=0 + +note() { echo "[Task $TASK_ID] $*"; } +fail() { note "FAIL: $*"; PASS=0; FAILS=$((FAILS+1)); } +check() { CHECKS=$((CHECKS+1)); "$@"; local code=$?; if [ $code -ne 0 ]; then fail "$*"; fi; } +have_any() { local pattern="$1"; compgen -G "$pattern" >/dev/null 2>&1; } +grep_any() { local pattern="$1"; shift; grep -REiq -- "$pattern" "$@" 2>/dev/null; } +source_files() { find . -type f \( -name '*.html' -o -name '*.js' -o -name '*.jsx' -o -name '*.ts' -o -name '*.tsx' -o -name '*.css' -o -name '*.py' -o -name '*.go' -o -name '*.swift' -o -name '*.svg' \) ! -path './tests/*' ! -path './logs/*'; } + +note "enhanced deterministic verifier start" +static_enhance_check "${TASK_ID}" "$(pwd)" +if [ ! -e 'data/dataset/000001.jpg' ]; then + fail "benchmark input asset missing: data/dataset/000001.jpg" +fi +if [ ! -e 'data/dataset/000001.txt' ]; then + fail "benchmark input asset missing: data/dataset/000001.txt" +fi +if [ ! -e 'data/dataset/000002.jpg' ]; then + fail "benchmark input asset missing: data/dataset/000002.jpg" +fi +if [ ! -e 'data/dataset/000002.txt' ]; then + fail "benchmark input asset missing: data/dataset/000002.txt" +fi +if [ ! -e 'data/dataset/000003.jpg' ]; then + fail "benchmark input asset missing: data/dataset/000003.jpg" +fi +if [ ! -e 'data/dataset/000003.txt' ]; then + fail "benchmark input asset missing: data/dataset/000003.txt" +fi +if [ ! -e 'data/dataset/000004.jpg' ]; then + fail "benchmark input asset missing: data/dataset/000004.jpg" +fi +if [ ! -e 'data/dataset/000004.txt' ]; then + fail "benchmark input asset missing: data/dataset/000004.txt" +fi +mapfile -t py_files < <(find . -type f -name '*.py' ! -path './tests/*') +if [ ${#py_files[@]} -eq 0 ]; then fail "no Python source found"; fi +if command -v python3 >/dev/null 2>&1; then + for f in "${py_files[@]}"; do timeout 30s "${RUN_ENV[@]}" python3 -m py_compile "$f" >/tmp/harbor_py_compile.log 2>&1 || fail "python compile failed: $f"; done +fi +if command -v python3 >/dev/null 2>&1; then + check test -s solve.py + timeout 60s "${RUN_ENV[@]}" python3 solve.py >/tmp/harbor_data_run.log 2>&1 || fail "solve.py did not run successfully" +fi +check test -s 'dataloader_demo.py' +check test -s 'distributed_demo.py' +check test -s 'score.txt' +check test -s 'shards/dataset-000000.tar' + +if command -v python3 >/dev/null 2>&1; then + check timeout 180s "${RUN_ENV[@]}" python3 "$TEST_DIR/validate_outputs.py" + check timeout 180s "${RUN_ENV[@]}" python3 "$TEST_DIR/validate_enhanced.py" +else + fail "python3 unavailable for output validation" +fi +# BEGIN AAAV_DYNAMIC_TEST +if [ -f "$TEST_DIR/validate_aaav_dynamic.js" ]; then + if command -v node >/dev/null 2>&1; then + check timeout 90s "${RUN_ENV[@]}" node "$TEST_DIR/validate_aaav_dynamic.js" + else + note "AAAV dynamic validation skipped (node unavailable in this runtime)" + fi +fi +# END AAAV_DYNAMIC_TEST +check python3 "$TEST_DIR/review_ranks.py" +note "checks=$CHECKS fails=$FAILS" +if [ "$PASS" -eq 1 ]; then + echo 1 > "$REWARD_FILE" + note "PASS" + exit 0 +fi +echo 0 > "$REWARD_FILE" +note "FAIL" +exit 0 diff --git a/task_036/tests/validate_aaav_dynamic.js b/task_036/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..1ae7fef1eb49d4f28a121ada1668c7661ce5bf49 --- /dev/null +++ b/task_036/tests/validate_aaav_dynamic.js @@ -0,0 +1,71 @@ +const fs = require('fs'); +const path = require('path'); +const child_process = require('child_process'); +const TASK_ID = 52; +const LANGUAGE = "python"; +const EXPECTED = [ + "dataloader_demo.py", + "score.txt", + "shards/dataset-000000.tar" +]; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { if (!condition) throw new Error(message); } +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} +function globToRe(glob) { + return new RegExp('^' + glob.split('*').map(x => x.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') + '$'); +} +function existsPattern(files, pat) { + const re = globToRe(String(pat).replace(/\\/g, '/')); + return files.some(f => re.test(f.replace(/\\/g, '/')) || f.replace(/\\/g, '/').endsWith(String(pat).replace(/\\/g, '/'))); +} + +const files = walk(process.cwd()); +assert(files.length > 0, 'candidate workspace should contain files'); +const rel = files.map(f => path.relative(process.cwd(), f)); +const source = files.filter(f => /\.(js|jsx|ts|tsx|css|html|py|go|md|svg)$/i.test(f)); +assert(source.length > 0, 'candidate should contain source or report files'); + +if (LANGUAGE === 'go') { + const goFiles = files.filter(f => f.endsWith('.go')); + assert(goFiles.length > 0, 'go task should contain .go files'); + try { + child_process.execFileSync('go', ['test', './...'], { cwd: process.cwd(), stdio: 'pipe', timeout: 120000 }); + } catch (err) { + // The benchmark's own verifier owns task-specific Go behavior. Here we + // keep go test as an opportunistic runtime probe so local module/path + // differences do not create false negatives. + const msg = Buffer.concat([err.stdout || Buffer.alloc(0), err.stderr || Buffer.alloc(0)]).toString().slice(0, 500); + console.warn('go test ./... probe failed but is non-fatal: ' + msg); + } +} else if (LANGUAGE === 'python') { + const pyFiles = files.filter(f => f.endsWith('.py')); + assert(pyFiles.length > 0 || rel.some(f => /\.(html|csv|json|txt|md|png)$/i.test(f)), 'python/data task should contain scripts or produced artifacts'); + for (const f of pyFiles.slice(0, 20)) { + child_process.execFileSync('python3', ['-m', 'py_compile', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); + } +} else { + for (const f of files.filter(f => f.endsWith('.js')).slice(0, 20)) { + child_process.execFileSync('node', ['--check', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); + } +} + +for (const pat of EXPECTED) { + assert(existsPattern(rel, pat), 'missing expected artifact pattern after verifier: ' + pat); +} + +console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); diff --git a/task_036/tests/validate_enhanced.py b/task_036/tests/validate_enhanced.py new file mode 100644 index 0000000000000000000000000000000000000000..25326b5dc6c6b3cb5159134a7c226e416402a5d1 --- /dev/null +++ b/task_036/tests/validate_enhanced.py @@ -0,0 +1,28 @@ +"""Mutation checks: new pairs, incomplete samples, changed captions, stale shard cleanup.""" + +from pathlib import Path +import shutil +import tempfile + +from validate_outputs import check_workspace, expected + + +ROOT = Path.cwd() +with tempfile.TemporaryDirectory(prefix="task052-mutation-") as tmp: + workspace = Path(tmp) + shutil.copytree(ROOT, workspace, dirs_exist_ok=True, ignore=shutil.ignore_patterns('tests', 'logs', 'shards', '__pycache__', 'node_modules')) + dataset = workspace / "data" / "dataset" + shutil.copy2(dataset / "000001.jpg", dataset / "000777.jpg") + (dataset / "000777.txt").write_text("a newly added complete sample\n", encoding="utf-8") + shutil.copy2(dataset / "000002.jpg", dataset / "000888.jpg") + (dataset / "000889.txt").write_text("no matching image\n", encoding="utf-8") + (dataset / "000003.txt").write_text("changed caption during verifier\n", encoding="utf-8") + shard_dir = workspace / "shards" + shard_dir.mkdir() + (shard_dir / "dataset-999999.tar").write_bytes(b"stale") + pairs, total = expected(workspace) + assert "000777" in pairs and "000888" not in pairs and "000889" not in pairs + check_workspace(workspace) + assert total >= len(pairs) + 2 + assert not (shard_dir / "dataset-999999.tar").exists(), "old shard was not cleaned" +print("mutation cases passed") diff --git a/task_036/tests/validate_outputs.py b/task_036/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..035224a5799eeac13350210b98f3dffe62e69556 --- /dev/null +++ b/task_036/tests/validate_outputs.py @@ -0,0 +1,81 @@ +"""Runtime checks for all shards, original bytes, score, and runnable loaders.""" + +import json +import math +from pathlib import Path +import re +import subprocess +import sys +import tarfile +import tempfile +import shutil + +from PIL import Image + + +ROOT = Path.cwd() + + +def run(workspace, *args): + result = subprocess.run([sys.executable, *args], cwd=workspace, capture_output=True, text=True, timeout=60) + assert result.returncode == 0, f"{' '.join(args)} failed: {result.stderr or result.stdout}" + return result.stdout + + +def expected(workspace): + dataset = workspace / "data" / "dataset" + images = {p.stem for p in dataset.glob("*.jpg")} + captions = {p.stem for p in dataset.glob("*.txt")} + for path in dataset.glob("*.jpg"): + with Image.open(path) as image: + image.verify() + return sorted(images & captions), len(images | captions) + + +def check_workspace(workspace): + pairs, total = expected(workspace) + assert pairs, "no complete image-caption pairs" + run(workspace, "solve.py") + score = (workspace / "score.txt").read_text(encoding="utf-8") + match = re.search(r"(\d+)\s*/\s*(\d+)", score) + assert match and (int(match[1]), int(match[2])) == (len(pairs), total), "incorrect score numerator/denominator" + shards = sorted((workspace / "shards").glob("dataset-*.tar")) + assert len(shards) == math.ceil(len(pairs) / 6), "incorrect shard count" + assert [p.name for p in shards] == [f"dataset-{i:06d}.tar" for i in range(len(shards))], "shard naming gap" + all_keys = [] + for shard_index, path in enumerate(shards): + group = pairs[shard_index * 6:(shard_index + 1) * 6] + with tarfile.open(path) as archive: + members = archive.getmembers() + names = [m.name for m in members] + expected_names = [f"{key}.{suffix}" for key in group for suffix in ("jpg", "txt")] + assert sorted(names) == sorted(expected_names), f"wrong pair membership in {path.name}" + assert len(names) == len(set(names)), "duplicate tar member" + for member in members: + assert member.isfile() and "/" not in member.name and ".." not in member.name + assert archive.extractfile(member).read() == (workspace / "data" / "dataset" / member.name).read_bytes(), f"payload changed: {member.name}" + all_keys.extend(group) + assert all_keys == pairs + # Consumers must read packaged shards even if the raw source is unavailable. + with tempfile.TemporaryDirectory(prefix='raw-pairs-') as directory: + dataset = workspace / 'data' / 'dataset' + saved = Path(directory) / 'dataset' + shutil.move(str(dataset), str(saved)) + try: + for batch_size in (1, 4, 7): + lines = run(workspace, "dataloader_demo.py", "--batch-size", str(batch_size)).splitlines() + batches = [json.loads(line) for line in lines] + assert batches == [pairs[offset:offset+batch_size] for offset in range(0, len(pairs), batch_size)], 'batch loader must honor batch size and include the final remainder' + for world_size in (1, 2, 3, len(pairs) + 1): + ranks = range(world_size) if world_size <= 3 else (0, world_size - 1) + for rank in ranks: + got = run(workspace, "distributed_demo.py", "--rank", str(rank), "--world-size", str(world_size)).splitlines() + assert got == pairs[rank::world_size], f"rank {rank}/{world_size} partition wrong" + finally: + shutil.move(str(saved), str(dataset)) + return pairs + + +if __name__ == "__main__": + check_workspace(ROOT) + print("all shard, JPEG, batch, and rank checks passed") diff --git a/task_037/acceptance_checklist.json b/task_037/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..6e3d802c969019a980913e07cd880803f3febb9f --- /dev/null +++ b/task_037/acceptance_checklist.json @@ -0,0 +1,20 @@ +{ + "task_id": 58, + "category": "application_development", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Implements the requested domain workflow end to end.", + "Includes maintainable separation of concerns and meaningful tests when the task asks for them." + ], + "input_assets": [ + "index.html" + ], + "expected_outputs": [], + "risk_notes": [ + "A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_037/environment/Dockerfile b/task_037/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_037/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_037/environment/code/index.html b/task_037/environment/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..60008f4f065fd09afa6d3885b70958eeff97097a --- /dev/null +++ b/task_037/environment/code/index.html @@ -0,0 +1,18 @@ + + + + + +图片上传 + + +

      图片上传页面

      +
      + +
      + + diff --git a/task_037/environment/docker-compose.yaml b/task_037/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_037/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_037/instruction.md b/task_037/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b07d0d7665ca7f06affbb0bcd6cff6d52d3587cd --- /dev/null +++ b/task_037/instruction.md @@ -0,0 +1,17 @@ +# Build an offline image gallery with upload and zoom + +Replace the starter `index.html` with a single front-end page that works directly in the browser without a server or network. + +## Interface + +- Use a multiple-file input with `data-testid="image-upload"` that accepts images the browser can decode, including PNG, SVG, JPEG, and WebP. +- Render each gallery image as an `` inside `data-testid="image-list"`, or mark the images with `data-testid="uploaded-image"`. +- Keep the original images in an in-memory store. Provide `data-testid="image-store"` and `window.__getImageStore()`, which returns an independent array of the original base64 image data URLs, with the original MIME types and file bytes, in upload order. Gallery and preview images may use data URLs or object URLs as long as they display the corresponding uploaded content. +- Mark the preview with `data-testid="image-preview"`, display the selected image in an ``, and place the zoom controls inside the preview, with `data-testid="zoom-button"` on at least one. Provide an upload notice region from initial load using `data-testid="status"`, `role="status"` or `role="alert"`. + +## Acceptance Checklist + +- Multiple selected images render and retain their original bytes and MIME types in selection order, even when files use different image formats. Later selections append without losing prior images. +- Reject non-image files without adding them to the gallery or store. Show a new visible invalid-file message rather than leaving a success message in place. +- Clicking a gallery image opens a preview containing that exact image, including when switching between different images. Zoom controls visibly enlarge and reduce the preview. +- Changing the observer's returned array cannot alter the actual stored images. The page renders and all interactions work offline. diff --git a/task_037/quality_notes.md b/task_037/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..177ca6b7cbc2fc2f6d24f4876159792c81d4b86b --- /dev/null +++ b/task_037/quality_notes.md @@ -0,0 +1,3 @@ +# Quality Notes + +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. \ No newline at end of file diff --git a/task_037/solution/README.md b/task_037/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_037/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_037/solution/code/index.html b/task_037/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..c12610634d9b5dcc448cb8db17ba6956b7f5e52c --- /dev/null +++ b/task_037/solution/code/index.html @@ -0,0 +1,122 @@ + + + + + +Image Upload + + + +

      Image Gallery

      +
      +
      YOUR WORKSPACE

      Collect Every Great Image

      Upload, preview, and zoom in on images to keep your visual assets organized.

      +
      + +

      Add images to your workspace

      + Select multiple images at once, then click a thumbnail to view it full size.
      + +

      No images uploaded

      +
      + + + + + + +
      + + +
      + preview +
      + + + +
      +
      + + + + diff --git a/task_037/solution/solve.sh b/task_037/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_037/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_037/task.toml b/task_037/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_037/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_037/task_meta.json b/task_037/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..00fc4171a8121779abfd11bfb9d171c64a825bca --- /dev/null +++ b/task_037/task_meta.json @@ -0,0 +1,22 @@ +{ + "task_id": 58, + "task_category": "application_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 1, + "language": "javascript", + "tool_files_from_selected_trace": [ + "Makefile", + "common.ts", + "index.css", + "index.ts", + "index.tsx" + ], + "input_assets": [ + "index.html" + ], + "expected_outputs": [], + "source_row_id": 348, + "repair_revision": "2026-09-29", + "instruction_sha256": "229b79a5a5022845046c6fc70e8ab9407dc4070ff96817dcc0b422fe90d2ebc8" +} diff --git a/task_037/tests/_shared/contract_checker.js b/task_037/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_037/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_037/tests/_shared/static_enhancer.sh b/task_037/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_037/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_037/tests/enhancement_cases.json b/task_037/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..9d7f0830f245399628819669581b4939f8016221 --- /dev/null +++ b/task_037/tests/enhancement_cases.json @@ -0,0 +1,26 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "提供一个文件选择控件,用户可选择一张或多张图片上传;\n- 上传的图片渲染到页面的图库/列表中展示;", + "validator": "validate_enhanced_cases.js#caseMultipleUpload", + "behavior": "选择 PNG、JPEG 和 WebP 后,图库按选择顺序加载三张可解码图片,存储保留原始 MIME 类型和字节,下一次上传追加。" + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "点击某张图片可打开预览", + "validator": "validate_enhanced_cases.js#casePreview", + "behavior": "点击已上传图片后,预览可见且与所选原图的解码内容一致。图片来源可以是 data URL 或对象 URL。" + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "并支持基础的放大/缩小(缩放)。", + "validator": "validate_enhanced_cases.js#caseZoomBothDirections", + "behavior": "预览中的控件能分别产生可观察的放大与缩小效果。" + }, + { + "case_id": "ENHANCED_CASE_4", + "instruction_evidence": "多张图片按选择顺序保存,点击后预览对应图片,拒绝非图片,并返回独立的存储副本。", + "validator": "validate_enhanced_cases.js#caseOrderedStoreAndFileType", + "behavior": "顺序加载内容不同的 SVG,核对可见图片顺序、原始存储、复制隔离和第二张图预览,并拒绝文本文件、显示新提示。" + } +] diff --git a/task_037/tests/test.sh b/task_037/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ab2150eb79f6f15b53d20b21738b84bbe0d8003 --- /dev/null +++ b/task_037/tests/test.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_ui_behavior.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_037/tests/validate_aaav_dynamic.js b/task_037/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..11d26d01036573f20c8ab778cabff1d390fd66b1 --- /dev/null +++ b/task_037/tests/validate_aaav_dynamic.js @@ -0,0 +1,153 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 58; +const KIND = "browser"; +const TESTIDS = [ + "image-upload", + "image-store", + "image-preview", + "zoom-button" +]; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_037/tests/validate_browser_smoke.js b/task_037/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_037/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_037/tests/validate_enhanced_cases.js b/task_037/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..3638648be4e2e1db7fb6dfd953dd7c9a7aa455e3 --- /dev/null +++ b/task_037/tests/validate_enhanced_cases.js @@ -0,0 +1,327 @@ +const path = require('path'); +const fs = require('fs'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const ACTION_TIMEOUT_MS = 5_000; +const CASE_TIMEOUT_MS = 15_000; +const GALLERY_IMAGES = '[data-testid="image-list"] img, img[data-testid="uploaded-image"]'; +const PREVIEW_IMAGES = '[data-testid="image-preview"] img'; +process.env.HARBOR_TEST_SEED = '58001'; +const PNG = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFgwJ/luznTQAAAABJRU5ErkJggg==', + 'base64' +); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +async function within(ms, label, work) { + let timer; + try { + return await Promise.race([ + work(), + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms); + }), + ]); + } finally { + clearTimeout(timer); + } +} + +async function freshPage(browser) { + const context = await browser.newContext({ offline: true, serviceWorkers: 'block' }); + const page = await context.newPage(); + page.setDefaultTimeout(ACTION_TIMEOUT_MS); + page.setDefaultNavigationTimeout(ACTION_TIMEOUT_MS); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { + waitUntil: 'domcontentloaded', + timeout: ACTION_TIMEOUT_MS, + }); + return { context, page }; +} + +async function capture(page, name) { + fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + await page.screenshot({path: `/logs/verifier/visual-audit/${name}.png`, fullPage: true}); +} + +async function upload(page, names) { + const files = names.map(name => ({ name, mimeType: 'image/png', buffer: PNG })); + await page.locator('[data-testid="image-upload"]').setInputFiles(files, { timeout: ACTION_TIMEOUT_MS }); + return originalDataUrls(files); +} + +async function rasterSamples(browser) { + const fixturePage = await browser.newPage({ offline: true }); + try { + const samples = await fixturePage.evaluate(() => { + const canvas = document.createElement('canvas'); + canvas.width = 12; + canvas.height = 8; + const context = canvas.getContext('2d'); + return [ + { name: 'photo.jpg', mimeType: 'image/jpeg', color: 'navy' }, + { name: 'illustration.webp', mimeType: 'image/webp', color: 'gold' }, + ].map(({ name, mimeType, color }) => { + context.fillStyle = color; + context.fillRect(0, 0, canvas.width, canvas.height); + return { name, mimeType, dataUrl: canvas.toDataURL(mimeType) }; + }); + }); + return samples.map(({ name, mimeType, dataUrl }) => { + const prefix = 'data:' + mimeType + ';base64,'; + assert(dataUrl.startsWith(prefix), 'test browser failed to encode ' + mimeType); + return { name, mimeType, buffer: Buffer.from(dataUrl.slice(prefix.length), 'base64') }; + }); + } finally { + await fixturePage.close(); + } +} + +async function assertPickerAllows(input, files) { + const accept = await input.getAttribute('accept'); + if (!accept || !accept.trim()) return; + const tokens = accept.toLowerCase().split(',').map(token => token.trim()); + for (const { name, mimeType } of files) { + const suffix = path.extname(name).toLowerCase(); + assert( + tokens.includes(mimeType) || tokens.includes('image/*') || tokens.includes(suffix), + 'the file picker excludes the supported image format ' + mimeType + ); + } +} + +function originalDataUrls(files) { + return files.map(({ mimeType, buffer }) => 'data:' + mimeType + ';base64,' + buffer.toString('base64')); +} + +async function fixturePixels(page, sources) { + const fixturePage = await page.context().newPage(); + try { + return await fixturePage.evaluate(urls => { + const canvas = new OffscreenCanvas(16, 16); + const context = canvas.getContext('2d', { willReadFrequently: true }); + return Promise.all(urls.map(async url => { + const image = new Image(); + image.src = url; + await image.decode(); + context.clearRect(0, 0, canvas.width, canvas.height); + context.drawImage(image, 0, 0, canvas.width, canvas.height); + return [...context.getImageData(0, 0, canvas.width, canvas.height).data]; + })); + }, sources); + } finally { + await fixturePage.close(); + } +} + +async function waitForRenderedImages(page, selector, sources, ordered) { + // Decode trusted fixtures in a blank page so application CSP cannot affect them. + const expected = await fixturePixels(page, sources); + const result = await page.waitForFunction(({ selector, expected, ordered }) => { + const images = [...document.querySelectorAll(selector)]; + if (ordered && images.length !== expected.length) return false; + const isVisibleImage = image => image.complete && image.naturalWidth > 0 + && image.naturalHeight > 0 && image.checkVisibility({ opacityProperty: true, visibilityProperty: true }) + && image.getBoundingClientRect().width > 0 && image.getBoundingClientRect().height > 0; + if (!images.some(isVisibleImage)) return false; + + const canvas = document.createElement('canvas'); + canvas.width = canvas.height = 16; + const context = canvas.getContext('2d', { willReadFrequently: true }); + const sample = image => { + context.clearRect(0, 0, canvas.width, canvas.height); + context.drawImage(image, 0, 0, canvas.width, canvas.height); + return context.getImageData(0, 0, canvas.width, canvas.height).data; + }; + const matches = (image, pixels) => { + if (!isVisibleImage(image)) return false; + const source = image.currentSrc || image.src; + if (!source.startsWith('data:') && !source.startsWith('blob:')) return false; + // The decoded bitmap remains available even after its object URL is revoked. + const actual = sample(image); + let difference = 0; + for (let index = 0; index < pixels.length; index += 1) difference += Math.abs(actual[index] - pixels[index]); + return difference / pixels.length <= 5; + }; + if (ordered) return images.every((image, index) => matches(image, expected[index])); + // A truthy one-based index lets the zoom check measure the matching image. + return images.findIndex(image => matches(image, expected[0])) + 1; + }, { selector, expected, ordered }, { timeout: ACTION_TIMEOUT_MS }); + try { + return await result.jsonValue(); + } finally { + await result.dispose(); + } +} + +async function waitForDecodedGallery(page, expected) { + await waitForRenderedImages(page, GALLERY_IMAGES, expected, true).catch(error => { + throw new Error('the gallery did not decode all selected images in order', { cause: error }); + }); +} + +async function waitForPreviewImage(page, expected) { + const index = await waitForRenderedImages(page, PREVIEW_IMAGES, [expected], false).catch(error => { + throw new Error('preview should visibly show the uploaded image that was clicked', { cause: error }); + }); + return page.locator(PREVIEW_IMAGES).nth(index - 1); +} + +// ENHANCED_CASE_1: mixed browser-decodable formats retain original bytes, MIME types and order. +async function caseMultipleUpload(browser) { + const { context, page } = await freshPage(browser); + try { + const input = page.locator('[data-testid="image-upload"]'); + assert(await input.getAttribute('type') === 'file', 'image-upload must be a file input'); + assert(await input.getAttribute('multiple') !== null, 'image-upload must allow multiple files'); + const files = [{ name: 'graphic.png', mimeType: 'image/png', buffer: PNG }, ...await rasterSamples(browser)]; + await assertPickerAllows(input, files); + await input.setInputFiles(files); + const expected = originalDataUrls(files); + await waitForDecodedGallery(page, expected); + const saved = await page.evaluate(() => window.__getImageStore()); + assert(JSON.stringify(saved) === JSON.stringify(expected), 'store must preserve PNG, JPEG and WebP uploads byte-for-byte in selection order'); + await upload(page, ['fourth.png']); + expected.push(expected[0]); + await waitForDecodedGallery(page, expected); + const more = await page.evaluate(() => window.__getImageStore()); + assert(JSON.stringify(more) === JSON.stringify(expected), 'a later upload must append without changing earlier images'); + } finally { + await context.close(); + } +} + +// ENHANCED_CASE_2: clicking an uploaded image opens a preview of that exact image. +async function casePreview(browser) { + const { context, page } = await freshPage(browser); + try { + const [expected] = await upload(page, ['preview-source.png']); + await waitForDecodedGallery(page, [expected]); + await page.locator(GALLERY_IMAGES).first().click(); + await waitForPreviewImage(page, expected); + } finally { + await context.close(); + } +} + +async function previewArea(image) { + const box = await image.boundingBox(); + assert(box, 'preview should visibly show the selected image'); + return box.width * box.height; +} + +// ENHANCED_CASE_3: preview controls provide observable enlargement and reduction. +async function caseZoomBothDirections(browser) { + const { context, page } = await freshPage(browser); + try { + const [expected] = await upload(page, ['zoom-source.png']); + await waitForDecodedGallery(page, [expected]); + const image = page.locator(GALLERY_IMAGES).first(); + await image.click(); + const preview = page.locator('[data-testid="image-preview"]'); + let previewImage = await waitForPreviewImage(page, expected); + assert(await preview.getByTestId('zoom-button').count() > 0, 'required zoom control is missing'); + + let previous = await previewArea(previewImage); + let enlarged = false; + let reduced = false; + const buttons = preview.locator('button, [role="button"]'); + const count = await buttons.count(); + for (let round = 0; round < 3 && !(enlarged && reduced); round += 1) { + for (let i = 0; i < count && !(enlarged && reduced); i += 1) { + const button = buttons.nth(i); + if (!(await button.isVisible())) continue; + await button.click({ timeout: ACTION_TIMEOUT_MS }); + await page.waitForTimeout(220); + if (!(await preview.isVisible())) { + await image.click({ timeout: ACTION_TIMEOUT_MS }); + previewImage = await waitForPreviewImage(page, expected); + previous = await previewArea(previewImage); + continue; + } + const current = await previewArea(previewImage); + const tolerance = Math.max(0.001, previous * 0.001); + enlarged ||= current > previous + tolerance; + reduced ||= current < previous - tolerance; + previous = current; + } + } + assert(enlarged, 'a preview control should enlarge the uploaded image'); + assert(reduced, 'a preview control should reduce the uploaded image'); + } finally { + await context.close(); + } +} + +// ENHANCED_CASE_4: distinct uploads retain selection order and reject non-image data. +async function caseOrderedStoreAndFileType(browser) { + const { context, page } = await freshPage(browser); + try { + const colors = ['red', 'green', 'blue']; + const inputs = colors.map((color, index) => { + const bytes = Buffer.from(``); + return { name: `unique-${index}.svg`, mimeType: 'image/svg+xml', buffer: bytes }; + }); + const input = page.locator('[data-testid="image-upload"]'); + await assertPickerAllows(input, inputs); + await input.setInputFiles(inputs); + const expected = originalDataUrls(inputs); + await waitForDecodedGallery(page, expected); + const saved = await page.evaluate(() => window.__getImageStore()); + assert(JSON.stringify(saved) === JSON.stringify(expected), 'store must preserve the selected distinct-image order'); + const copied = await page.evaluate(() => { + const exposed = window.__getImageStore(); + exposed.splice(0, exposed.length, 'corrupted'); + return window.__getImageStore(); + }); + assert(JSON.stringify(copied) === JSON.stringify(expected), 'observer must return a copy, not a mutable store reference'); + await capture(page, 'ordered-gallery'); + const status = page.locator('[data-testid="status"], [role="status"], [role="alert"]').first(); + const previousStatus = await status.innerText(); + await page.locator('[data-testid="image-upload"]').setInputFiles({ + name: 'not-an-image.txt', mimeType: 'text/plain', buffer: Buffer.from('not image pixels') + }); + await page.waitForFunction(previous => { + const status = document.querySelector('[data-testid="status"], [role="status"], [role="alert"]'); + return status && status.innerText.trim() && status.innerText !== previous; + }, previousStatus); + const after = await page.evaluate(() => window.__getImageStore()); + assert(JSON.stringify(after) === JSON.stringify(expected), 'non-image files must not be saved as images'); + assert(await status.isVisible(), 'invalid upload needs a visible new status'); + await capture(page, 'invalid-file-feedback'); + const images = page.locator(GALLERY_IMAGES); + assert(await images.count() === expected.length, 'non-image files must not change the gallery'); + await images.nth(1).click(); + await waitForPreviewImage(page, expected[1]); + await capture(page, 'second-image-preview'); + } finally { + await context.close(); + } +} + +const enhancedCases = { + ENHANCED_CASE_1: caseMultipleUpload, + ENHANCED_CASE_2: casePreview, + ENHANCED_CASE_3: caseZoomBothDirections, + ENHANCED_CASE_4: caseOrderedStoreAndFileType, +}; + +(async () => { + const requested = process.argv[2]; + assert(!requested || enhancedCases[requested], `unknown enhanced case: ${requested}`); + const browser = await chromium.launch({ headless: true, timeout: ACTION_TIMEOUT_MS }); + try { + const entries = requested ? [[requested, enhancedCases[requested]]] : Object.entries(enhancedCases); + for (const [caseId, run] of entries) await within(CASE_TIMEOUT_MS, caseId, () => run(browser)); + console.log(`task 58 enhanced cases passed (${entries.length}/${entries.length})`); + } finally { + await browser.close(); + } +})().catch((err) => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_037/tests/validate_semantics.js b/task_037/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_037/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_037/tests/validate_ui_behavior.js b/task_037/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..fc30f842aa7795999c2b8a11933170d56070b173 --- /dev/null +++ b/task_037/tests/validate_ui_behavior.js @@ -0,0 +1,46 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1000, height: 720 } }); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + + // Upload control must exist. + const upload = page.locator('[data-testid="image-upload"]'); + if (!(await upload.count())) throw new Error('page should expose an image upload control'); + + // A local store abstraction is required for the fixture. + const hasStore = await page.locator('[data-testid="image-store"], [data-storage], [data-testid*="storage"]').count(); + if(!await page.evaluate(()=>typeof window.__getImageStore==='function'))throw Error('image storage observer missing'); + + // Preview + zoom controls are required. + const preview = page.locator('[data-testid="image-preview"]'); + const zoom = page.locator('[data-testid="zoom-button"], [data-testid*="zoom"], button[aria-label*="zoom" i]'); + if (!(await preview.count()) || !(await zoom.count())) throw new Error('image preview and zoom controls are required'); + + // Simulate an upload and confirm the image is rendered in the gallery/list. + const dataUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFgwJ/luznTQAAAABJRU5ErkJggg=='; + await page.evaluate(async src => { + const blob = await (await fetch(src)).blob(); + const file = new File([blob], 'sample.png', { type: 'image/png' }); + const input = document.querySelector('[data-testid="image-upload"]'); + const dt = new DataTransfer(); + dt.items.add(file); + input.files = dt.files; + input.dispatchEvent(new Event('change', { bubbles: true })); + }, dataUrl); + await page.waitForFunction(() => window.__getImageStore().length === 1, null, {timeout: 5000}); + + const renderedImage = await page.locator( + '[data-testid="image-list"] img, [data-testid="uploaded-image"], [data-testid*="gallery"] img, main img' + ).count(); + if (!renderedImage) throw new Error('uploaded image should render in the gallery/list'); + + // Clicking an uploaded image should open the preview modal. + const firstImg = page.locator('[data-testid="uploaded-image"], [data-testid="image-list"] img, main img').first(); + await firstImg.click(); + await preview.first().waitFor({state: 'visible', timeout: 5000}); + + await browser.close(); +})().catch(err => { console.error(err && err.stack || err); process.exit(1); }); diff --git a/task_038/acceptance_checklist.json b/task_038/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..01ea9dc1a46194aff82e7d8c80ff084b749b3422 --- /dev/null +++ b/task_038/acceptance_checklist.json @@ -0,0 +1,20 @@ +{ + "task_id": 59, + "category": "application_development", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Implements the requested domain workflow end to end.", + "Includes maintainable separation of concerns and meaningful tests when the task asks for them." + ], + "input_assets": [ + "index.html" + ], + "expected_outputs": [], + "risk_notes": [ + "A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_038/environment/Dockerfile b/task_038/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_038/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_038/environment/code/index.html b/task_038/environment/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..09e34c9d4e72b30e5719bec89d837375b79cc6c0 --- /dev/null +++ b/task_038/environment/code/index.html @@ -0,0 +1,19 @@ + + + + + +图片上传 · 自动加水印 + + +

      图片上传页面 · 自动加水印

      +
      + +
      + + diff --git a/task_038/environment/docker-compose.yaml b/task_038/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_038/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_038/instruction.md b/task_038/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..519b779963c120a921ce6ac9e28d577254bd529b --- /dev/null +++ b/task_038/instruction.md @@ -0,0 +1,16 @@ +# Add a configurable text watermark to uploaded images + +Replace the starter `index.html` with a single offline front-end page that automatically watermarks a locally selected image and displays the result. + +## Interface + +- Use a file input with `data-testid="image-upload"` and a visible result canvas with `data-testid="watermark-canvas"`. +- Use `data-testid` values `wm-text` for the text control (default `Answer`), `wm-size` for font size (including 16 and 32), `wm-opacity` for opacity (0 through 1), and `wm-position` for position (including `top-left`, `center` and `bottom-right`). +- Keep each original and its corresponding result separately in memory. Expose `window.__getImageStore()` returning an independent copy of `{originals: [...], watermarked: [...]}`, two corresponding arrays of data URLs. + +## Acceptance Checklist + +- Uploading draws the image at its original aspect ratio and applies the default watermark without another action. +- Editing a setting updates the visible result within five seconds. Changing the text changes the lettering; a larger font enlarges it; lower opacity makes it fainter; position moves it to the selected area. At opacity zero only the original image is visible. +- Store the actual canvas result while leaving original bytes unchanged, including when editing or restoring settings. Mutating the returned store snapshot cannot change either underlying list. +- The page loads and the complete upload and editing workflow works without a network. diff --git a/task_038/quality_notes.md b/task_038/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..177ca6b7cbc2fc2f6d24f4876159792c81d4b86b --- /dev/null +++ b/task_038/quality_notes.md @@ -0,0 +1,3 @@ +# Quality Notes + +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. \ No newline at end of file diff --git a/task_038/solution/README.md b/task_038/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_038/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_038/solution/code/index.html b/task_038/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..a6a710b7f5b523ecf0fb11bf962d7748dbcd69c2 --- /dev/null +++ b/task_038/solution/code/index.html @@ -0,0 +1,150 @@ + + + + + +Image Upload · Automatic Watermark + + + +

      Image Upload · Automatic Watermark

      +
      +
      +

      Select an image to upload. The system adds a text watermark automatically while preserving the original aspect ratio.

      + + +
      + + + + +
      + +

      No image uploaded

      + + + + + +
      + +
      +
      +
      + + + + diff --git a/task_038/solution/solve.sh b/task_038/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_038/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_038/task.toml b/task_038/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_038/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_038/task_meta.json b/task_038/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..388221f167b8a2f758f088bb11598861428a4817 --- /dev/null +++ b/task_038/task_meta.json @@ -0,0 +1,18 @@ +{ + "task_id": 59, + "task_category": "application_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 1, + "language": "javascript", + "tool_files_from_selected_trace": [ + "index.html" + ], + "input_assets": [ + "index.html" + ], + "expected_outputs": [], + "source_row_id": 354, + "repair_revision": "2026-09-29", + "instruction_sha256": "92e68c67d4b046a4df753bc7dbf2ff0c64323b4fcd74990ebf4b3aea1921c50a" +} diff --git a/task_038/tests/_shared/contract_checker.js b/task_038/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_038/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_038/tests/_shared/static_enhancer.sh b/task_038/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_038/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_038/tests/enhancement_cases.json b/task_038/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..879d2a421fc57556f48b6d99fc308c1b80bbcb28 --- /dev/null +++ b/task_038/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "自动叠加文字水印,默认文字为 \"Answer\";", + "validator": "validate_enhanced_cases.js#caseDefaultAnswer", + "behavior": "默认配置精确为 Answer;改成另一文字会改变结果,恢复 Answer 会恢复相同结果。" + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "将上传的图片绘制到 `` 上,并保持原图比例(不拉伸变形);", + "validator": "validate_enhanced_cases.js#caseAspectRatio", + "behavior": "上传确定性的 240×120 非方形图片后,canvas 保持 2:1 纵横比。" + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "支持配置水印样式:文字内容、字号、透明度、位置;", + "validator": "validate_enhanced_cases.js#caseAllConfigurationKinds", + "behavior": "文字控件及三个独立样式控件均会实际重新渲染 canvas,而非仅展示无效控件。" + } +] diff --git a/task_038/tests/test.sh b/task_038/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ab2150eb79f6f15b53d20b21738b84bbe0d8003 --- /dev/null +++ b/task_038/tests/test.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_ui_behavior.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_038/tests/validate_aaav_dynamic.js b/task_038/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..4cd04045b796742ba75acf8eca2338ad7623c16d --- /dev/null +++ b/task_038/tests/validate_aaav_dynamic.js @@ -0,0 +1,152 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 59; +const KIND = "browser"; +const TESTIDS = [ + "image-upload", + "watermark-canvas", + "wm-text" +]; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_038/tests/validate_browser_smoke.js b/task_038/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_038/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_038/tests/validate_enhanced_cases.js b/task_038/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..3ade3b6e6b7aac23892719fc69c6b3376154aa14 --- /dev/null +++ b/task_038/tests/validate_enhanced_cases.js @@ -0,0 +1,281 @@ +const path = require('path'); +const fs = require('fs'); +const { pathToFileURL } = require('url'); +const zlib = require('zlib'); +const { chromium } = require('playwright'); + +const ACTION_TIMEOUT_MS = 5_000; +const CASE_TIMEOUT_MS = 15_000; +process.env.HARBOR_TEST_SEED = '59001'; + +function crc32(buffer) { + let crc = 0xffffffff; + for (const byte of buffer) { + crc ^= byte; + for (let bit = 0; bit < 8; bit += 1) crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1)); + } + return (crc ^ 0xffffffff) >>> 0; +} + +function pngChunk(type, data) { + const name = Buffer.from(type, 'ascii'); + const length = Buffer.alloc(4); + length.writeUInt32BE(data.length); + const checksum = Buffer.alloc(4); + checksum.writeUInt32BE(crc32(Buffer.concat([name, data]))); + return Buffer.concat([length, name, data, checksum]); +} + +function deterministicPng(width, height) { + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(width, 0); + ihdr.writeUInt32BE(height, 4); + ihdr.set([8, 6, 0, 0, 0], 8); + const scanlines = Buffer.alloc(height * (1 + width * 4)); + for (let y = 0; y < height; y += 1) { + const row = y * (1 + width * 4); + for (let x = 0; x < width; x += 1) { + const offset = row + 1 + x * 4; + const left = x < Math.floor(width / 3); + scanlines.set(left ? [224, 160, 32, 255] : [32, 64, 96, 255], offset); + } + } + return Buffer.concat([ + Buffer.from('89504e470d0a1a0a', 'hex'), + pngChunk('IHDR', ihdr), + pngChunk('IDAT', zlib.deflateSync(scanlines, { level: 9 })), + pngChunk('IEND', Buffer.alloc(0)), + ]); +} + +const SOURCE_PNG = deterministicPng(240, 120); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +async function within(ms, label, work) { + let timer; + try { + return await Promise.race([ + work(), + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms); + }), + ]); + } finally { + clearTimeout(timer); + } +} + +async function freshPage(browser) { + const context = await browser.newContext({ offline: true, serviceWorkers: 'block' }); + const page = await context.newPage(); + page.setDefaultTimeout(ACTION_TIMEOUT_MS); + page.setDefaultNavigationTimeout(ACTION_TIMEOUT_MS); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { + waitUntil: 'domcontentloaded', + timeout: ACTION_TIMEOUT_MS, + }); + return { context, page }; +} + +async function uploadSource(page, buffer = SOURCE_PNG, name = 'deterministic-source.png') { + await page.locator('[data-testid="image-upload"]').setInputFiles({ + name, + mimeType: 'image/png', + buffer, + }, { timeout: ACTION_TIMEOUT_MS }); + await page.waitForFunction(() => { + const canvas = document.querySelector('[data-testid="watermark-canvas"]'); + if (!canvas || !canvas.width || !canvas.height) return false; + const pixels = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).data; + for (let i = 3; i < pixels.length; i += 4) if (pixels[i] !== 0) return true; + return false; + }, null, { timeout: ACTION_TIMEOUT_MS }); +} + +async function canvasUrl(page) { + return page.locator('[data-testid="watermark-canvas"]').evaluate((canvas) => canvas.toDataURL()); +} + +async function capture(page, name) { + fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + await page.screenshot({path: `/logs/verifier/visual-audit/${name}.png`, fullPage: true}); +} + +// ENHANCED_CASE_1: the mandated default text is Answer and affects the rendered result. +async function caseDefaultAnswer(browser) { + const { context, page } = await freshPage(browser); + try { + const text = page.locator('[data-testid="wm-text"]'); + assert(await text.inputValue() === 'Answer', 'default watermark text must be exactly "Answer"'); + await uploadSource(page); + const answerOutput = await canvasUrl(page); + const original='data:image/png;base64,'+SOURCE_PNG.toString('base64'); + const saved=await page.evaluate(()=>window.__getImageStore()); + assert(saved.originals.length===1&&saved.originals[0]===original,'stored original must equal input bytes'); + assert(saved.watermarked[0]===answerOutput&&saved.watermarked[0]!==original,'store must retain actual watermarked result separately'); + await capture(page, 'default-watermark'); + const copy = await page.evaluate(() => { + const snapshot = window.__getImageStore(); + snapshot.originals[0] = 'corrupted'; snapshot.watermarked.length = 0; + return window.__getImageStore(); + }); + assert(copy.originals[0] === original && copy.watermarked[0] === answerOutput, 'store observer must return an independent deep copy'); + await text.fill('A different deterministic watermark', { timeout: ACTION_TIMEOUT_MS }); + await page.waitForFunction( + (before) => document.querySelector('[data-testid="watermark-canvas"]').toDataURL() !== before, + answerOutput, + { timeout: ACTION_TIMEOUT_MS } + ); + const differentOutput = await canvasUrl(page); + const updated=await page.evaluate(()=>window.__getImageStore()); + assert(updated.originals[0]===original&&updated.watermarked[0]===differentOutput,'editing watermark must preserve original and update result'); + assert(differentOutput !== answerOutput, 'changing Answer should change the watermarked pixels'); + await text.fill('Answer', { timeout: ACTION_TIMEOUT_MS }); + await page.waitForFunction(previous => { + const canvas = document.querySelector('[data-testid="watermark-canvas"]'); + const actual = canvas.toDataURL(); + const saved = window.__getImageStore(); + return actual !== previous && saved.watermarked[0] === actual; + }, differentOutput, {timeout: ACTION_TIMEOUT_MS}); + const restored = await page.evaluate(() => window.__getImageStore()); + assert(restored.originals[0] === original, 'restoring settings must not replace source bytes'); + } finally { + await context.close(); + } +} + +// ENHANCED_CASE_2: a non-square upload is drawn without changing its aspect ratio. +async function caseAspectRatio(browser) { + const { context, page } = await freshPage(browser); + try { + await uploadSource(page); + const dimensions = await page.locator('[data-testid="watermark-canvas"]').evaluate((canvas) => ({ + width: canvas.width, + height: canvas.height, + })); + assert(dimensions.width > 0 && dimensions.height > 0, 'watermark canvas must have positive dimensions'); + assert( + Math.abs(dimensions.width / dimensions.height - 2) < 0.01, + `uploaded 240x120 image ratio should remain 2:1, got ${dimensions.width}:${dimensions.height}` + ); + } finally { + await context.close(); + } +} + +async function caseAllConfigurationKinds(browser) { + const {context, page} = await freshPage(browser); + try { + await uploadSource(page); + const set = async (id, value) => { + await page.locator(`[data-testid="${id}"]`).evaluate((element, value) => { + element.value = value; + element.dispatchEvent(new Event('input', {bubbles: true})); + element.dispatchEvent(new Event('change', {bubbles: true})); + }, String(value)); + }; + const pixels = () => page.locator('[data-testid="watermark-canvas"]').evaluate(canvas => Array.from(canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).data)); + await set('wm-opacity', 0); + const original = 'data:image/png;base64,' + SOURCE_PNG.toString('base64'); + await page.waitForFunction(async source => { + const image = new Image(); image.src = source; await image.decode(); + const actual = document.querySelector('[data-testid="watermark-canvas"]'); + const base = document.createElement('canvas'); base.width = actual.width; base.height = actual.height; + base.getContext('2d').drawImage(image, 0, 0, base.width, base.height); + const a = actual.getContext('2d').getImageData(0, 0, actual.width, actual.height).data; + const b = base.getContext('2d').getImageData(0, 0, base.width, base.height).data; + return a.every((value, index) => value === b[index]); + }, original); + const base = await pixels(); + const stats = async () => { + const actual = await pixels(); + const width = await page.locator('canvas').first().evaluate(canvas => canvas.width); + let count = 0, energy = 0, x = 0, y = 0; + for (let offset = 0; offset < base.length; offset += 4) { + const delta = Math.abs(actual[offset]-base[offset]) + Math.abs(actual[offset+1]-base[offset+1]) + Math.abs(actual[offset+2]-base[offset+2]); + if (delta > 3) {count++; energy += delta; x += offset/4%width; y += Math.floor(offset/4/width);} + } + return {count, energy, x: x/count, y: y/count}; + }; + const changed = async (id, value) => { + const before = await canvasUrl(page); await set(id, value); + await page.waitForFunction(before => document.querySelector('[data-testid="watermark-canvas"]').toDataURL() !== before, before); + return stats(); + }; + await set('wm-text', 'Answer'); await set('wm-position', 'center'); await set('wm-size', 16); + const small = await changed('wm-opacity', 0.8); + const large = await changed('wm-size', 32); + assert(large.count > small.count * 1.3, 'increasing font size must enlarge the actual watermark footprint'); + const faint = await changed('wm-opacity', 0.2); + assert(faint.energy < large.energy * 0.7, 'lower opacity must reduce watermark contrast, not merely change pixels'); + await set('wm-opacity', 0.8); await set('wm-size', 16); + const topLeft = await changed('wm-position', 'top-left'); + const bottomRight = await changed('wm-position', 'bottom-right'); + assert(bottomRight.x > topLeft.x + 20 && bottomRight.y > topLeft.y + 20, 'position selector must move watermark toward its selected corner'); + await capture(page, 'configured-watermark'); + } finally {await context.close();} +} + +async function caseMultipleUploads(browser) { + const {context, page} = await freshPage(browser); + try { + await uploadSource(page); + const firstResult = await canvasUrl(page); + const secondSource = deterministicPng(120, 180); + await uploadSource(page, secondSource, 'portrait.png'); + const encode = buffer => 'data:image/png;base64,' + buffer.toString('base64'); + const firstOriginal = encode(SOURCE_PNG); + const secondOriginal = encode(secondSource); + await page.waitForFunction(original => { + const store = window.__getImageStore(); + const canvas = document.querySelector('[data-testid="watermark-canvas"]'); + const second = store.originals.indexOf(original); + return second >= 0 && store.watermarked[second] === canvas.toDataURL() && store.originals.length >= 2; + }, secondOriginal, {timeout: ACTION_TIMEOUT_MS}); + const snapshot = await page.evaluate(() => window.__getImageStore()); + const first = snapshot.originals.indexOf(firstOriginal); + const second = snapshot.originals.indexOf(secondOriginal); + assert(first >= 0 && second >= 0 && snapshot.originals.length === 2, 'both original byte sequences must remain stored'); + assert(snapshot.watermarked.length === 2 && snapshot.watermarked[first] === firstResult, 'the first canvas result must survive the next upload'); + assert(snapshot.watermarked[second] !== firstResult && snapshot.watermarked[second] !== secondOriginal, 'the portrait must have its own watermarked result'); + const sameAsUnmarked = await page.getByTestId('watermark-canvas').evaluate(async (canvas, original) => { + const image = new Image(); image.src = original; await image.decode(); + const raw = document.createElement('canvas'); raw.width = canvas.width; raw.height = canvas.height; + const context = raw.getContext('2d'); + context.drawImage(image, 0, 0, raw.width, raw.height); + const unmarked = context.getImageData(0, 0, raw.width, raw.height).data; + const actual = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).data; + return actual.every((value, index) => value === unmarked[index]); + }, secondOriginal); + assert(!sameAsUnmarked, 'the second upload must actually paint a watermark, not just re-encode the source'); + await capture(page, 'second-upload'); + } finally { + await context.close(); + } +} + +const enhancedCases = { + ENHANCED_CASE_1: caseDefaultAnswer, + ENHANCED_CASE_2: caseAspectRatio, + ENHANCED_CASE_3: caseAllConfigurationKinds, + ENHANCED_CASE_4: caseMultipleUploads, +}; + +(async () => { + const requested = process.argv[2]; + assert(!requested || enhancedCases[requested], `unknown enhanced case: ${requested}`); + const browser = await chromium.launch({ headless: true, timeout: ACTION_TIMEOUT_MS }); + try { + const entries = requested ? [[requested, enhancedCases[requested]]] : Object.entries(enhancedCases); + for (const [caseId, run] of entries) await within(CASE_TIMEOUT_MS, caseId, () => run(browser)); + console.log(`task 59 enhanced cases passed (${entries.length}/${entries.length})`); + } finally { + await browser.close(); + } +})().catch((err) => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_038/tests/validate_semantics.js b/task_038/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_038/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_038/tests/validate_ui_behavior.js b/task_038/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..bdb4d2d578c11d893bedb910a88649c110d7a3bd --- /dev/null +++ b/task_038/tests/validate_ui_behavior.js @@ -0,0 +1,74 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1000, height: 760 } }); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + + // Required controls: upload input, canvas, configurable watermark text. + const upload = page.locator('[data-testid="image-upload"]'); + if (!(await upload.count())) throw new Error('page should expose an image upload control'); + const canvas = page.locator('[data-testid="watermark-canvas"], canvas'); + if (!(await canvas.count())) throw new Error('a canvas is required to draw the watermarked image'); + const wmText = page.locator('[data-testid="wm-text"]'); + if (!(await wmText.count())) throw new Error('a configurable watermark text input is required'); + + // Default watermark text should be present (e.g. "Answer"). + const defaultText = (await wmText.first().inputValue()) || ''; + if (!defaultText.trim()) throw new Error('watermark text should have a sensible default'); + + // Canvas must be a usable size. + const dims0 = await canvas.first().evaluate(c => ({ w: c.width, h: c.height })); + + // Upload a real, non-trivial source image (200x120) generated in-page, and + // confirm the canvas is drawn (non-blank) and preserves the image aspect ratio. + async function uploadGenerated() { + await page.evaluate(async () => { + const src = document.createElement('canvas'); + src.width = 200; src.height = 120; + const c = src.getContext('2d'); + c.fillStyle = '#3b82f6'; c.fillRect(0, 0, 200, 120); + c.fillStyle = '#f59e0b'; c.fillRect(20, 20, 80, 60); + const blob = await new Promise(res => src.toBlob(res, 'image/png')); + const file = new File([blob], 'src.png', { type: 'image/png' }); + const input = document.querySelector('[data-testid="image-upload"]'); + const dt = new DataTransfer(); + dt.items.add(file); + input.files = dt.files; + input.dispatchEvent(new Event('change', { bubbles: true })); + }); + await page.waitForFunction(() => { + const canvas = document.querySelector('[data-testid="watermark-canvas"]'); + return window.__getImageStore().originals.length === 1 && canvas.width / canvas.height === 200 / 120; + }, null, {timeout: 5000}); + } + await uploadGenerated(); + + const drawn = await canvas.first().evaluate(c => { + const ctx = c.getContext('2d'); + const data = ctx.getImageData(0, 0, c.width, c.height).data; + let nonBlank = false; + for (let i = 0; i < data.length; i += 4) { + if (data[i] !== 0 || data[i + 1] !== 0 || data[i + 2] !== 0 || data[i + 3] !== 0) { nonBlank = true; break; } + } + return { w: c.width, h: c.height, nonBlank, url: c.toDataURL() }; + }); + if (!drawn.nonBlank) throw new Error('uploaded image should be drawn onto the canvas'); + // Aspect ratio of the source (200:120) should be preserved on the canvas. + const ratio = drawn.w / drawn.h; + if (Math.abs(ratio - (200 / 120)) > 0.05) { + throw new Error('canvas should preserve the original image aspect ratio, got ' + ratio.toFixed(3)); + } + + // The watermark must actually be drawn: changing the watermark text must + // change the rendered pixels (a no-op "image only" solution would not). + await wmText.first().fill('WMTEST'); + await page.waitForFunction(before => document.querySelector('[data-testid="watermark-canvas"]').toDataURL() !== before, drawn.url, {timeout: 5000}); + const afterUrl = await canvas.first().evaluate(c => c.toDataURL()); + if (afterUrl === drawn.url) { + throw new Error('changing the watermark text should re-render the watermark on the canvas'); + } + + await browser.close(); +})().catch(err => { console.error(err && err.stack || err); process.exit(1); }); diff --git a/task_039/acceptance_checklist.json b/task_039/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..610bd2a2322ce041863c36de0781594fa691d8c4 --- /dev/null +++ b/task_039/acceptance_checklist.json @@ -0,0 +1,29 @@ +{ + "task_id": 60, + "category": "application_development", + "language": "go", + "acceptance_items": [ + "Go package compiles and base behavior tests pass", + "three content types and distinct configured words", + "repeated word-list replacement", + "audit captures every blocked attempt", + "configuration file loading and accepted submissions", + "invalid type and defensive list copies" + ], + "input_assets": [ + "content_safety.go", + "content_safety_test.go", + "sensitive_words.txt" + ], + "expected_outputs": [ + "content_safety.go", + "sensitive_words.txt", + "optional index.html demo" + ], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns.", + "A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-30" +} diff --git a/task_039/environment/Dockerfile b/task_039/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f7c63c1afe472bd572b57d5a48ffd3cf28ff5c8a --- /dev/null +++ b/task_039/environment/Dockerfile @@ -0,0 +1,4 @@ +# syntax=docker/dockerfile:1.7-labs +FROM golang:1.23-bookworm@sha256:167053a2bb901972bf2c1611f8f52c44d5fe7e762e5cab213708d82c421614db +WORKDIR /app +COPY ./code /app diff --git a/task_039/environment/code/content_safety.go b/task_039/environment/code/content_safety.go new file mode 100644 index 0000000000000000000000000000000000000000..cc25d04562a7672502dda6d8ff6b5e4aa010921d --- /dev/null +++ b/task_039/environment/code/content_safety.go @@ -0,0 +1,23 @@ +package contentsafety + +type AuditEntry struct { + ContentType string + Text string + Word string +} + +type Filter struct{} + +func NewFilter(words []string) *Filter { + return &Filter{} +} + +func (f *Filter) SetWords(words []string) {} + +func (f *Filter) Validate(contentType string, text string) error { + return nil +} + +func (f *Filter) AuditLog() []AuditEntry { + return nil +} diff --git a/task_039/environment/code/content_safety_test.go b/task_039/environment/code/content_safety_test.go new file mode 100644 index 0000000000000000000000000000000000000000..77172f657138bfc107076d6c591cdd2a068b4afe --- /dev/null +++ b/task_039/environment/code/content_safety_test.go @@ -0,0 +1,69 @@ +package contentsafety + +import ( + "strings" + "testing" +) + +func TestBlocksSensitiveWordsAcrossContentTypes(t *testing.T) { + filter := NewFilter([]string{"forbidden", "辱骂"}) + for _, contentType := range []string{"question", "answer", "comment"} { + err := filter.Validate(contentType, "this contains forbidden content") + if err == nil { + t.Fatalf("%s containing sensitive word should be blocked", contentType) + } + if !strings.Contains(strings.ToLower(err.Error()), "sensitive") && !strings.Contains(err.Error(), "敏感") { + t.Fatalf("error should clearly mention sensitive content, got %v", err) + } + } +} + +func TestAllowsCleanContentAndSupportsConfigUpdates(t *testing.T) { + filter := NewFilter([]string{"alpha"}) + if err := filter.Validate("question", "clean text"); err != nil { + t.Fatalf("clean content should pass: %v", err) + } + filter.SetWords([]string{"beta"}) + if err := filter.Validate("answer", "alpha is no longer blocked"); err != nil { + t.Fatalf("updated word list should replace old words: %v", err) + } + if err := filter.Validate("answer", "beta should now be blocked"); err == nil { + t.Fatalf("updated word list should block beta") + } +} + +func TestMatchIsCaseInsensitive(t *testing.T) { + // Validate lowercases both the configured word and the text before Contains, + // so a lowercase word "forbidden" matches uppercase text "FORBIDDEN". + filter := NewFilter([]string{"Forbidden"}) + if err := filter.Validate("comment", "FORBIDDEN here"); err == nil { + t.Fatalf("case-insensitive match should block FORBIDDEN") + } + logs := filter.AuditLog() + if len(logs) != 1 || logs[0].Word != "Forbidden" { + t.Fatalf("audit should record the configured word verbatim: %+v", logs) + } +} + +func TestNoAuditEntryForCleanContent(t *testing.T) { + // Audit entries are appended only when a block occurs; clean content logs nothing. + filter := NewFilter([]string{"forbidden"}) + if err := filter.Validate("question", "perfectly clean text"); err != nil { + t.Fatalf("clean content should pass: %v", err) + } + if logs := filter.AuditLog(); len(logs) != 0 { + t.Fatalf("clean content should not create audit entries, got %d", len(logs)) + } +} + +func TestRecordsAuditEntriesForBlockedAttempts(t *testing.T) { + filter := NewFilter([]string{"risk"}) + _ = filter.Validate("comment", "risk appears here") + logs := filter.AuditLog() + if len(logs) != 1 { + t.Fatalf("blocked attempt should create one audit entry, got %d", len(logs)) + } + if logs[0].ContentType != "comment" || logs[0].Word != "risk" { + t.Fatalf("audit entry should capture content type and matched word: %+v", logs[0]) + } +} diff --git a/task_039/environment/code/go.mod b/task_039/environment/code/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..2b1bd777af00bc13a86bc5a138ecbae7085019f1 --- /dev/null +++ b/task_039/environment/code/go.mod @@ -0,0 +1,3 @@ +module answer_content_safety + +go 1.23 diff --git a/task_039/environment/code/sensitive_words.txt b/task_039/environment/code/sensitive_words.txt new file mode 100644 index 0000000000000000000000000000000000000000..6b6029aa5763f7c8c405c54f06b0c0b6ce140310 --- /dev/null +++ b/task_039/environment/code/sensitive_words.txt @@ -0,0 +1,4 @@ +# 每行一个演示用词;管理员可替换此文件并重新加载 +spam-link +abuse-term +违规广告 diff --git a/task_039/environment/docker-compose.yaml b/task_039/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_039/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_039/instruction.md b/task_039/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d091a3ccd51040a0061cb4f2e24e1177b596f871 --- /dev/null +++ b/task_039/instruction.md @@ -0,0 +1,25 @@ +# Filter and audit sensitive-content submissions + +Implement the Go `contentsafety` package in the supplied project. Check questions, answers and comments against a configurable sensitive-word list before accepting them. + +## Interface + +```go +func NewFilter(words []string) *Filter +func LoadWordsFile(path string) ([]string, error) +func NewFilterFromFile(path string) (*Filter, error) +func (f *Filter) SetWords(words []string) +func (f *Filter) Validate(contentType, text string) error +func (f *Filter) Submit(contentType, text string) error +func (f *Filter) AuditLog() []AuditEntry +func (f *Filter) Accepted() []SubmittedEntry +``` + +Keep the `AuditEntry` fields `ContentType`, `Text` and `Word`; expose `ContentType` and `Text` string fields on `SubmittedEntry`. The starter includes UTF-8 `sensitive_words.txt`, one entry per line. An administrator can edit and reload this file or update the API's word list. An administrator UI is optional; no Apache Answer instance is needed. Local packages are allowed; `go test ./...` must work offline. + +## Acceptance Checklist + +- Read entries in file order, preserving case, trimming surrounding whitespace and ignoring blank and `#` comment lines. Return an error for a missing or unreadable file. +- For `question`, `answer` and `comment`, detect nonblank configured words as case-insensitive substrings. A match returns an error indicating sensitive content and appends exactly one audit entry with the original text, type and configured word. A clean validation adds no audit entry. +- Clean submissions go to the accepted list; blocked submissions do not. Unsupported types are rejected without changing either list. +- The constructor and `SetWords` take independent snapshots. Updates replace the old list immediately; nil and empty lists clear it. Returned audit and accepted lists are independent snapshots. diff --git a/task_039/quality_notes.md b/task_039/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..e9b6e85de99a140c182ed08065c0ab91ebc08cef --- /dev/null +++ b/task_039/quality_notes.md @@ -0,0 +1,11 @@ +# Quality notes — harbor_060 + +2026-09-30 人工反馈修订。题面、解答与可执行 verifier 已按同一公开约定同步。 + +验证重点: +- Go package compiles and base behavior tests pass(tests/test.sh) +- three content types and distinct configured words(tests/enhanced_cases_test.go.fixture) +- repeated word-list replacement(tests/enhanced_cases_test.go.fixture) +- audit captures every blocked attempt(tests/enhanced_cases_test.go.fixture) +- configuration file loading and accepted submissions(tests/enhanced_cases_test.go.fixture) +- invalid type and defensive list copies(tests/enhanced_cases_test.go.fixture) diff --git a/task_039/solution/README.md b/task_039/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_039/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_039/solution/code/content_safety.go b/task_039/solution/code/content_safety.go new file mode 100644 index 0000000000000000000000000000000000000000..a2d1545b3363cfb215cc7858a1265b47ad3601e9 --- /dev/null +++ b/task_039/solution/code/content_safety.go @@ -0,0 +1,123 @@ +package contentsafety + +import ( + "bufio" + "fmt" + "os" + "strings" + "sync" +) + +type AuditEntry struct { + ContentType string + Word string + Text string +} + +type SubmittedEntry struct { + ContentType string + Text string +} + +type Filter struct { + mu sync.Mutex + words []string + audit []AuditEntry + accepted []SubmittedEntry +} + +func NewFilter(words []string) *Filter { + f := &Filter{} + f.SetWords(words) + return f +} + +func (f *Filter) SetWords(words []string) { + clean := make([]string, 0, len(words)) + seen := make(map[string]bool) + for _, word := range words { + word = strings.TrimSpace(word) + key := strings.ToLower(word) + if word != "" && !seen[key] { + clean = append(clean, word) + seen[key] = true + } + } + f.mu.Lock() + defer f.mu.Unlock() + f.words = clean +} + +func LoadWordsFile(path string) ([]string, error) { + file, err := os.Open(path) + if err != nil { + return nil, err + } + defer file.Close() + scanner := bufio.NewScanner(file) + words := []string{} + for scanner.Scan() { + line := strings.TrimSpace(strings.TrimPrefix(scanner.Text(), "\ufeff")) + if line != "" && !strings.HasPrefix(line, "#") { + words = append(words, line) + } + } + if err := scanner.Err(); err != nil { + return nil, err + } + return words, nil +} + +func NewFilterFromFile(path string) (*Filter, error) { + words, err := LoadWordsFile(path) + if err != nil { + return nil, err + } + return NewFilter(words), nil +} + +func validType(contentType string) bool { + return contentType == "question" || contentType == "answer" || contentType == "comment" +} + +func (f *Filter) validateLocked(contentType string, text string) error { + if !validType(contentType) { + return fmt.Errorf("unsupported content type: %s", contentType) + } + lower := strings.ToLower(text) + for _, word := range f.words { + if strings.Contains(lower, strings.ToLower(word)) { + f.audit = append(f.audit, AuditEntry{ContentType: contentType, Word: word, Text: text}) + return fmt.Errorf("sensitive content blocked: %s", word) + } + } + return nil +} + +func (f *Filter) Validate(contentType string, text string) error { + f.mu.Lock() + defer f.mu.Unlock() + return f.validateLocked(contentType, text) +} + +func (f *Filter) Submit(contentType string, text string) error { + f.mu.Lock() + defer f.mu.Unlock() + if err := f.validateLocked(contentType, text); err != nil { + return err + } + f.accepted = append(f.accepted, SubmittedEntry{ContentType: contentType, Text: text}) + return nil +} + +func (f *Filter) AuditLog() []AuditEntry { + f.mu.Lock() + defer f.mu.Unlock() + return append([]AuditEntry(nil), f.audit...) +} + +func (f *Filter) Accepted() []SubmittedEntry { + f.mu.Lock() + defer f.mu.Unlock() + return append([]SubmittedEntry(nil), f.accepted...) +} diff --git a/task_039/solution/code/go.mod b/task_039/solution/code/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..2b1bd777af00bc13a86bc5a138ecbae7085019f1 --- /dev/null +++ b/task_039/solution/code/go.mod @@ -0,0 +1,3 @@ +module answer_content_safety + +go 1.23 diff --git a/task_039/solution/code/index.html b/task_039/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..6b9b6d247368fcd8c21c9ab81d4a806d1e1006f2 --- /dev/null +++ b/task_039/solution/code/index.html @@ -0,0 +1,64 @@ + + + + + + Content Safety Console + + + +
      Answer / Content SafetyAdmin Demo
      +
      +
      CONTENT MODERATION
      +

      Keep Every Submission Accountable

      +

      Maintain a term list, simulate question, answer, and comment submissions, and review blocked attempts. This page runs offline.

      +
      +
      +

      Submit Content

      A submission that matches the term list is blocked, and both the original text and matched term are added to the audit log below.

      + + +
      Waiting for a submission
      +
      +
      +

      Blocked-Term Settings

      Enter one term per line. Blank lines and comments beginning with # are ignored. Save changes to apply them immediately.

      + +
      3 terms enabled
      +
      +
      +

      Blocked Attempt Audit

      • No blocked submissions
      +
      + + + diff --git a/task_039/solution/code/sensitive_words.txt b/task_039/solution/code/sensitive_words.txt new file mode 100644 index 0000000000000000000000000000000000000000..b65db36955066601e07c188baa321c3cd2fafe36 --- /dev/null +++ b/task_039/solution/code/sensitive_words.txt @@ -0,0 +1,4 @@ +# One demo term per line; administrators can replace this file and reload it. +spam-link +abuse-term +prohibited-ad diff --git a/task_039/solution/solve.sh b/task_039/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_039/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_039/task.toml b/task_039/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_039/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_039/task_meta.json b/task_039/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..8be549b398217963cb0978ee1a6fb5dc916f7f30 --- /dev/null +++ b/task_039/task_meta.json @@ -0,0 +1,45 @@ +{ + "task_id": 60, + "task_category": "application_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 2, + "language": "go", + "tool_files_from_selected_trace": [ + "answer_controller.go", + "comment_controller.go", + "comment_repo.go", + "comment_service.go", + "content_moderation.go", + "content_moderation.md", + "content_moderation_controller.go", + "content_moderation_repo.go", + "content_moderation_schema.go", + "content_moderation_service.go", + "content_moderation_service_impl.go", + "content_moderation_service_test.go", + "migrations.go", + "question_controller.go", + "question_repo.go", + "question_schema.go", + "question_service.go", + "reason.go", + "sensitive_word_detector.go", + "sensitive_word_entity.go", + "v27.go", + "v28.go" + ], + "input_assets": [ + "content_safety.go", + "content_safety_test.go", + "sensitive_words.txt" + ], + "expected_outputs": [ + "content_safety.go", + "sensitive_words.txt", + "optional index.html demo" + ], + "source_row_id": 360, + "repair_revision": "2026-09-30", + "instruction_sha256": "30567badc6a7c9dc20d17e2e0f06d5ff819da6818153ccfc4af7e65c53405096" +} diff --git a/task_039/tests/_shared/contract_checker.js b/task_039/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_039/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_039/tests/_shared/static_enhancer.sh b/task_039/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_039/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_039/tests/enhanced_cases_test.go.fixture b/task_039/tests/enhanced_cases_test.go.fixture new file mode 100644 index 0000000000000000000000000000000000000000..2a2019f8408f1df0e43726091bc8124fbff9f8bf --- /dev/null +++ b/task_039/tests/enhanced_cases_test.go.fixture @@ -0,0 +1,175 @@ +package contentsafety + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// ENHANCED_CASE_1: configured non-placeholder words are blocked in all required content types. +func TestEnhancedDistinctWordsAcrossAllContentTypes(t *testing.T) { + words := []string{"question-risk-731", "回答风险词", "comment-risk-419"} + filter := NewFilter(words) + cases := []struct{ contentType, text, word string }{ + {"question", "prefix question-risk-731 suffix", words[0]}, + {"answer", "回答中包含回答风险词需要阻止", words[1]}, + {"comment", "prefix comment-risk-419 suffix", words[2]}, + } + for _, tc := range cases { + err := filter.Validate(tc.contentType, tc.text) + if err == nil { + t.Fatalf("%s containing configured word %q was not blocked", tc.contentType, tc.word) + } + if strings.TrimSpace(err.Error()) == "" { + t.Errorf("%s block should return a non-empty error", tc.contentType) + } + } +} + +// ENHANCED_CASE_2: administrator-style repeated configuration updates take effect immediately. +func TestEnhancedRepeatedConfigurationReplacement(t *testing.T) { + filter := NewFilter([]string{"retired-risk-101"}) + filter.SetWords([]string{"current-risk-202"}) + if err := filter.Validate("question", "retired-risk-101 is now clean"); err != nil { + t.Fatalf("replaced word remained blocked: %v", err) + } + if err := filter.Validate("answer", "contains current-risk-202"); err == nil { + t.Fatal("newly configured word was not blocked") + } + filter.SetWords([]string{"final-risk-303"}) + if err := filter.Validate("comment", "current-risk-202 is now clean"); err != nil { + t.Fatalf("second replacement did not remove prior configuration: %v", err) + } + if err := filter.Validate("comment", "contains final-risk-303"); err == nil { + t.Fatal("second replacement did not add new configuration") + } +} + +// ENHANCED_CASE_3: every blocked attempt is auditable with its type, text, and matched word. +func TestEnhancedAuditTrailForMultipleAttempts(t *testing.T) { + filter := NewFilter([]string{"audit-risk-551"}) + attempts := []struct{ contentType, text string }{ + {"question", "question audit-risk-551 payload"}, + {"answer", "answer audit-risk-551 payload"}, + {"comment", "comment audit-risk-551 payload"}, + } + for _, attempt := range attempts { + if err := filter.Validate(attempt.contentType, attempt.text); err == nil { + t.Fatalf("blocked attempt for %s unexpectedly passed", attempt.contentType) + } + } + if err := filter.Validate("comment", "a clean control message"); err != nil { + t.Fatalf("clean control message was blocked: %v", err) + } + log := filter.AuditLog() + if len(log) != len(attempts) { + t.Fatalf("want %d audit entries, got %d", len(attempts), len(log)) + } + remaining := make(map[string]bool, len(attempts)) + for _, attempt := range attempts { + remaining[attempt.contentType+"\x00"+attempt.text] = true + } + for _, entry := range log { + key := entry.ContentType + "\x00" + entry.Text + if !remaining[key] || entry.Word != "audit-risk-551" { + t.Errorf("audit entry does not preserve a blocked attempt: %+v", entry) + } + delete(remaining, key) + } + if len(remaining) != 0 { + t.Fatalf("audit log omitted %d blocked attempts", len(remaining)) + } +} + +func TestEnhancedFileConfigAndSubmission(t *testing.T) { + f, err := NewFilterFromFile("sensitive_words.txt") + if err != nil { + t.Fatal(err) + } + if err := f.Submit("question", "A SPAM-LINK should not be accepted"); err == nil { + t.Fatal("bundled word should block") + } + if len(f.Accepted()) != 0 { + t.Fatal("blocked submission entered accepted list") + } + if err := f.Submit("answer", "This is a clean answer"); err != nil { + t.Fatal(err) + } + if got := f.Accepted(); len(got) != 1 || got[0].ContentType != "answer" { + t.Fatalf("accepted=%+v", got) + } + if got := f.AuditLog(); len(got) != 1 || got[0].Word != "spam-link" { + t.Fatalf("audit=%+v", got) + } + path := filepath.Join(t.TempDir(), "words.txt") + if err := os.WriteFile(path, []byte("# comment\n\n alpha \nBETA\n"), 0600); err != nil { + t.Fatal(err) + } + words, err := LoadWordsFile(path) + if err != nil || len(words) != 2 || words[0] != "alpha" || words[1] != "BETA" { + t.Fatalf("loaded=%v err=%v", words, err) + } + f.SetWords(words) + if err := f.Submit("comment", "beta mention"); err == nil { + t.Fatal("updated file words did not block") + } + if err := f.Submit("comment", "spam-link is retired"); err != nil { + t.Fatal("old word still active:", err) + } + if _, err := NewFilterFromFile(filepath.Join(t.TempDir(), "missing")); err == nil { + t.Fatal("missing config must return error") + } +} + +func TestEnhancedInvalidTypeAndDefensiveCopies(t *testing.T) { + f := NewFilter([]string{" ", "Risk", "risk"}) + if err := f.Submit("question", "clean"); err != nil { + t.Fatal("blank word blocked all text:", err) + } + if err := f.Submit("post", "risk"); err == nil { + t.Fatal("unsupported type accepted") + } + if len(f.Accepted()) != 1 || len(f.AuditLog()) != 0 { + t.Fatal("invalid type altered records") + } + if err := f.Submit("comment", "RISK"); err == nil { + t.Fatal("case fold failed") + } + accepted := f.Accepted() + accepted[0].Text = "mutated" + audit := f.AuditLog() + audit[0].Text = "mutated" + if f.Accepted()[0].Text != "clean" || f.AuditLog()[0].Text != "RISK" { + t.Fatal("record snapshots expose internal state") + } +} + +func TestEnhancedWordOwnershipAndEmptyReplacement(t *testing.T) { + words := []string{"original"} + f := NewFilter(words) + words[0] = "outside-change" + if f.Validate("question", "original") == nil { + t.Fatal("constructor must own its word snapshot") + } + updated := []string{"replacement"} + f.SetWords(updated) + updated[0] = "outside-change" + if f.Validate("answer", "replacement") == nil { + t.Fatal("SetWords must own its word snapshot") + } + f.SetWords(nil) + before := len(f.AuditLog()) + if err := f.Submit("comment", "original replacement outside-change"); err != nil { + t.Fatal("empty replacement must clear the word list:", err) + } + if len(f.AuditLog()) != before { + t.Fatal("empty configuration created a block audit") + } + if err := f.Validate("post", "anything"); err == nil { + t.Fatal("Validate must reject unsupported content types too") + } + if len(f.AuditLog()) != before { + t.Fatal("invalid Validate call altered audit") + } +} diff --git a/task_039/tests/enhancement_cases.json b/task_039/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..e4a0cef473781330cecfa6ef2ca5b357ec04dff6 --- /dev/null +++ b/task_039/tests/enhancement_cases.json @@ -0,0 +1,38 @@ +[ + { + "case_id": "CASE_1", + "instruction_evidence": "Go package compiles and base behavior tests pass", + "validator": "tests/test.sh", + "behavior": "Go package compiles and base behavior tests pass" + }, + { + "case_id": "CASE_2", + "instruction_evidence": "three content types and distinct configured words", + "validator": "tests/enhanced_cases_test.go.fixture", + "behavior": "three content types and distinct configured words" + }, + { + "case_id": "CASE_3", + "instruction_evidence": "repeated word-list replacement", + "validator": "tests/enhanced_cases_test.go.fixture", + "behavior": "repeated word-list replacement" + }, + { + "case_id": "CASE_4", + "instruction_evidence": "audit captures every blocked attempt", + "validator": "tests/enhanced_cases_test.go.fixture", + "behavior": "audit captures every blocked attempt" + }, + { + "case_id": "CASE_5", + "instruction_evidence": "configuration file loading and accepted submissions", + "validator": "tests/enhanced_cases_test.go.fixture", + "behavior": "configuration file loading and accepted submissions" + }, + { + "case_id": "CASE_6", + "instruction_evidence": "invalid type and defensive list copies", + "validator": "tests/enhanced_cases_test.go.fixture", + "behavior": "invalid type and defensive list copies" + } +] diff --git a/task_039/tests/test.sh b/task_039/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8d0ae52dd9a75e070570e881b5eebd9ac4595701 --- /dev/null +++ b/task_039/tests/test.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set +e +T="$(cd "$(dirname "$0")" && pwd)"; R=/logs/verifier; mkdir -p "$R"; p=1 +command -v go >/dev/null 2>&1 || p=0 +[ "$p" = 1 ] && timeout 120s go test ./... || p=0 +for c in ENHANCED_CASE_1 ENHANCED_CASE_2 ENHANCED_CASE_3 ENHANCED_CASE_4 ENHANCED_CASE_5; do [ "$p" = 1 ] && timeout 60s bash "$T/validate_enhanced_cases.sh" "$c" || p=0; done +echo "$p" > "$R/reward.txt"; exit 0 diff --git a/task_039/tests/validate_aaav_dynamic.js b/task_039/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..17debf370d78c915dd1b98742bbe37e225256651 --- /dev/null +++ b/task_039/tests/validate_aaav_dynamic.js @@ -0,0 +1,69 @@ +const fs = require('fs'); +const path = require('path'); +const child_process = require('child_process'); +const TASK_ID = 60; +const LANGUAGE = "go"; +const EXPECTED = []; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { if (!condition) throw new Error(message); } +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} +function globToRe(glob) { + return new RegExp('^' + glob.split('*').map(x => x.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') + '$'); +} +function existsPattern(files, pat) { + const re = globToRe(String(pat).replace(/\\/g, '/')); + return files.some(f => re.test(f.replace(/\\/g, '/')) || f.replace(/\\/g, '/').endsWith(String(pat).replace(/\\/g, '/'))); +} + +const files = walk(process.cwd()); +assert(files.length > 0, 'candidate workspace should contain files'); +const rel = files.map(f => path.relative(process.cwd(), f)); +const source = files.filter(f => /\.(js|jsx|ts|tsx|css|html|py|go|md|svg)$/i.test(f)); +assert(source.length > 0, 'candidate should contain source or report files'); +const totalBytes = source.reduce((n, f) => n + fs.statSync(f).size, 0); +assert(totalBytes >= 80, 'candidate source/report content is too small'); + +if (LANGUAGE === 'go') { + const goFiles = files.filter(f => f.endsWith('.go')); + assert(goFiles.length > 0, 'go task should contain .go files'); + try { + child_process.execFileSync('go', ['test', './...'], { cwd: process.cwd(), stdio: 'pipe', timeout: 120000 }); + } catch (err) { + // The benchmark's own verifier owns task-specific Go behavior. Here we + // keep go test as an opportunistic runtime probe so local module/path + // differences do not create false negatives. + const msg = Buffer.concat([err.stdout || Buffer.alloc(0), err.stderr || Buffer.alloc(0)]).toString().slice(0, 500); + console.warn('go test ./... probe failed but is non-fatal: ' + msg); + } +} else if (LANGUAGE === 'python') { + const pyFiles = files.filter(f => f.endsWith('.py')); + assert(pyFiles.length > 0 || rel.some(f => /\.(html|csv|json|txt|md|png)$/i.test(f)), 'python/data task should contain scripts or produced artifacts'); + for (const f of pyFiles.slice(0, 20)) { + child_process.execFileSync('python', ['-m', 'py_compile', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); + } +} else { + for (const f of files.filter(f => f.endsWith('.js')).slice(0, 20)) { + child_process.execFileSync('node', ['--check', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); + } +} + +for (const pat of EXPECTED) { + assert(existsPattern(rel, pat), 'missing expected artifact pattern after verifier: ' + pat); +} + +console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); diff --git a/task_039/tests/validate_enhanced_cases.sh b/task_039/tests/validate_enhanced_cases.sh new file mode 100644 index 0000000000000000000000000000000000000000..2a8deb47ebbbdac4dea1b85a2eb4e1c384293a92 --- /dev/null +++ b/task_039/tests/validate_enhanced_cases.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +set -euo pipefail + +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +TEMP_DIR="$(mktemp -d /tmp/task-060-enhanced-XXXXXX)" +cleanup() { rm -rf -- "$TEMP_DIR"; } +trap cleanup EXIT + +# Preserve legitimate local packages and support assets, not only root Go files. +tar --exclude='./tests' --exclude='./logs' --exclude='./.git' -cf - . | tar -xf - -C "$TEMP_DIR" +cp "$TEST_DIR/enhanced_cases_test.go.fixture" "$TEMP_DIR/enhanced_cases_test.go" +cp ./sensitive_words.txt "$TEMP_DIR/sensitive_words.txt" +test -f "$TEMP_DIR/go.mod" + +export GOPROXY=off +export GOSUMDB=off +# Reuse Go's container-local compilation cache across the five isolated test +# cases. A fresh empty cache per case can spend the 45s limit compiling stdlib. +export HARBOR_TEST_SEED=60001 +command -v timeout >/dev/null 2>&1 + +case "${1:-}" in + '') test_names=(TestEnhancedDistinctWordsAcrossAllContentTypes TestEnhancedRepeatedConfigurationReplacement TestEnhancedAuditTrailForMultipleAttempts TestEnhancedFileConfigAndSubmission TestEnhancedInvalidTypeAndDefensiveCopies) ;; + ENHANCED_CASE_1) test_names=(TestEnhancedDistinctWordsAcrossAllContentTypes) ;; + ENHANCED_CASE_2) test_names=(TestEnhancedRepeatedConfigurationReplacement) ;; + ENHANCED_CASE_3) test_names=(TestEnhancedAuditTrailForMultipleAttempts) ;; + ENHANCED_CASE_4) test_names=(TestEnhancedFileConfigAndSubmission) ;; + ENHANCED_CASE_5) test_names=(TestEnhancedInvalidTypeAndDefensiveCopies TestEnhancedWordOwnershipAndEmptyReplacement) ;; + *) echo "unknown enhanced case: $1" >&2; exit 2 ;; +esac + +for test_name in "${test_names[@]}"; do + (cd "$TEMP_DIR" && timeout --signal=TERM --kill-after=5s 45s go test -count=1 -run "^${test_name}$" ./...) +done +echo "task 60 enhanced cases passed (${#test_names[@]}/${#test_names[@]})" diff --git a/task_040/acceptance_checklist.json b/task_040/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..1d192e715662381f9c32af5f3f4a9a1b50a6da11 --- /dev/null +++ b/task_040/acceptance_checklist.json @@ -0,0 +1,20 @@ +{ + "task_id": 62, + "category": "frontend_development", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Provides an actual interactive first screen.", + "Persists state or handles keyboard/mouse interactions when requested." + ], + "input_assets": [ + "index.html" + ], + "expected_outputs": [], + "risk_notes": [ + "A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_040/environment/Dockerfile b/task_040/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_040/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_040/environment/code/index.html b/task_040/environment/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..920338249f5005c0ba69354f241bc33f27d0d175 --- /dev/null +++ b/task_040/environment/code/index.html @@ -0,0 +1,20 @@ + + + + + Answer Theme Toggle Fixture + + + +
      +
      +
      Question list
      +
      Question detail
      +
      Comments
      +
      + + diff --git a/task_040/environment/docker-compose.yaml b/task_040/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_040/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_040/instruction.md b/task_040/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e59ae31d761d57eddc4bb914312ccc2b64547019 --- /dev/null +++ b/task_040/instruction.md @@ -0,0 +1,14 @@ +# Add a one-click theme switch to the discussion page + +Extend the supplied `index.html` with a prominent button that switches the whole page between light and dark modes. Keep it usable offline. + +## Interface + +Mark the button with `data-testid="theme-toggle"`. Preserve the supplied contents and `data-testid` values `question-list`, `question-detail` and `comment-area`. Either theme may be initial; no CSS class, theme attribute or storage key is prescribed. + +## Acceptance Checklist + +- One click switches both the body and all three regions in the same direction. The dark background is less luminous than the light background in each. A brief transition is allowed if it settles within five seconds. +- Each effective background changes by at least 32 on the weighted RGB scale `0.2126R + 0.7152G + 0.0722B`, using 0–255 channel values. Transparent regions may inherit their parent backgrounds. +- Repeated clicks alternate between the same two visual states; ten toggles restore the initial state. A refresh preserves the selected theme between clicks. +- Toggling and refreshing do not alter page text or cause browser errors. diff --git a/task_040/quality_notes.md b/task_040/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..177ca6b7cbc2fc2f6d24f4876159792c81d4b86b --- /dev/null +++ b/task_040/quality_notes.md @@ -0,0 +1,3 @@ +# Quality Notes + +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. \ No newline at end of file diff --git a/task_040/solution/README.md b/task_040/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_040/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_040/solution/code/index.html b/task_040/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..9050aad0c5862f3730502f058b3c655f7e742f03 --- /dev/null +++ b/task_040/solution/code/index.html @@ -0,0 +1,2 @@ + +Theme Toggle
      Question list
      Question detail
      Comments
      diff --git a/task_040/solution/solve.sh b/task_040/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_040/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_040/task.toml b/task_040/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_040/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_040/task_meta.json b/task_040/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..6ba26d6237ec7b3cb0e4a8406bef468cb52fa1e9 --- /dev/null +++ b/task_040/task_meta.json @@ -0,0 +1,24 @@ +{ + "task_id": 62, + "task_category": "frontend_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 1, + "language": "javascript", + "tool_files_from_selected_trace": [ + "common.ts", + "index.scss", + "index.ts", + "index.tsx", + "interface.ts", + "package.json", + "themeSetting.ts" + ], + "input_assets": [ + "index.html" + ], + "expected_outputs": [], + "source_row_id": 372, + "repair_revision": "2026-09-29", + "instruction_sha256": "cef78b98fbcf36fa3ff06e1f68809a0549a335d989e7cb578a9332db66b2eb36" +} diff --git a/task_040/tests/_shared/contract_checker.js b/task_040/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_040/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_040/tests/_shared/static_enhancer.sh b/task_040/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_040/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_040/tests/enhancement_cases.json b/task_040/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..aa3b82226721019bd84ab052be9a7a035bbae293 --- /dev/null +++ b/task_040/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "用户点击按钮时,应能立即在深色模式和亮色模式之间切换;", + "validator": "validate_enhanced_cases.js#caseImmediateLightDarkTransition", + "behavior": "单击可见按钮后,页面背景立即产生明确的明暗模式变化。" + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "切换应覆盖整个页面(含问题列表、详情页、评论区等),而不是仅部分组件。", + "validator": "validate_enhanced_cases.js#caseEveryAreaChanges", + "behavior": "逐一断言问题列表、详情区和评论区的计算样式均随同一次主题切换变化。" + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "用户点击按钮时,应能立即在深色模式和亮色模式之间切换;", + "validator": "validate_enhanced_cases.js#caseBidirectionalRoundTrip", + "behavior": "连续点击两次分别切到另一主题并完整恢复初始页面样式,验证双向切换而非一次性状态。" + } +] diff --git a/task_040/tests/review_hard.js b/task_040/tests/review_hard.js new file mode 100644 index 0000000000000000000000000000000000000000..c70852fbdf3f007cabc81d77ee7e1d95c1b3db33 --- /dev/null +++ b/task_040/tests/review_hard.js @@ -0,0 +1,77 @@ +const fs = require('fs'); +const path = require('path'); +const {pathToFileURL} = require('url'); +const {chromium} = require('playwright'); +const assert = require('assert'); + +async function state(page) { + return page.evaluate(() => { + const ids = ['question-list', 'question-detail', 'comment-area']; + const canvas = document.createElement('canvas'); + canvas.width = canvas.height = 1; + const paint = canvas.getContext('2d', {colorSpace: 'srgb', willReadFrequently: true}); + const effectiveBackground = element => { + const ancestors = []; + for (let node = element; node; node = node.parentElement) ancestors.unshift(node); + paint.fillStyle = '#fff'; + paint.fillRect(0, 0, 1, 1); + for (const ancestor of ancestors) { + paint.fillStyle = getComputedStyle(ancestor).backgroundColor; + paint.fillRect(0, 0, 1, 1); + } + return [...paint.getImageData(0, 0, 1, 1).data].slice(0, 3); + }; + const elements = [document.body, ...ids.map(id => document.querySelector(`[data-testid="${id}"]`))]; + if (elements.some(element => !element)) throw new Error('missing required page area'); + return elements.map(element => ({background: effectiveBackground(element), color: getComputedStyle(element).color, + text: element === document.body ? '' : element.innerText.trim().replace(/\s+/g, ' ')})); + }); +} + +async function settled(page, accept) { + const deadline = Date.now() + 5000; + let previous; + while (Date.now() < deadline) { + const current = await state(page); + if (accept(current) && JSON.stringify(current) === JSON.stringify(previous)) return current; + previous = current; + await page.waitForTimeout(100); + } + throw new Error('theme did not reach the required stable visible state within five seconds'); +} + +const luminance = color => color[0]*0.2126 + color[1]*0.7152 + color[2]*0.0722; +(async () => { + const browser = await chromium.launch({headless: true}); + try { + const page = await browser.newPage({viewport: {width: 1100, height: 760}}); + const errors = []; + page.on('pageerror', error => errors.push(error.message)); + await page.goto(pathToFileURL(path.join(process.argv[2] || process.cwd(), 'index.html')).href); + const toggle = page.locator('[data-testid="theme-toggle"]'); + assert(await toggle.isVisible(), 'theme toggle must be visible'); + const initial = await settled(page, () => true); + assert.deepStrictEqual(initial.slice(1).map(area => area.text), ['Question list', 'Question detail', 'Comments'], 'preserve the supplied content'); + let previous = initial; + const snapshots = []; + for (let index = 0; index < 10; index++) { + await toggle.click(); + const current = await settled(page, candidate => candidate.every((area, i) => Math.abs(luminance(area.background)-luminance(previous[i].background)) >= 32)); + const direction = Math.sign(luminance(current[0].background)-luminance(previous[0].background)); + current.forEach((area, i) => { + assert.equal(Math.sign(luminance(area.background)-luminance(previous[i].background)), direction, 'all areas must switch in the same light/dark direction'); + assert.equal(area.text, initial[i].text, 'theme switch changed page content'); + }); + if (index < 2) { + fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + await page.screenshot({path: `/logs/verifier/visual-audit/theme-${index+1}.png`, fullPage: true}); + snapshots.push(current); + } else assert.deepStrictEqual(current, snapshots[index%2], 'repeated toggle does not restore the same whole-page theme'); + await page.reload(); + await settled(page, candidate => JSON.stringify(candidate) === JSON.stringify(current)); + previous = current; + } + assert.deepStrictEqual(previous, initial, 'ten toggles must return to the initial theme'); + assert.equal(errors.length, 0, errors.join(' | ')); + } finally {await browser.close();} +})().catch(error => {console.error(error); process.exit(1);}); diff --git a/task_040/tests/review_legacy.sh b/task_040/tests/review_legacy.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ab2150eb79f6f15b53d20b21738b84bbe0d8003 --- /dev/null +++ b/task_040/tests/review_legacy.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_ui_behavior.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_040/tests/test.sh b/task_040/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3822fb7c2c0f7ef0629799c8aaefe4e5f674ce4e --- /dev/null +++ b/task_040/tests/test.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -uo pipefail +mkdir -p /logs/verifier +echo 0 > /logs/verifier/reward.txt +if timeout 120s node /tests/review_hard.js /app 2>&1 | tee /logs/verifier/review_hard.log; then + echo 1 > /logs/verifier/reward.txt +fi diff --git a/task_040/tests/validate_aaav_dynamic.js b/task_040/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..9ea71d5d8a7591495cbbb926637bb3a8f4daa945 --- /dev/null +++ b/task_040/tests/validate_aaav_dynamic.js @@ -0,0 +1,148 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 62; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_040/tests/validate_browser_smoke.js b/task_040/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_040/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_040/tests/validate_enhanced_cases.js b/task_040/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..53369c1de8a9e44365c2e6d881b9669ef4591875 --- /dev/null +++ b/task_040/tests/validate_enhanced_cases.js @@ -0,0 +1,149 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const ACTION_TIMEOUT_MS = 5_000; +const CASE_TIMEOUT_MS = 15_000; +const AREA_IDS = ['question-list', 'question-detail', 'comment-area']; +process.env.HARBOR_TEST_SEED = '62001'; + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +async function within(ms, label, work) { + let timer; + try { + return await Promise.race([ + work(), + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms); + }), + ]); + } finally { + clearTimeout(timer); + } +} + +async function freshPage(browser) { + const context = await browser.newContext({ offline: true, serviceWorkers: 'block' }); + const page = await context.newPage(); + page.setDefaultTimeout(ACTION_TIMEOUT_MS); + page.setDefaultNavigationTimeout(ACTION_TIMEOUT_MS); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { + waitUntil: 'domcontentloaded', + timeout: ACTION_TIMEOUT_MS, + }); + return { context, page }; +} + +async function snapshot(page) { + return page.evaluate((ids) => { + const styleOf = (element) => { + if (!element) throw new Error('required page area is missing'); + const style = getComputedStyle(element); + return { background: style.backgroundColor, color: style.color }; + }; + return { + body: styleOf(document.body), + areas: Object.fromEntries(ids.map((id) => [id, styleOf(document.querySelector(`[data-testid="${id}"]`))])), + }; + }, AREA_IDS); +} + +function styleKey(style) { + return `${style.background}|${style.color}`; +} + +async function themeToggle(page) { + const control = page.locator('[data-testid="theme-toggle"]'); + assert(await control.count() === 1, 'fixture theme-toggle button must exist exactly once'); + assert(await control.isVisible(), 'theme-toggle button must be visible'); + return control; +} + +function rgb(color) { + const values = color.match(/[\d.]+/g); + assert(values && values.length >= 3, `unable to parse computed color: ${color}`); + return values.slice(0, 3).map(Number); +} + +function luminance(color) { + const [r, g, b] = rgb(color); + return 0.2126 * r + 0.7152 * g + 0.0722 * b; +} + +// ENHANCED_CASE_1: one click makes an immediate, visible light/dark transition. +async function caseImmediateLightDarkTransition(browser) { + const { context, page } = await freshPage(browser); + try { + const toggle = await themeToggle(page); + const before = await snapshot(page); + await toggle.click({ timeout: ACTION_TIMEOUT_MS }); + await page.waitForTimeout(300); + const after = await snapshot(page); + const delta = Math.abs(luminance(before.body.background) - luminance(after.body.background)); + assert(delta > 0, `body background should visibly switch light/dark modes (luminance delta ${delta.toFixed(1)})`); + } finally { + await context.close(); + } +} + +// ENHANCED_CASE_2: every named page region participates in the same toggle. +async function caseEveryAreaChanges(browser) { + const { context, page } = await freshPage(browser); + try { + const toggle = await themeToggle(page); + const before = await snapshot(page); + await toggle.click({ timeout: ACTION_TIMEOUT_MS }); + await page.waitForTimeout(300); + const after = await snapshot(page); + for (const id of AREA_IDS) { + assert( + styleKey(before.areas[id]) !== styleKey(after.areas[id]), + `${id} should change computed foreground/background styles with the global theme` + ); + } + } finally { + await context.close(); + } +} + +// ENHANCED_CASE_3: a second click switches back and restores the entire page. +async function caseBidirectionalRoundTrip(browser) { + const { context, page } = await freshPage(browser); + try { + const toggle = await themeToggle(page); + const initial = await snapshot(page); + await toggle.click({ timeout: ACTION_TIMEOUT_MS }); + const opposite = await snapshot(page); + await toggle.click({ timeout: ACTION_TIMEOUT_MS }); + const restored = await snapshot(page); + assert(JSON.stringify(opposite) !== JSON.stringify(initial), 'first click should switch to the opposite theme'); + assert(JSON.stringify(restored) === JSON.stringify(initial), 'second click should restore the original whole-page theme'); + } finally { + await context.close(); + } +} + +const enhancedCases = { + ENHANCED_CASE_1: caseImmediateLightDarkTransition, + ENHANCED_CASE_2: caseEveryAreaChanges, + ENHANCED_CASE_3: caseBidirectionalRoundTrip, +}; + +(async () => { + const requested = process.argv[2]; + assert(!requested || enhancedCases[requested], `unknown enhanced case: ${requested}`); + const browser = await chromium.launch({ headless: true, timeout: ACTION_TIMEOUT_MS }); + try { + const entries = requested ? [[requested, enhancedCases[requested]]] : Object.entries(enhancedCases); + for (const [caseId, run] of entries) await within(CASE_TIMEOUT_MS, caseId, () => run(browser)); + console.log(`task 62 enhanced cases passed (${entries.length}/${entries.length})`); + } finally { + await browser.close(); + } +})().catch((err) => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_040/tests/validate_semantics.js b/task_040/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_040/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_040/tests/validate_ui_behavior.js b/task_040/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..d71192deee7cc5bec2ece52f7c67d1555464554d --- /dev/null +++ b/task_040/tests/validate_ui_behavior.js @@ -0,0 +1,38 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1000, height: 700 } }); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + const toggle = page.locator('[data-testid="theme-toggle"], button:has-text("主题切换")').first(); + if (!(await toggle.isVisible())) throw new Error('prominent theme toggle button should be visible near top'); + const before = await page.evaluate(() => { + const ids = ['question-list', 'question-detail', 'comment-area']; + return ids.map(id => { + const el = document.querySelector(`[data-testid="${id}"]`); + const s = getComputedStyle(el); + return `${s.backgroundColor}|${s.color}`; + }).join('||') + '::' + getComputedStyle(document.body).backgroundColor; + }); + await toggle.click(); + await page.waitForTimeout(150); + const mode = await page.evaluate(() => document.documentElement.dataset.theme || document.body.dataset.theme || document.documentElement.className + ' ' + document.body.className); + const after = await page.evaluate(() => { + const ids = ['question-list', 'question-detail', 'comment-area']; + return ids.map(id => { + const el = document.querySelector(`[data-testid="${id}"]`); + const s = getComputedStyle(el); + return `${s.backgroundColor}|${s.color}`; + }).join('||') + '::' + getComputedStyle(document.body).backgroundColor; + }); + if (before === after) throw new Error('theme toggle should immediately change visual styles across the page'); + for (const id of ['question-list', 'question-detail', 'comment-area']) { + const changed = await page.locator(`[data-testid="${id}"]`).evaluate(el => { + const s = getComputedStyle(el); + return s.backgroundColor !== 'rgba(0, 0, 0, 0)' && s.color !== ''; + }); + if (!changed) throw new Error(`${id} should participate in global theme styling`); + } + await browser.close(); +})().catch(err => { console.error(err && err.stack || err); process.exit(1); }); diff --git a/task_041/acceptance_checklist.json b/task_041/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..70770cc35def2e8a1d0a99078a972b5d3383f944 --- /dev/null +++ b/task_041/acceptance_checklist.json @@ -0,0 +1,18 @@ +{ + "task_id": 64, + "category": "frontend_development", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies." + ], + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "risk_notes": [ + "This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_041/environment/Dockerfile b/task_041/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_041/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_041/environment/code/.gitkeep b/task_041/environment/code/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/task_041/environment/docker-compose.yaml b/task_041/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_041/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_041/instruction.md b/task_041/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1c12edfd45bf268bf82ab08b4a1c4f13cb7b1775 --- /dev/null +++ b/task_041/instruction.md @@ -0,0 +1,31 @@ +# Build a Gold Miner mini-game + +Create an offline `index.html` with a home menu and one playable canvas level. + +## Starting a game + +On the home menu, let the player choose single-player or two-player mode and click a separate Start button. Selecting a mode leaves play inactive until Start is clicked. Before starting, the state may expose idle preview hooks, but neither key launches a hook. Start opens the same playable level with A's hook in single-player mode or both A's and B's hooks in two-player mode. + +Mark the home menu with `data-testid="mode-menu"` and the Start control with `data-testid="start-game"`. For a native select, use `data-testid="game-mode"` and option values `single` and `double`. For other controls, put `data-testid="mode-single"` and `data-testid="mode-double"` on the respective clickable choices. + +## Gameplay + +- Each player has a swinging surface hook. Press `s` for A or `ArrowDown` for B to launch that hook along its current angle. A miss at the edge returns along the same path without scoring. +- The default field contains small and large gold, stones of at least two sizes, bombs, pigs and at least three diamonds. Weight and value vary with the size of gold and stones. Stones are heaviest; diamonds and pigs lightest. Diamonds are the most valuable objects at 800 points, and bombs are the least valuable at 2 points. Pigs are worth 3 points and move slowly back and forth horizontally. All other item values are strictly between 2 and 800 points. +- A hook retrieves the object it hits. Heavier catches retract more slowly. Bombs explode visibly and retract quickly. Each completed catch removes the item and credits its value once. Put A's numeric score alone in `#scoreA` and show a visible “Victory” or “胜利” surprise upon reaching the default target of 800. + +## State interface + +Expose `window.gameTest` with `reset(config)`, `step(milliseconds)`, `dropClaw(player = 'A')` and `state()`, driving the same simulation and rendering as the visible game. + +- `reset` accepts `{mode?, targetScore?, items?}`; `mode: 'double'` activates both hooks. A supplied `targetScore` replaces 800 for that round. Report it as `target` and set `won` and show the victory message when either player's score reaches or exceeds it. Items are `{type,x,y,def?}` in canvas pixels, with type `diamond`, `pig`, `bomb`, `goldS`, `goldL` or `stone`. In a single-player reset hook A points vertically down from horizontal coordinate 320. +- `step` advances and renders the game in steps of about 16 ms. `dropClaw` performs the same action as the matching key. +- `state()` returns `{scores:{A,B},target,won,explosions,items:[{type,x,y,value,weight,grabbed}],hooks:[{player,state,len,holding,fastReturn}]}`. Idle hooks are in `'swing'`, launched hooks in `'extend'`. Length `len` is in pixels; `holding` is a type or null. + +## Acceptance Checklist + +- The home menu supports both modes. Selecting either mode leaves play inactive. Clicking Start enters the selected game, and the live keyboard inputs launch the corresponding hooks. +- The default field contains every listed item type, including enough diamonds and differently sized stones. Diamonds and bombs set the upper and lower bounds for item values. +- Both key controls launch their own hooks; a miss returns to idle within four seconds, and a pig moves even if it has no direction specified. +- With an item directly beneath the reset hook A at (320, 110), light and heavy catches are still retracting after 100 ms, with the heavy catch slower. A bomb at that position retracts and adds 2 points within 80 ms. At 80 ms the explosion is still visible and changes at least 100 canvas pixels. A diamond at that position returns within three seconds. +- The visible score, explosion and victory agree with gameplay state. Victory uses the current round's default or injected target. Reset clears prior scores, explosions and victory messages. diff --git a/task_041/quality_notes.md b/task_041/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..160c1210219d27d8536b80599a676d09b212afe9 --- /dev/null +++ b/task_041/quality_notes.md @@ -0,0 +1,3 @@ +# Quality Notes + +- This task came from a multi-turn trajectory; the enhanced instruction preserves all user turns. \ No newline at end of file diff --git a/task_041/solution/README.md b/task_041/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_041/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_041/solution/code/index.html b/task_041/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..a95955687c8e37a7aeb39fcf97c64934ae20b63a --- /dev/null +++ b/task_041/solution/code/index.html @@ -0,0 +1,248 @@ + + + + + +Gold Miner + + + +

      Gold Miner

      + + + + + + diff --git a/task_041/solution/solve.sh b/task_041/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_041/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_041/task.toml b/task_041/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_041/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_041/task_meta.json b/task_041/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..be4a2a754819714ecdb3401918f89e92cf7cec8e --- /dev/null +++ b/task_041/task_meta.json @@ -0,0 +1,20 @@ +{ + "task_id": 64, + "task_category": "frontend_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 6, + "language": "javascript", + "tool_files_from_selected_trace": [ + "gold-miner-game-fixed.html", + "gold-miner-game.html", + "gold-miner-simple.html" + ], + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "source_row_id": 384, + "repair_revision": "2026-09-29", + "instruction_sha256": "bb3d3b80c189bb0e86cecc35be4bea7dfe474aa462f86ee15d0adaaa35b416d4" +} diff --git a/task_041/tests/_shared/contract_checker.js b/task_041/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_041/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_041/tests/_shared/static_enhancer.sh b/task_041/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_041/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_041/tests/enhancement_cases.json b/task_041/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..b6ebeca734184608f481e14e5c32e1f9b1d77cdb --- /dev/null +++ b/task_041/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "游戏首页可以选择单人或者双人模式", + "validator": "validate_enhanced_cases.js", + "behavior": "在可见首页选择单双人模式,确认开始前无法放钩,点击开始后出现对应玩家的钩子并响应真实按键。" + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "玩家可以用s键(玩家A)或者方向键下(玩家B)来选择钩子下放时机", + "validator": "validate_enhanced_cases.js", + "behavior": "在双人模式用真实按键放钩,验证空钩返回、玩家 B 抓取和独立记分。" + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "钻石的最值钱(800,且至少有3个钻石),炸弹最不值钱(2),金矿和石头按照大小来给定价格(有不同的大小),小猪会左右横向跑(价值3,速度较为缓慢)", + "validator": "validate_enhanced_cases.js", + "behavior": "实际启动两种模式后检查默认关卡物品种类、数量和价值上下界,再用确定性场景验证负重、炸弹爆炸和钻石胜利。" + } +] diff --git a/task_041/tests/test.sh b/task_041/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5b93094e3a03087c4e33dbad0e01077a559a54e5 --- /dev/null +++ b/task_041/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_041/tests/validate_aaav_dynamic.js b/task_041/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..06f13ec133a7977c62abbec3bc3082eb65a40bbe --- /dev/null +++ b/task_041/tests/validate_aaav_dynamic.js @@ -0,0 +1,148 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 64; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_041/tests/validate_browser_smoke.js b/task_041/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..658969881ac5de913eb45fddd8f4e1aae56c7ff5 --- /dev/null +++ b/task_041/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_041/tests/validate_enhanced_cases.js b/task_041/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..ff7bb546c950f7f3586f7e2df887fec1fc8d4408 --- /dev/null +++ b/task_041/tests/validate_enhanced_cases.js @@ -0,0 +1,201 @@ +const fs = require('fs'); +const path = require('path'); +const {pathToFileURL} = require('url'); +const {chromium} = require('playwright'); +const assert = require('assert'); + +function assertDefaultField(items) { + assert(items.filter(item => item.type === 'diamond').length >= 3, 'default level needs at least three diamonds'); + for (const type of ['goldS', 'goldL', 'stone', 'pig', 'bomb']) { + assert(items.some(item => item.type === type), 'default level omitted ' + type); + } + for (const item of items) { + assert(Number.isFinite(item.x) && Number.isFinite(item.y) && item.weight > 0); + if (item.type === 'diamond') assert.equal(item.value, 800); + else if (item.type === 'bomb') assert.equal(item.value, 2); + else { + assert(Number.isFinite(item.value) && item.value > 2 && item.value < 800, + item.type + ' must be worth more than a bomb and less than a diamond'); + if (item.type === 'pig') assert.equal(item.value, 3); + } + } + const stones = items.filter(item => item.type === 'stone'); + assert(new Set(stones.map(item => item.weight)).size >= 2 && new Set(stones.map(item => item.value)).size >= 2, + 'different stone sizes need different weight and price'); +} + +async function startFromHome(page, entry, mode) { + await page.goto(entry); + const menu = page.getByTestId('mode-menu'); + await menu.waitFor({state: 'visible'}); + const select = menu.getByTestId('game-mode'); + if (await select.isVisible()) { + await select.selectOption(mode); + } else { + await menu.getByTestId('mode-' + mode).click(); + } + const start = menu.getByTestId('start-game'); + await start.waitFor({state: 'visible'}); + await start.focus(); + + const state = () => page.evaluate(() => gameTest.state()); + for (const key of ['s', 'ArrowDown']) { + await page.keyboard.press(key); + assert((await state()).hooks.every(hook => hook.state === 'swing' && hook.len === 0), + 'selecting a mode must not allow a hook to launch before Start'); + } + await start.click(); + await page.locator('canvas').first().waitFor({state: 'visible'}); + const players = mode === 'single' ? ['A'] : ['A', 'B']; + const current = await state(); + assert.deepStrictEqual(current.hooks.map(hook => hook.player).sort(), players, + 'Start must activate the hooks for the selected mode'); + assertDefaultField(current.items); + for (const player of players) { + await page.keyboard.press(player === 'A' ? 's' : 'ArrowDown'); + const after = await state(); + assert(after.hooks.some(hook => hook.player === player && (hook.state !== 'swing' || hook.len > 0)) + || after.scores[player] > current.scores[player], 'the live game did not launch hook ' + player); + } +} + +(async () => { + const browser = await chromium.launch({headless: true}); + try { + const page = await browser.newPage({viewport: {width: 1000, height: 760}}); + const errors = []; + page.on('pageerror', error => errors.push(error.message)); + const entry = pathToFileURL(path.join(process.cwd(), 'index.html')).href; + const state = () => page.evaluate(() => gameTest.state()); + const reset = config => page.evaluate(config => gameTest.reset(config), config); + const step = ms => page.evaluate(ms => gameTest.step(ms), ms); + const waitForCatch = async (player, initialCount) => { + for (let elapsed = 0; elapsed < 15_000; elapsed += 250) { + await step(250); + const result = await state(); + if (result.items.length < initialCount) return result; + const hook = result.hooks.find(hook => hook.player === player); + if (hook.state === 'swing' && hook.holding === null) break; + } + throw Error(`hook ${player} did not retrieve an on-path target`); + }; + const capture = async name => { + fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + await page.screenshot({path: `/logs/verifier/visual-audit/${name}.png`, fullPage: true}); + }; + await startFromHome(page, entry, 'single'); + await capture('default-level'); + await startFromHome(page, entry, 'double'); + + await reset({items: [{type: 'pig', x: 200, y: 300}]}); + await step(160); + let current = await state(); + assert(Number.isFinite(current.items[0].x) && current.items[0].x !== 200 && current.items[0].y === 300, 'pig must move horizontally using the actual injected state'); + + await reset({mode: 'double', items: []}); + await page.keyboard.press('s'); + await page.keyboard.press('ArrowDown'); + current = await state(); + assert.deepStrictEqual(current.hooks.map(hook => hook.player).sort(), ['A', 'B']); + assert(current.hooks.every(hook => hook.state === 'extend'), 'both keyboard controls must launch their corresponding hook'); + await step(160); + assert((await state()).hooks.every(hook => hook.len > 0)); + await capture('two-player-hooks'); + await step(4000); + current = await state(); + assert(current.hooks.every(hook => hook.state === 'swing' && hook.len === 0), 'empty catches must return from the boundary'); + assert.deepStrictEqual(current.scores, {A: 0, B: 0}); + + // The problem does not specify B's anchor. Supply targets across the + // field rather than binding the test to the reference's x coordinate. + const canvas = page.locator('canvas').first(); + const dimensions = await canvas.evaluate(({width, height}) => ({width, height})); + const targets = []; + for (let y = 8; y < dimensions.height; y += 12) { + for (let x = 8; x < dimensions.width; x += 12) targets.push({type: 'goldS', x, y}); + } + let value; + let caught = false; + for (const swingTime of [0, 176, 368, 640, 1008, 1536]) { + await reset({mode: 'double', items: targets, targetScore: 10_000}); + await step(swingTime); + value = (await state()).items[0].value; + await page.keyboard.press('ArrowDown'); + try { + current = await waitForCatch('B', targets.length); + caught = true; + break; + } catch (error) { + if (!error.message.includes('did not retrieve an on-path target')) throw error; + } + } + assert(caught, 'B could not catch an item at any tested swing phase'); + assert.deepStrictEqual(current.scores, {A: 0, B: value}, 'B must be able to catch and receive credit without changing A’s score'); + assert.equal(current.items.length, targets.length - 1, 'a catch removes exactly its own target'); + await step(160); + assert.deepStrictEqual((await state()).scores, current.scores, 'one catch must not be credited repeatedly'); + + // A starts down at x=320. Include one on-path object at a new + // distance and a tempting off-path target on the same row. + await reset({items: [{type: 'diamond', x: 100, y: 161}, {type: 'goldS', x: 320, y: 161}]}); + const goldValue = (await state()).items[1].value; + await page.keyboard.press('s'); + current = await waitForCatch('A', 2); + assert.deepStrictEqual(current.scores, {A: goldValue, B: 0}, 'the hook should catch the object it intersects'); + assert.equal(current.items.length, 1, 'the off-path object should remain'); + assert.equal(current.items[0].type, 'diamond', 'the off-path object must not be selected by array order or value'); + + const catchLength = type => page.evaluate(type => { + gameTest.reset({items: [{type, x: 320, y: 110}]}); + gameTest.dropClaw(); gameTest.step(100); + return gameTest.state().hooks[0].len; + }, type); + assert(await catchLength('stone') > await catchLength('goldS'), 'heavier catch must reel more slowly'); + + await reset({items: [{type: 'bomb', x: 320, y: 110}], targetScore: 999}); + await page.evaluate(() => gameTest.dropClaw()); + await step(80); + current = await state(); + assert.equal(current.explosions, 1); + assert.equal(current.scores.A, 2); + assert.equal(current.items.length, 0); + assert.equal(current.hooks[0].holding, null); + assert.equal(await page.locator('#scoreA').innerText(), '2'); + const explosionFrame = await page.locator('canvas').first().evaluate(canvas => Array.from(canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).data)); + await capture('visible-bomb-explosion'); + await reset({items: [], targetScore: 999}); + const changedPixels = await page.locator('canvas').first().evaluate((canvas, before) => { + const current = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).data; + let count = 0; + for (let i = 0; i < current.length; i += 4) if (Math.abs(current[i]-before[i])+Math.abs(current[i+1]-before[i+1])+Math.abs(current[i+2]-before[i+2]) > 15) count++; + return count; + }, explosionFrame); + assert(changedPixels >= 100, 'the visible bomb effect must change at least 100 canvas pixels'); + + const diamond = {type: 'diamond', x: 320, y: 110}; + await reset({items: [diamond]}); + await page.evaluate(() => gameTest.dropClaw()); + await step(3000); + current = await state(); + assert.equal(current.scores.A, 800); + assert(current.won && /胜利|victory|彩蛋/i.test(await page.locator('body').innerText())); + assert.equal(await page.locator('#scoreA').innerText(), '800'); + await capture('diamond-victory'); + for (const targetScore of [600, 1000]) { + await reset({items: [diamond], targetScore}); + await page.evaluate(() => gameTest.dropClaw()); + await step(3000); + const result = await state(); + assert.equal(result.target, targetScore, 'reset must report the injected target'); + assert.equal(result.scores.A, 800, 'the custom target must not change the item value'); + assert.equal(result.won, result.scores.A >= targetScore, 'victory must follow the injected target'); + if (result.won) { + assert(/胜利|victory|彩蛋/i.test(await page.locator('body').innerText()), 'meeting the injected target must show victory'); + } + } + await reset({items: [], targetScore: 800}); + assert(!(await state()).won && (await state()).explosions === 0); + assert(!/victory!|胜利彩蛋/i.test(await page.locator('body').innerText()), 'reset must clear the previous victory message'); + assert.equal(errors.length, 0, errors.join(' | ')); + } finally {await browser.close();} +})().catch(error => {console.error(error); process.exit(1);}); diff --git a/task_041/tests/validate_semantics.js b/task_041/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..d10cc042756f6e9dba39b8f2484d59aaea267cc8 --- /dev/null +++ b/task_041/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_042/acceptance_checklist.json b/task_042/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..e776782d7ad2c493194b8fd182cf0b5ace52f4fe --- /dev/null +++ b/task_042/acceptance_checklist.json @@ -0,0 +1,16 @@ +{ + "task_id": 65, + "category": "frontend_development", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies." + ], + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "risk_notes": [], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_042/environment/Dockerfile b/task_042/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_042/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_042/environment/code/.gitkeep b/task_042/environment/code/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/task_042/environment/docker-compose.yaml b/task_042/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_042/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_042/instruction.md b/task_042/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2b280e9c4ae9b81da3760db7a0ddb8f7a3b3dbe2 --- /dev/null +++ b/task_042/instruction.md @@ -0,0 +1,25 @@ +# Build a colony excavation and survival game + +Create an offline `index.html` inspired by the basic mechanics of *Oxygen Not Included*. Show a two-dimensional underground map, a lit starting area, unknown rock and a duplicant printer. + +## Gameplay + +- Choose a duplicant and a cell to walk through known space or excavate rock. Walk one cell at a time and climb at most one cell; fall through open space under gravity. Dig up to one cell horizontally and three cells upward. Excavation opens and lights rock; a move into unknown space must not dig it, and a dig on known empty space must not move the duplicant. +- Continue exploring on all four sides of the starting area and render all current cells, known and unknown. +- Display environmental oxygen and each duplicant's hydration; `#oxygen` contains only the current numeric oxygen value. Oxygen falls by one per accumulated second, to a minimum of zero. Hydration declines over time; digging plain rock costs more than one hydration point immediately and costs stamina. Oxygen and water discovered during excavation replenish the corresponding values. Critical oxygen or hydration causes illness. +- Every ten seconds show the printer's yes/no question. Yes adds a randomly generated duplicant; no dismisses without adding one. + +## State and controls + +Expose `window.gameTest` with `reset(config)`, `move(row,col)`, `dig(row,col)`, `step(milliseconds)`, `answerPrint(yes)` and `state()`. These operate on the real game state and UI. `move`, `dig` and `step` return the resulting state. + +- `reset` accepts `{oxygen?,duplicant?,openCells?,resourceCells?}`. The duplicant accepts `{r,c,water}`; open cells are `[[r,c],...]`; supplied resource cells are `[{r,c,type},...]` with type `oxygen`, `water` or `open`. They are revealed by digging; other unknown cells use game probabilities. Rows increase downward. +- `state()` returns `{oxygen,duplicants:[{r,c,water,stamina,sick}],resources:{oxygen,water},dimensions:{rows,cols},printPending,map}`, with `map[row][col]` cells of shape `{type,known}`. +- Give each expansion control the corresponding `data-expand` value: `up`, `down`, `left`, `right`. Mark each map cell with `.cell`, `data-r` and `data-c`; mark oxygen with `id="oxygen"`, the prompt with `data-testid="print-prompt"` and responses with `data-answer-print="yes"` or `"no"`. + +## Acceptance Checklist + +- Known-space movement, gravity, legal excavation and blocked out-of-reach actions work via visible controls and the state interface. An outside-map destination first expands the appropriate edge without bypassing movement or digging constraints. +- Real cell clicks reveal injected resource results. Plain rock costs more hydration to dig than an idle second; oxygen and water replenish their corresponding values and the HUD stays in sync. +- After reset, only virtual time advances the state. Tick resource consumption per accumulated 1,000 ms; show the printer prompt per accumulated 10,000 ms. Accept or decline immediately; an answer with no pending prompt cannot create a duplicant. +- Each navigation control expands the requested edge and renders the complete larger map. diff --git a/task_042/quality_notes.md b/task_042/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..125a20b7b283c909235a49e7cd080f13240f2b2a --- /dev/null +++ b/task_042/quality_notes.md @@ -0,0 +1,2 @@ +# Quality Notes + diff --git a/task_042/solution/README.md b/task_042/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_042/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_042/solution/code/index.html b/task_042/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..57da11393fd7102cca2684bc08fd321b7a870362 --- /dev/null +++ b/task_042/solution/code/index.html @@ -0,0 +1,222 @@ + + + + + +Oxygen Not Included (Mini) + + + +

      Oxygen Not Included (Mini)

      +
      + Environmental Oxygen: 100% + +
      +
      +
      + + +
      +

      Select a duplicant, then click an adjacent rock to dig.

      +

      Print a new duplicant?

      + + + + diff --git a/task_042/solution/solve.sh b/task_042/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_042/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_042/task.toml b/task_042/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_042/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_042/task_meta.json b/task_042/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..0acbf7cd64d8a2a03491a57dfc83b2c006505a81 --- /dev/null +++ b/task_042/task_meta.json @@ -0,0 +1,18 @@ +{ + "task_id": 65, + "task_category": "frontend_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 1, + "language": "javascript", + "tool_files_from_selected_trace": [ + "index.html" + ], + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "source_row_id": 390, + "repair_revision": "2026-09-29", + "instruction_sha256": "6c8ee634238d369cfb7f243cd9d76b120def68ee9b7a8e34d24e400ec80715ab" +} diff --git a/task_042/tests/_shared/contract_checker.js b/task_042/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_042/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_042/tests/_shared/static_enhancer.sh b/task_042/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_042/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_042/tests/enhancement_cases.json b/task_042/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..1898f9216b027a85aec2c03b44d785b60a3695ae --- /dev/null +++ b/task_042/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "你需要显示环境氧气值和每个小人的缺水值。", + "validator": "validate_enhanced_cases.js", + "behavior": "从实际可见页面文本验证环境氧气和小人缺水均有数值,并确认至少显示一个小人状态。" + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "(点击对应的小人再点击岩石,对应的小人会自动前往挖掘),挖掘后这些区域变亮,不再昏暗", + "validator": "validate_enhanced_cases.js", + "behavior": "按二维渲染布局发现网格和小人,依次点击小人与可达的昏暗岩石,验证目标格变亮且小人的可见位置朝目标移动;不依赖业务 id 或 class 名。" + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "每隔 10 秒会提示你是否随机生成一个新的小人。", + "validator": "validate_enhanced_cases.js", + "behavior": "确定性推进受控计时器 10 秒,验证存在约 10 秒周期、出现生成决策,并在接受后新增小人或显示可操作提示。" + } +] diff --git a/task_042/tests/test.sh b/task_042/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5b93094e3a03087c4e33dbad0e01077a559a54e5 --- /dev/null +++ b/task_042/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_042/tests/validate_aaav_dynamic.js b/task_042/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..a6df01c8b9a4a208b78b75e79f2a0c8c237dce8d --- /dev/null +++ b/task_042/tests/validate_aaav_dynamic.js @@ -0,0 +1,148 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 65; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_042/tests/validate_browser_smoke.js b/task_042/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..658969881ac5de913eb45fddd8f4e1aae56c7ff5 --- /dev/null +++ b/task_042/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_042/tests/validate_enhanced_cases.js b/task_042/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..632f47f1f5e2d24867342f610dbd36ba388422a9 --- /dev/null +++ b/task_042/tests/validate_enhanced_cases.js @@ -0,0 +1,110 @@ +const fs = require('fs'); +const path = require('path'); +const {pathToFileURL} = require('url'); +const {chromium} = require('playwright'); +const assert = require('assert'); + +(async () => { + const browser = await chromium.launch({headless: true}); + try { + const page = await browser.newPage({viewport: {width: 1100, height: 760}}); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href); + const reset = config => page.evaluate(config => gameTest.reset(config), config); + const state = () => page.evaluate(() => gameTest.state()); + const capture = async name => { + fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + await page.screenshot({path: `/logs/verifier/visual-audit/${name}.png`, fullPage: true}); + }; + assert.equal(await page.locator('[data-expand]').count(), 4); + await reset({oxygen: 2, duplicant: {r: 5, c: 2, water: 2}, openCells: [[5, 2], [6, 2], [6, 3]]}); + let current = await page.evaluate(() => gameTest.step(2000)); + assert(current.oxygen === 0 && current.duplicants[0].sick); + assert.equal(current.duplicants[0].r, 6, 'gravity must move through known open space'); + current = await page.evaluate(() => gameTest.move(6, 3)); + assert.equal(current.duplicants[0].c, 3); + assert.equal(await page.locator('#oxygen').innerText(), '0'); + await capture('depleted-and-sick'); + + await reset({oxygen: 60, duplicant: {r: 6, c: 2, water: 60}, openCells: [[6, 2]]}); + current = await state(); + await page.waitForTimeout(1100); + assert.deepStrictEqual(await state(), current, 'real timers must not advance virtual-clock mode'); + await page.evaluate(() => gameTest.step(999)); + assert.equal((await state()).oxygen, 60); + await page.evaluate(() => gameTest.step(1)); + assert.equal((await state()).oxygen, 59); + current = await page.evaluate(() => gameTest.move(6, 3)); + assert(!current.map[6][3].known && current.duplicants[0].c === 2, 'move must not reveal unknown rock'); + current = await page.evaluate(() => gameTest.dig(3, 2)); + assert(current.map[3][2].known); + current = await page.evaluate(() => gameTest.dig(2, 2)); + assert(!current.map[2][2].known, 'upward reach is at most three cells'); + current = await page.evaluate(() => gameTest.dig(6, 4)); + assert(!current.map[6][4].known, 'horizontal digging reach is at most one cell'); + + const runAction = (name, row, col) => page.evaluate( + ([name, row, col]) => gameTest[name](row, col), + [name, row, col], + ); + await reset({oxygen: 60, duplicant: {r: 6, c: 2, water: 0}, openCells: [[5, 2], [6, 2]]}); + current = await page.evaluate(() => gameTest.step(1000)); + assert(current.oxygen > 0 && current.duplicants[0].sick, 'dehydration alone must cause illness'); + current = await runAction('dig', 5, 2); + assert.equal(current.duplicants[0].r, 6, 'digging known empty space must not move the duplicant'); + + // Use the returned dimensions instead of baking in the reference map size. + const {rows, cols} = (await state()).dimensions; + await reset({duplicant: {r: rows - 1, c: cols - 1, water: 60}, openCells: [[rows - 1, cols - 1]]}); + current = await runAction('move', rows - 1, cols); + assert(current.dimensions.cols > cols, 'an outside move should expand the requested edge'); + assert(!current.map[rows - 1][cols].known && current.duplicants[0].c === cols - 1, + 'an outside move may not excavate newly discovered rock'); + await reset({duplicant: {r: rows - 1, c: cols - 1, water: 60}, openCells: [[rows - 1, cols - 1]]}); + current = await runAction('dig', rows - 1, cols); + assert(current.dimensions.cols > cols && current.map[rows - 1][cols].known, + 'a reachable outside rock should expand and be excavated'); + assert.equal(await page.locator('.cell').count(), current.dimensions.rows * current.dimensions.cols); + const distant = await runAction('dig', -1, 0); + assert(distant.dimensions.rows > current.dimensions.rows, 'an outside dig should expand even when out of reach'); + const addedRows = distant.dimensions.rows - current.dimensions.rows; + assert(!distant.map[addedRows - 1][0].known, 'expansion may not bypass digging range'); + + for (const resource of ['open', 'oxygen', 'water']) { + await reset({oxygen: 40, duplicant: {r: 6, c: 2, water: 50}, openCells: [[6, 2]], resourceCells: [{r: 6, c: 3, type: resource}]}); + await page.locator('.cell[data-r="6"][data-c="2"]').click(); + await page.locator('.cell[data-r="6"][data-c="3"]').click(); + current = await state(); + assert(current.map[6][3].known && current.map[6][3].type === resource, 'real click must reveal injected resource'); + if (resource === 'open') assert(current.duplicants[0].water < 49, 'digging must consume water faster than a quiet one-second tick'); + if (resource === 'oxygen') assert(current.oxygen > 40, 'oxygen discovery must replenish environment'); + if (resource === 'water') assert(current.duplicants[0].water > 50, 'water discovery must alleviate dehydration'); + assert.equal(Number(await page.locator('#oxygen').innerText()), current.oxygen); + } + await capture('water-discovery'); + + await reset({}); + const count = (await state()).duplicants.length; + await page.evaluate(() => gameTest.answerPrint(true)); + assert.equal((await state()).duplicants.length, count, 'no pending request may not print a free duplicant'); + await page.evaluate(() => gameTest.step(9999)); + assert(!(await state()).printPending); + await page.evaluate(() => gameTest.step(1)); + assert((await state()).printPending && await page.locator('[data-testid="print-prompt"]').isVisible()); + await capture('ten-second-print-prompt'); + await page.locator('[data-answer-print="no"]').click(); + assert(!(await state()).printPending && (await state()).duplicants.length === count); + await page.evaluate(() => gameTest.step(10000)); + await page.locator('[data-answer-print="yes"]').click(); + assert.equal((await state()).duplicants.length, count + 1); + + for (const direction of ['up', 'down', 'left', 'right']) { + const before = (await state()).dimensions; + await page.locator(`[data-expand="${direction}"]`).click(); + current = await state(); + const key = ['up', 'down'].includes(direction) ? 'rows' : 'cols'; + assert(current.dimensions[key] > before[key], `${direction} navigation failed to expand`); + assert.equal(await page.locator('.cell').count(), current.dimensions.rows * current.dimensions.cols); + } + await capture('expanded-map'); + } finally {await browser.close();} +})().catch(error => {console.error(error); process.exit(1);}); diff --git a/task_042/tests/validate_semantics.js b/task_042/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..d10cc042756f6e9dba39b8f2484d59aaea267cc8 --- /dev/null +++ b/task_042/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_043/acceptance_checklist.json b/task_043/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..25281ab286939228c173bf2a8d780e832d670458 --- /dev/null +++ b/task_043/acceptance_checklist.json @@ -0,0 +1,16 @@ +{ + "task_id": 66, + "category": "frontend_development", + "language": "javascript", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies." + ], + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "risk_notes": [], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_043/environment/Dockerfile b/task_043/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_043/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_043/environment/code/.gitkeep b/task_043/environment/code/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/task_043/environment/docker-compose.yaml b/task_043/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_043/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_043/instruction.md b/task_043/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..981a2e918ddbadee33a45afa781307770635badc --- /dev/null +++ b/task_043/instruction.md @@ -0,0 +1,15 @@ +# Simulate two falling objects + +Build an offline science demonstration in `index.html`. Put experiment settings to the left, a canvas with two distinguishable falling objects to the right, and start/reset controls and landing results below. + +## Controls and state + +- Use `#typeA` and `#typeB` for `ball` or `feather`, `#vacuum` for the vacuum checkbox, and numeric range controls `#drag`, `#gravity` and `#weight`. Show their values in `#dragVal`, `#gravityVal` and `#weightVal`. Use `#start`, `#reset`, `#scene` and `#result` for buttons, canvas and result. +- Expose `window.gameTest` with `reset(config)`, `step(milliseconds)` and `state()`. Configuration is `{types:[typeA,typeB],vacuum,drag,gravity,mass}`; the weight control sets `mass`. State is `{objects:[{height,velocity,landed,landingTime}],config:{vacuum,drag,gravity,mass}}` with one object entry per selector. Height is pixels above ground, falling velocity is positive, and landing time is in seconds or null before landing. Reset and step return the resulting state. +- Set object types at reset; other controls update the active simulation during the fall. Injected and manually selected settings must agree with the displayed controls. + +## Acceptance Checklist + +- Start both objects from the same height. In a vacuum their trajectories and landing times match regardless of type or mass, and zero drag produces the same result. More gravity shortens a vacuum fall. In air, higher drag delays a fall, the feather is affected more than the ball, and higher mass reduces the delay. The ordinary comparison settings (mass 1–5, gravity 9.8, drag 0.01–0.08) allow both objects to land within 20 seconds. +- Use shared 50 ms simulation updates for manual and animated execution. Preserve partial elapsed time between manual calls; the start button uses real elapsed time rather than assuming a frame rate. +- The canvas and results reflect state changes in both modes. Give each landed object's time to two decimal places. Reset stops animation, clears accumulated time, velocities and landing results, and returns both objects to their starting height. diff --git a/task_043/quality_notes.md b/task_043/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..125a20b7b283c909235a49e7cd080f13240f2b2a --- /dev/null +++ b/task_043/quality_notes.md @@ -0,0 +1,2 @@ +# Quality Notes + diff --git a/task_043/solution/README.md b/task_043/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_043/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_043/solution/code/index.html b/task_043/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..940269facf72148e241d54ab664243ab835d91c2 --- /dev/null +++ b/task_043/solution/code/index.html @@ -0,0 +1,174 @@ + + + + + +Two-Object Drop Experiment + + + +

      Two-Object Drop Experiment

      +
      + + +
      + +
      + + +
      +
      Result: Ready…
      +
      +
      + + + + diff --git a/task_043/solution/solve.sh b/task_043/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_043/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_043/task.toml b/task_043/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_043/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_043/task_meta.json b/task_043/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..56e71219643356107cf7fb890ee40a3aaa6482ae --- /dev/null +++ b/task_043/task_meta.json @@ -0,0 +1,18 @@ +{ + "task_id": 66, + "task_category": "frontend_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 1, + "language": "javascript", + "tool_files_from_selected_trace": [ + "free-fall-experiment.html" + ], + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "source_row_id": 396, + "repair_revision": "2026-09-29", + "instruction_sha256": "35b2015c24bd2307f286ce7fa03f7b56d2dfac14d1265f487f788549717b7945" +} diff --git a/task_043/tests/_shared/contract_checker.js b/task_043/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_043/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_043/tests/_shared/static_enhancer.sh b/task_043/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_043/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_043/tests/enhancement_cases.json b/task_043/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..56c4701addbe4298f1976c83a06ac1ea935e9ddc --- /dev/null +++ b/task_043/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "用户可以通过下拉菜单或滑块选择:两个物体类型(小球或羽毛)、环境是否真空、风阻系数、重力加速度、物体重量这几个参数", + "validator": "validate_enhanced_cases.js", + "behavior": "按控件关联标签和选项检查两个独立物体类型控件,以及真空、风阻、重力、重量参数控件,不依赖 id。" + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "右侧是实验显示区,展示两个物体从屏幕顶部同时下落的动画,动画会根据用户设置实时模拟物理效果(空气阻力、重力差异等),底部有开始/重置按钮和实验结果展示区(如到达地面的时间)", + "validator": "validate_enhanced_cases.js", + "behavior": "点击语义匹配的开始控件并确定性推进动画帧,验证画面变化、两个落地时间结果,以及重置后恢复初始画面。" + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "动画会根据用户设置实时模拟物理效果(空气阻力、重力差异等)", + "validator": "validate_enhanced_cases.js", + "behavior": "选择不同物体类型并开启真空,完整推进实验,验证去除空气阻力后两个物体报告相同落地时间。" + } +] diff --git a/task_043/tests/test.sh b/task_043/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5b93094e3a03087c4e33dbad0e01077a559a54e5 --- /dev/null +++ b/task_043/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_043/tests/validate_aaav_dynamic.js b/task_043/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..bd200a35f9c1806112dc601fe7ee5f820b10441f --- /dev/null +++ b/task_043/tests/validate_aaav_dynamic.js @@ -0,0 +1,148 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 66; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_043/tests/validate_browser_smoke.js b/task_043/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..658969881ac5de913eb45fddd8f4e1aae56c7ff5 --- /dev/null +++ b/task_043/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_043/tests/validate_enhanced_cases.js b/task_043/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..51d79cf4e4e358c4b5f6c1af33c0f8a3a7c0dbe5 --- /dev/null +++ b/task_043/tests/validate_enhanced_cases.js @@ -0,0 +1,127 @@ +const fs = require('fs'); +const path = require('path'); +const {pathToFileURL} = require('url'); +const {chromium} = require('playwright'); +const assert = require('assert'); + +async function checkElapsedTime(browser, entry, config) { + const timed = await browser.newPage(); + try { + await timed.clock.install({time: new Date('2026-01-01T00:00:00Z')}); + await timed.clock.pauseAt(new Date('2026-01-01T00:00:01Z')); + await timed.addInitScript(() => { + const pending = new Map(); + let nextId = 0; + window.requestAnimationFrame = callback => { + pending.set(++nextId, callback); + return nextId; + }; + window.cancelAnimationFrame = id => pending.delete(id); + window.flushVerifierFrame = () => { + const frame = [...pending]; + const timestamp = performance.now(); + for (const [id, callback] of frame) { + if (pending.delete(id)) callback(timestamp); + } + }; + }); + await timed.goto(entry); + const elapsed = 704; + const manualWindow = await timed.evaluate(({config, elapsed}) => { + return [elapsed - 50, elapsed, elapsed + 50].map(duration => { + gameTest.reset(config); + return gameTest.step(duration).objects; + }); + }, {config, elapsed}); + + // Run the same elapsed time at two frame rates. Native timer callbacks + // also run against the virtual clock, so requestAnimationFrame is optional. + for (const tick of [16, 64]) { + await timed.evaluate(config => { + gameTest.reset(config); + document.querySelector('#start').click(); + window.flushVerifierFrame(); + }, config); + for (let ms = 0; ms < elapsed; ms += tick) { + await timed.clock.runFor(tick); + await timed.evaluate(() => window.flushVerifierFrame()); + } + const animated = await timed.evaluate(() => gameTest.state().objects); + const nearManualStep = manualWindow.some(expected => expected.every((object, index) => { + const actual = animated[index]; + return actual.landed === object.landed && + Math.abs(actual.height - object.height) < 0.01 && + Math.abs(actual.velocity - object.velocity) < 0.01; + })); + assert(nearManualStep, `animation with ${tick} ms frames did not advance by real elapsed time`); + } + } finally { + await timed.close(); + } +} + +(async () => { + const browser = await chromium.launch({headless: true}); + try { + const page = await browser.newPage({viewport: {width: 1100, height: 800}}); + const entry = pathToFileURL(path.resolve('index.html')).href; + await page.goto(entry); + const reset = config => page.evaluate(config => gameTest.reset(config), config); + const step = ms => page.evaluate(ms => gameTest.step(ms), ms); + const state = () => page.evaluate(() => gameTest.state()); + const pixels = () => page.locator('#scene').evaluate(canvas => canvas.toDataURL()); + const capture = async name => { + fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true}); + await page.screenshot({path: '/logs/verifier/visual-audit/' + name + '.png', fullPage: true}); + }; + const base = {types: ['ball', 'feather'], vacuum: true, gravity: 9.8, drag: .08, mass: 1}; + const run = async config => {await reset({...base, ...config}); return step(20000);}; + const vacuum = await run({}); + assert(vacuum.objects.every(object => object.landed)); + assert(Math.abs(vacuum.objects[0].landingTime - vacuum.objects[1].landingTime) < .02); + assert.deepStrictEqual((await run({mass: 5})).objects, vacuum.objects, 'mass may not alter vacuum trajectory'); + assert.deepStrictEqual((await run({vacuum: false, drag: 0})).objects, vacuum.objects, 'zero drag must match vacuum'); + assert((await run({gravity: 20})).objects[0].landingTime < vacuum.objects[0].landingTime); + const low = await run({vacuum: false, drag: .01}); + const high = await run({vacuum: false, drag: .08}); + const heavy = await run({vacuum: false, drag: .08, mass: 5}); + assert(high.objects[1].landingTime > low.objects[1].landingTime); + assert(heavy.objects[1].landingTime < high.objects[1].landingTime); + assert(high.objects[1].landingTime > high.objects[0].landingTime, 'feather must experience stronger drag'); + const reversed = await run({types: ['feather', 'ball'], vacuum: false, drag: .08}); + assert(reversed.objects[0].landingTime > reversed.objects[1].landingTime, + 'switching the selectors must switch which object experiences more drag'); + await run({vacuum: false, drag: .08, mass: 5}); + const result = await page.locator('#result').innerText(); + assert.equal(Number(await page.locator('#weightVal').innerText()), 5, 'visible mass value must match injected control'); + for (const object of heavy.objects) assert(result.includes(object.landingTime.toFixed(2)), 'visible landing time must match state'); + await capture('air-drag-landed'); + const initial = await reset(base); + const before = await pixels(); + await step(20); + assert.deepStrictEqual((await state()).objects, initial.objects); + const partitioned = await step(30); + await reset(base); + assert.deepStrictEqual((await step(50)).objects, partitioned.objects, 'fractional virtual time must accumulate'); + await step(500); + const falling = await state(); + assert(falling.objects.every((object, index) => object.height < initial.objects[index].height && object.velocity > 0 && !object.landed)); + assert.notEqual(await pixels(), before, 'state changes must actually render'); + await capture('virtual-falling'); + await page.locator('#reset').click(); + assert.deepStrictEqual((await state()).objects, initial.objects); + assert(!/\d+\.\d+s/.test(await page.locator('#result').innerText()), 'reset must clear landing results'); + await page.waitForTimeout(180); + assert.deepStrictEqual((await state()).objects, initial.objects, 'reset must stop real animation'); + await page.locator('#start').click(); + await page.waitForFunction(() => gameTest.state().objects.some(object => object.velocity > 0), null, {timeout: 5000}); + for (const [id, value] of [['gravity', '15'], ['weight', '2'], ['drag', '0.04']]) { + await page.locator('#' + id).evaluate((input, value) => {input.value = value; input.dispatchEvent(new Event('input', {bubbles: true}));}, value); + } + await page.locator('#vacuum').uncheck(); + assert.deepStrictEqual((await state()).config, {gravity: 15, mass: 2, drag: .04, vacuum: false}); + await capture('real-animation-controls'); + await page.locator('#reset').click(); + await checkElapsedTime(browser, entry, base); + } finally {await browser.close();} +})().catch(error => {console.error(error); process.exit(1);}); diff --git a/task_043/tests/validate_semantics.js b/task_043/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..d10cc042756f6e9dba39b8f2484d59aaea267cc8 --- /dev/null +++ b/task_043/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_044/acceptance_checklist.json b/task_044/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..e0a2fc4380eaf1d49116ae084480478c8c17fe03 --- /dev/null +++ b/task_044/acceptance_checklist.json @@ -0,0 +1,16 @@ +{ + "task_id": 68, + "category": "frontend_development", + "language": "svg", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies." + ], + "input_assets": [], + "expected_outputs": [ + "*.svg" + ], + "risk_notes": [], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_044/environment/Dockerfile b/task_044/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_044/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_044/environment/code/.gitkeep b/task_044/environment/code/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/task_044/environment/docker-compose.yaml b/task_044/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_044/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_044/instruction.md b/task_044/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4253e9931f136248b50d7b03e88f857638db8215 --- /dev/null +++ b/task_044/instruction.md @@ -0,0 +1,15 @@ +# Draw an interactive SVG aquarium + +Deliver a standalone `.svg` in the project root that opens directly offline. Show a transparent aquarium with a subtle glass reflection, several green plants and brown stones near the bottom, and two golden carp of visibly different sizes. Give each fish a body, a tail with a moving fin, and a discernible eye that contrasts with its body. + +## Interface + +- Render the aquarium at least 400×240. The feedable SVG coordinates include `(470,60)`. +- Mark the two fish containers with `data-fish="0"` and `"1"`, the corresponding fins with `data-tail="0"` and `"1"`, and the visible food container with `data-food-layer`. +- Expose `window.aquariumTest.feed(x,y)`, `.step(milliseconds)` and `.snapshot()`. Feeding is the same action as clicking at the given SVG position. Snapshot returns an independent `{time,fish:[{x,y,tail}],food:[{x,y}]}`; each fish container's rendered origin matches its snapshot position. Test-mode stepping may pause the real clock; it must advance the same visible scene. + +## Acceptance Checklist + +- On an ordinary load, both fish swim automatically in both axes and their tails sway independently. Update each fish group's SVG `transform` attribute to reflect its translation. Plants, bottom decoration, both fish and their features are visibly rendered. +- A click or feed action adds at least three visible pellets near the chosen point. During the first 200 ms the pellets start sinking and fish pursue them by reducing their distance, not by moving in a constant direction. +- Fish eat and remove all pellets within ten seconds of feeding and resume free swimming. Repeated feeding works, and editing a snapshot cannot alter the scene. diff --git a/task_044/quality_notes.md b/task_044/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..125a20b7b283c909235a49e7cd080f13240f2b2a --- /dev/null +++ b/task_044/quality_notes.md @@ -0,0 +1,2 @@ +# Quality Notes + diff --git a/task_044/solution/README.md b/task_044/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_044/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_044/solution/code/aquarium.svg b/task_044/solution/code/aquarium.svg new file mode 100644 index 0000000000000000000000000000000000000000..d35f120ee0ed575caf6ad84780dc4550a35e349b --- /dev/null +++ b/task_044/solution/code/aquarium.svg @@ -0,0 +1,23 @@ + + + + + + Interactive koi aquarium + + + + + + + + diff --git a/task_044/solution/solve.sh b/task_044/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_044/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_044/task.toml b/task_044/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_044/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_044/task_meta.json b/task_044/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..d1da37c6af3d4ae0c3fe1ad969818bb86e8ccc7d --- /dev/null +++ b/task_044/task_meta.json @@ -0,0 +1,18 @@ +{ + "task_id": 68, + "task_category": "frontend_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 1, + "language": "svg", + "tool_files_from_selected_trace": [ + "fish_tank.svg" + ], + "input_assets": [], + "expected_outputs": [ + "*.svg" + ], + "source_row_id": 408, + "repair_revision": "2026-09-29", + "instruction_sha256": "06c767a543ef251f0d7ad4b2ae7e7f61f3ca78467195167f9bfb95c38ab1cfde" +} diff --git a/task_044/tests/_shared/contract_checker.js b/task_044/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_044/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_044/tests/_shared/static_enhancer.sh b/task_044/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_044/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_044/tests/enhancement_cases.json b/task_044/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..6d4bbf8c95b343e4d7dc869c938e581c1d0b045f --- /dev/null +++ b/task_044/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","scored":true,"instruction_evidence":"首先要有一个足够大的透明鱼缸;鱼缸底部是几颗绿色水草和几颗棕色石头","validator":"validate_enhanced_cases.js","behavior":"验证大尺寸鱼缸以及底部多株植物和装饰几何,不绑定特定棕色名称或 SVG 标签"}, + {"case_id":"ENHANCED_CASE_2","scored":true,"instruction_evidence":"鱼缸内部有两条金色鲤鱼,一大一小;鲤鱼要有眼睛、身体、尾巴、尾鳍等元素","validator":"validate_enhanced_cases.js","behavior":"验证两条不同尺寸鱼体及至少两组眼睛、尾部几何,不以 fill 字符串作为鱼 selector"}, + {"case_id":"ENHANCED_CASE_3","scored":true,"instruction_evidence":"鱼缸内部有两条金色鲤鱼,一大一小,会上下左右游动","validator":"validate_enhanced_cases.js","behavior":"验证至少两条持续的鱼体位置运动动画,允许等价 SVG 动画结构"} +] diff --git a/task_044/tests/test.sh b/task_044/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5b93094e3a03087c4e33dbad0e01077a559a54e5 --- /dev/null +++ b/task_044/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_044/tests/validate_aaav_dynamic.js b/task_044/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..d8b1c04cd4791db7cc0696168aac73615aa7154f --- /dev/null +++ b/task_044/tests/validate_aaav_dynamic.js @@ -0,0 +1,148 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 68; +const KIND = "svg"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_044/tests/validate_browser_smoke.js b/task_044/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_044/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_044/tests/validate_enhanced_cases.js b/task_044/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..8e14452d9a1691c3615c35ef9fff096f1ce1dbd2 --- /dev/null +++ b/task_044/tests/validate_enhanced_cases.js @@ -0,0 +1,162 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +function assert(ok, message) { if (!ok) throw new Error(message); } +function entry() { + const found = fs.readdirSync(process.cwd()).find(f => f.toLowerCase().endsWith('.svg')); + assert(found, 'missing SVG output'); + return path.join(process.cwd(), found); +} +async function runCase(id, fn) { + try { await fn(); console.log(`${id} PASS`); } + catch (e) { console.error(`${id} FAIL: ${e.message}`); process.exitCode = 1; } +} + +(async () => { + const browser = await chromium.launch({ headless: true, args: ['--no-sandbox', '--disable-dev-shm-usage'] }); + const page = await browser.newPage({ viewport: { width: 1000, height: 720 } }); + await page.goto(pathToFileURL(entry()).href, { waitUntil: 'domcontentloaded' }); + + // ENHANCED_CASE_1: a large aquarium scene includes multiple plants and bottom decoration. + // Paint names are deliberately not selectors: equivalent SVG palettes remain valid. + await runCase('ENHANCED_CASE_1', async () => { + const s = await page.evaluate(() => { + const svg = document.querySelector('svg'); + const box = svg?.getBoundingClientRect(); + const nodes = [...document.querySelectorAll('svg rect,svg path,svg polygon,svg circle,svg ellipse')]; + const plants = nodes.filter(el => { + const r = el.getBoundingClientRect(); + const paint = `${el.getAttribute('fill') || ''} ${getComputedStyle(el).fill}`.toLowerCase(); + return r.y + r.height / 2 > (box?.y || 0) + (box?.height || 0) * 0.6 && + (/green/.test(paint) || [...paint.matchAll(/rgba?\((\d+),\s*(\d+),\s*(\d+)/g)].some(m => +m[2] > +m[1] && +m[2] > +m[3])); + }); + const bottomDecor = nodes.filter(el => { + const r = el.getBoundingClientRect(); + return r.width >= 10 && r.height >= 10 && r.y + r.height / 2 > (box?.y || 0) + (box?.height || 0) * 0.7; + }); + return { w: box?.width || 0, h: box?.height || 0, plants: plants.length, bottomDecor: bottomDecor.length }; + }); + assert(s.w >= 400 && s.h >= 240, `aquarium is not large enough (${s.w}x${s.h})`); + assert(s.plants >= 2, 'expected multiple visible plant elements near the tank bottom'); + assert(s.bottomDecor >= 3, 'expected visible bottom scenery in addition to the tank'); + }); + + // Check the actual marked fish and fins, regardless of painted shape type. + // Body/eye recognizability is visual evidence, not an SVG tag requirement. + await runCase('ENHANCED_CASE_2', async () => { + const fish = await page.evaluate(() => { + const measure = element => { + if (!element) return 0; + for (let node = element; node; node = node.parentElement) { + const style = getComputedStyle(node); + if (style.display === 'none' || style.visibility === 'hidden' || +style.opacity === 0) return 0; + } + const {width, height} = element.getBoundingClientRect(); + return width * height; + }; + return [0, 1].map(i => ({ + body: measure(document.querySelector(`[data-fish="${i}"]`)), + fin: measure(document.querySelector(`[data-tail="${i}"]`)), + })); + }); + assert(fish.every(f => f.body > 0 && f.fin > 0), 'both marked fish and fins must have visible geometry'); + assert(Math.abs(fish[0].body - fish[1].body) > 20, 'the two rendered fish should have different sizes'); + }); + + // ENHANCED_CASE_3: both fish have ongoing movement, independent of exact SVG selector structure. + await runCase('ENHANCED_CASE_3', async () => { + const result = await page.evaluate(() => { const a=window.aquariumTest.snapshot(); window.aquariumTest.step(120); const b=window.aquariumTest.snapshot(); return {a,b}; }); + assert(result.a.fish[0].tail !== result.b.fish[0].tail && result.a.fish[1].tail !== result.b.fish[1].tail, 'both tails must animate'); + assert((result.b.fish[0].tail-result.a.fish[0].tail) !== (result.b.fish[1].tail-result.a.fish[1].tail), 'tail fins need independent animation state'); + }); + + await runCase('ENHANCED_CASE_4', async () => { + const result = await page.evaluate(() => { window.aquariumTest.feed(470,60); const a=window.aquariumTest.snapshot(); window.aquariumTest.step(200); const b=window.aquariumTest.snapshot(); return {a,b}; }); + assert(result.a.food.length >= 3, 'feeding must create several pellets at the selected location'); + assert(result.b.food[0].y > result.a.food[0].y, 'pellets must sink over time'); + assert(result.b.fish.some((f,i) => Math.hypot(f.x-470,f.y-60) < Math.hypot(result.a.fish[i].x-470,result.a.fish[i].y-60)), 'fish must move closer to the food'); + }); + + await runCase('ENHANCED_CASE_5', async () => { + const consumption = await page.evaluate(() => { + const svg = document.documentElement; + const screen = svg.getScreenCTM(); + const pad = Math.max(Math.hypot(screen.a, screen.b), Math.hypot(screen.c, screen.d)) * 12; + const fish = [...document.querySelectorAll('[data-fish]')]; + const frame = () => ({ + food: window.aquariumTest.snapshot().food.map(({x, y}) => new DOMPoint(x, y).matrixTransform(screen)), + fish: fish.map(node => node.getBoundingClientRect()), + }); + const reaches = (point, box) => point.x >= box.left - pad && point.x <= box.right + pad && + point.y >= box.top - pad && point.y <= box.bottom + pad; + let before = frame(); + for (let elapsed = 200; elapsed < 10000 && before.food.length; elapsed += 40) { + window.aquariumTest.step(40); + const after = frame(); + const consumed = before.food.length - after.food.length; + const reachable = before.food.filter(pellet => + [...before.fish, ...after.fish].some(box => reaches(pellet, box))); + if (consumed > reachable.length) { + return {remaining: after.food.length, removedAtDistance: true}; + } + before = after; + } + return {remaining: before.food.length, removedAtDistance: false}; + }); + assert(!consumption.removedAtDistance, 'pellets must not disappear while all fish are away from them'); + assert(consumption.remaining === 0, 'food must be eaten within ten seconds of feeding'); + }); + + await runCase('ENHANCED_CASE_6', async () => { + const before = await page.evaluate(() => window.aquariumTest.snapshot().food.length); + const tank = await page.locator('svg').boundingBox(); + const target = await page.locator('svg').evaluate(svg => { + const b = svg.getBoundingClientRect(), p = svg.createSVGPoint(); + p.x = b.x + b.width * .75; p.y = b.y + b.height * .3; + const q = p.matrixTransform(svg.getScreenCTM().inverse()); + return { x: q.x, y: q.y }; + }); + await page.mouse.click(tank.x + tank.width * .75, tank.y + tank.height * .3); + const after = await page.evaluate(() => window.aquariumTest.snapshot()); + assert(after.food.length >= before + 3, 'clicking the tank must feed through the same state machine'); + assert(after.food.some(p => Math.abs(p.x - target.x) < 20 && Math.abs(p.y - target.y) < 20), 'pellets should appear near the clicked point'); + }); + + + await runCase('VISIBLE_STATE_AND_COPY', async () => { + const visible = await page.evaluate(() => { + const elements = [...document.querySelectorAll('[data-fish], [data-tail], [data-food-layer] > *')]; + const good = element => { + for (let node=element; node; node=node.parentElement) { + const style=getComputedStyle(node); + if(style.display==='none'||style.visibility==='hidden'||+style.opacity===0) return false; + } + return true; + }; + const snapshot=aquariumTest.snapshot(); + const origins=[...document.querySelectorAll('[data-fish]')].map(element => { + const matrix=element.getCTM(); + return {x:matrix.e,y:matrix.f}; + }); + snapshot.fish[0].x=-99999;snapshot.food.length=0; + return {allVisible:elements.every(good),origins,state:aquariumTest.snapshot()}; + }); + assert(visible.allVisible && visible.origins.length === 2, 'visible fish/tail/food geometry required'); + visible.origins.forEach((point,index) => assert(Math.abs(point.x-visible.state.fish[index].x)<1 && Math.abs(point.y-visible.state.fish[index].y)<1,'rendered fish position must match snapshot')); + assert(visible.state.food.length>=3 && visible.state.fish[0].x!==-99999,'snapshot must be an isolated copy'); + fs.mkdirSync('/logs/verifier/visual-audit',{recursive:true}); + await page.screenshot({path:'/logs/verifier/visual-audit/fed-aquarium.png'}); + await page.evaluate(() => {for(let i=0;i<120;i++)aquariumTest.step(100);}); + const movement=await page.evaluate(() => {const a=aquariumTest.snapshot();aquariumTest.step(300);return {a,b:aquariumTest.snapshot()};}); + assert(movement.b.food.length===0,'second meal must be eaten'); + for(let i=0;i<2;i++) assert(Math.abs(movement.a.fish[i].x-movement.b.fish[i].x)>0.1 && Math.abs(movement.a.fish[i].y-movement.b.fish[i].y)>0.1,'both fish must swim horizontally and vertically'); + await page.screenshot({path:'/logs/verifier/visual-audit/free-swimming.png'}); + await page.reload(); + const first=await page.locator('[data-fish="0"]').getAttribute('transform'); + await page.waitForFunction(first => document.querySelector('[data-fish="0"]').getAttribute('transform')!==first,first,{timeout:5000}); + }); + await browser.close(); + if (process.exitCode) process.exit(process.exitCode); +})().catch(e => { console.error(e.stack || e); process.exit(1); }); diff --git a/task_044/tests/validate_semantics.js b/task_044/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_044/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_045/acceptance_checklist.json b/task_045/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..9332e09bcf9fba14499cb6f8b96657ef4f13c35a --- /dev/null +++ b/task_045/acceptance_checklist.json @@ -0,0 +1,16 @@ +{ + "task_id": 69, + "category": "frontend_development", + "language": "svg", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies." + ], + "input_assets": [], + "expected_outputs": [ + "*.svg" + ], + "risk_notes": [], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_045/environment/Dockerfile b/task_045/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..776aa5544a69bee5568d052e6fc806540ba59d47 --- /dev/null +++ b/task_045/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# Benchmark fix: the mcr/playwright base ships browsers but NOT the `playwright` +# npm package, so the verifier's require('playwright') threw MODULE_NOT_FOUND. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_045/environment/code/.gitkeep b/task_045/environment/code/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/task_045/environment/docker-compose.yaml b/task_045/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_045/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_045/instruction.md b/task_045/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e30ab2c52dcabfb4d19c103fedfe68415f291e4a --- /dev/null +++ b/task_045/instruction.md @@ -0,0 +1,29 @@ +# Draw an emergency-department swimlane diagram + +Deliver a standalone `.svg` at the project root, readable offline. Illustrate the clinical workflow as six left-to-right stages within five top-to-bottom horizontal role lanes. + +## Lanes and ownership + +| Lane ID | Role and responsibilities | Node IDs | +| --- | --- | --- | +| `triage` | Triage nurse: reception, registration, vital signs and preliminary assessment | `triage`, `waiting` | +| `doctor` | Emergency physician: history, examination, orders and diagnosis | `doctor`, `diagnosis` | +| `lab` | Examination/laboratory: blood, urine, imaging and ECG | `lab` | +| `specialist` | Specialist/surgical team: emergency treatment, surgery, monitoring and ward handover | `resuscitation`, `surgery`, `ward` | +| `admin` | Administration: discharge, admission, ward allocation and transfer | `death`, `discharge`, `admission`, `transfer` | + +## Stages and paths + +1. **Arrival and triage:** critical (red) → emergency treatment; severe (yellow) → physician's initial exam; mild (green) → waiting, then initial exam. +2. **Initial examination:** take history, examine and order tests. Emergency care → resuscitation; further testing → lab; minor case/prescription → discharge. +3. **Examination and diagnosis:** show blood/urine tests, imaging (X-ray, CT or MRI) and ECG. Normal results → physician diagnosis (`lab->diagnosis`); abnormal results → surgery (`lab->surgery`). +4. **Emergency/critical care:** show cardiopulmonary resuscitation, airway management and emergency medication. Stabilized → diagnosis; deterioration → repeat resuscitation (`resuscitation->resuscitation`); unsuccessful → death. +5. **Diagnosis and disposition:** outpatient care → discharge; hospitalization → admission; surgery needed → surgical preparation; transfer needed → transfer coordination. +6. **Disposition processing:** discharge and transfer complete their workflows; admission leads to ward nursing handover. Mark death, discharge and transfer as terminal outcomes. + +## Acceptance Checklist + +- Mark lanes with `data-lane` and nodes with `data-node`, `data-lane-owner` and `data-stage` (1–6). All twelve listed nodes are visibly inside their specified role lane; each stage is overall farther right than the previous stage. +- Show all seventeen paths above as visible arrowed SVG lines, paths or polylines with `data-from` and `data-to` set to endpoint node IDs. Additional documented connections may not replace required ones or contradict terminal outcomes. +- A connector starts and ends within five screen pixels of its respective node boundaries, has a visible stroke and uses `marker-end` referencing an SVG arrowhead marker. Route it around the interiors of unrelated nodes. +- State each branch condition beside its arrow or in a corresponding visible legend; mark the label `data-edge-label="from->to"` using the endpoint IDs. Use the conditions above in English or Chinese. Color the critical, severe and mild triage connector strokes red, yellow and green respectively (for example `#d32f2f`, `#f9d40d`, `#388e3c`). diff --git a/task_045/quality_notes.md b/task_045/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..125a20b7b283c909235a49e7cd080f13240f2b2a --- /dev/null +++ b/task_045/quality_notes.md @@ -0,0 +1,2 @@ +# Quality Notes + diff --git a/task_045/solution/README.md b/task_045/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_045/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_045/solution/code/hospital_flow.svg b/task_045/solution/code/hospital_flow.svg new file mode 100644 index 0000000000000000000000000000000000000000..3124384f71c0bbb08770cfe94e1a162b46aaec25 --- /dev/null +++ b/task_045/solution/code/hospital_flow.svg @@ -0,0 +1,63 @@ + + + + Emergency Medical Workflow + + Triage NurseER PhysicianDiagnosticsSpecialist TeamAdministration + Arrival / Triage + Low-Risk Queue + Initial ER ExamHistory / Orders + Lab / Imaging / ECGDiagnostic Tests + Critical CareAirway / Medication + Death / End + Diagnosis / DecisionReview Test Results + Surgery / SpecialtyTreatment / Monitor + Discharge (End) + Admit / Assign Bed + Transfer (End) + Ward Handoff + + + + + + + + +E1 +E2 +E3 +E4 +E5 +E6 +E7 +E8 +E9 +E10 +E11 +E12 +E13 +E14 +E15 +E16 +E17 +Branch Index (E numbers map to connectors; workflow visualization only, not clinical advice) +E1 · triage → resuscitation: critical / red +E2 · triage → doctor: severe / yellow +E3 · triage → waiting: mild / green +E4 · waiting → doctor: initial exam after waiting +E5 · doctor → resuscitation: emergency care needed +E6 · doctor → lab: further tests needed +E7 · doctor → discharge: outpatient treatment / prescription +E8 · lab → diagnosis: normal results +E9 · lab → surgery: abnormal results +E10 · resuscitation → diagnosis: condition stable +E11 · resuscitation → resuscitation: deterioration / repeat care +E12 · resuscitation → death: resuscitation unsuccessful +E13 · diagnosis → discharge: outpatient care / discharge +E14 · diagnosis → admission: inpatient care needed +E15 · diagnosis → surgery: surgery needed +E16 · diagnosis → transfer: transfer needed +E17 · admission → ward: nursing handoff +Triage: reception, registration, vital signs, and acuity level. Initial exam: history, physical exam, and test orders.Diagnostics: blood, urine, X-ray / CT / MRI, and ECG. Administration: discharge, bed assignment, and transfer. + diff --git a/task_045/solution/solve.sh b/task_045/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_045/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_045/task.toml b/task_045/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_045/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_045/task_meta.json b/task_045/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..f046223d9a2f29ecfe5ff04d5f24f17fbe85b8f6 --- /dev/null +++ b/task_045/task_meta.json @@ -0,0 +1,18 @@ +{ + "task_id": 69, + "task_category": "frontend_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 1, + "language": "svg", + "tool_files_from_selected_trace": [ + "emergency_process_swimlane.svg" + ], + "input_assets": [], + "expected_outputs": [ + "*.svg" + ], + "source_row_id": 414, + "repair_revision": "2026-09-29", + "instruction_sha256": "6b10d408e4f0c10797a20e183ce59f3148eb15ef54310fedd26c77ba6c4764b2" +} diff --git a/task_045/tests/_shared/contract_checker.js b/task_045/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_045/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_045/tests/_shared/static_enhancer.sh b/task_045/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_045/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_045/tests/enhancement_cases.json b/task_045/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..0cf1287a77b7349303bd7d79798dac1f9994fd1a --- /dev/null +++ b/task_045/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","scored":true,"instruction_evidence":"横向第一行是分诊护士...横向第五行是行政/出入院管理","validator":"validate_enhanced_cases.js","behavior":"验证五类角色/部门标签均可见,不绑定标签必须作为独立 text 节点或固定 y 坐标"}, + {"case_id":"ENHANCED_CASE_2","scored":true,"instruction_evidence":"医疗急诊处理流程包含分诊、医生、检查、专科/手术、行政及出院/住院/转院结果","validator":"validate_enhanced_cases.js","behavior":"验证主要处理部门及出院、转院、死亡、病房等流程目的地和足量可见节点"}, + {"case_id":"ENHANCED_CASE_3","scored":true,"instruction_evidence":"危重(红色)、严重(黄色)、轻症(绿色)以及各分支方向","validator":"validate_enhanced_cases.js","behavior":"验证三类视觉色彩编码及至少八条带方向标记的流程连接"} +] diff --git a/task_045/tests/test.sh b/task_045/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5b93094e3a03087c4e33dbad0e01077a559a54e5 --- /dev/null +++ b/task_045/tests/test.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +PASS=1 +run validate_semantics.js || PASS=0 +run validate_browser_smoke.js || PASS=0 +run validate_enhanced_cases.js || PASS=0 +echo "$PASS" > "$REWARD_FILE" diff --git a/task_045/tests/validate_aaav_dynamic.js b/task_045/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..83f91cb3902648baf652a21082fe1d95fa394ec8 --- /dev/null +++ b/task_045/tests/validate_aaav_dynamic.js @@ -0,0 +1,148 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 69; +const KIND = "svg"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_045/tests/validate_browser_smoke.js b/task_045/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_045/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_045/tests/validate_enhanced_cases.js b/task_045/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..e1c6e0780ed4256c673393c18ec659b5d34f5f0b --- /dev/null +++ b/task_045/tests/validate_enhanced_cases.js @@ -0,0 +1,162 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +function assert(ok, msg) { if (!ok) throw new Error(msg); } +function findSVG() { const f = fs.readdirSync(process.cwd()).find(x => x.toLowerCase().endsWith('.svg')); assert(f, 'missing SVG'); return path.join(process.cwd(), f); } +async function test(id, fn) { try { await fn(); console.log(`${id} PASS`); } catch (e) { console.error(`${id} FAIL: ${e.message}`); process.exitCode = 1; } } +(async () => { + const browser = await chromium.launch({ headless: true, args: ['--no-sandbox', '--disable-dev-shm-usage'] }); + const page = await browser.newPage({ viewport: { width: 1200, height: 1000 } }); + await page.goto(pathToFileURL(findSVG()).href, { waitUntil: 'domcontentloaded' }); + const normalizedText = async () => (await page.locator('svg').textContent()).toLowerCase().replace(/\s+/g, ' '); + + // ENHANCED_CASE_1: all five explicitly named roles/departments are represented. + // Labels may sit inside nodes or lane headers; their exact y coordinate is not an API contract. + await test('ENHANCED_CASE_1', async () => { + const text = await normalizedText(); + const groups = [/(分诊|triage).*(护士|nurse)/, /(急诊.*医生|emergency doctor|doctor)/, /(检查|检验|lab|imaging|exam)/, /(专科|手术|specialist|surgery)/, /(行政|出入院|admin|admission|discharge)/]; + assert(groups.every(re => re.test(text)), 'one or more of the five required roles/departments is missing'); + }); + + // ENHANCED_CASE_2: the diagram exposes the major processing and terminal destinations. + await test('ENHANCED_CASE_2', async () => { + const text = await normalizedText(); + const destinations = [/(分诊|triage)/, /(医生|doctor)/, /(检查|检验|lab|test|exam)/, /(专科|手术|specialist|surgery)/, /(行政|admin|admission)/, /(出院|discharge)/, /(转院|transfer)/, /(死亡|death)/, /(病房|ward)/]; + assert(destinations.every(re => re.test(text)), 'one or more required workflow destinations/outcomes is missing'); + assert(await page.locator('svg rect,svg path').count() >= 8, 'workflow lacks enough rendered process nodes'); + }); + + // ENHANCED_CASE_3: triage colors and directional branch connectors are rendered as SVG behavior, not prose only. + await test('ENHANCED_CASE_3', async () => { + const s = await page.evaluate(() => { + const els = [...document.querySelectorAll('svg *')]; + const paints = els.map(e => `${e.getAttribute('fill') || ''} ${e.getAttribute('stroke') || ''} ${getComputedStyle(e).fill} ${getComputedStyle(e).stroke}`.toLowerCase()); + const has = re => paints.some(x => re.test(x)); + const rgb = paints.flatMap(x => [...x.matchAll(/rgba?\((\d+),\s*(\d+),\s*(\d+)/g)].map(m => m.slice(1,4).map(Number))); + return { red: has(/red|#f00/) || rgb.some(([r,g,b]) => r >= g && r >= b && r-b >= 12), yellow: has(/yellow|#ff0/) || rgb.some(([r,g,b]) => r > 200 && g > 200 && b < Math.min(r,g)-12), green: has(/green|#0f0/) || rgb.some(([r,g,b]) => g >= r && g >= b && g-r >= 12), connectors: document.querySelectorAll('path,line,polyline').length, arrows: document.querySelectorAll('marker,[marker-end],[marker-start]').length }; + }); + assert(s.red && s.yellow && s.green, 'red/yellow/green triage coding is incomplete'); + assert(s.connectors >= 8 && s.arrows >= 1, 'insufficient directional connectors for the workflow branches'); + }); + await test('ENHANCED_CASE_4', async () => { + const graph = await page.evaluate(() => ({ + lanes: [...document.querySelectorAll('[data-lane]')].map(e => ({name:e.dataset.lane,y:e.getBoundingClientRect().y})), + nodes: [...document.querySelectorAll('[data-node]')].map(e => { const r=e.getBoundingClientRect(); return {id:e.dataset.node,owner:e.dataset.laneOwner,stage:Number(e.dataset.stage),x:r.x+r.width/2,rect:{left:r.left,right:r.right,top:r.top,bottom:r.bottom}} }), + edges: [...document.querySelectorAll('[data-from][data-to]')].map(e => { + const a=document.querySelector(`[data-node="${e.dataset.from}"]`), b=document.querySelector(`[data-node="${e.dataset.to}"]`); + const ar=a&&a.getBoundingClientRect(), br=b&&b.getBoundingClientRect(); + let p1,p2; + const tag=e.tagName.toLowerCase(), point=(x,y)=>{const q=e.ownerSVGElement.createSVGPoint();q.x=x;q.y=y;return q.matrixTransform(e.getScreenCTM())}; + if(tag==='line') { p1=point(e.x1.baseVal.value,e.y1.baseVal.value);p2=point(e.x2.baseVal.value,e.y2.baseVal.value); } + else if(tag==='path') { const n=e.getTotalLength(); const a=e.getPointAtLength(0),b=e.getPointAtLength(n);p1=point(a.x,a.y);p2=point(b.x,b.y); } + else if(tag==='polyline') { const q=e.points;p1=q.length&&point(q[0].x,q[0].y);p2=q.length&&point(q[q.length-1].x,q[q.length-1].y); } + const near=(p,r)=>p&&r&&p.x>=r.left-5&&p.x<=r.right+5&&p.y>=r.top-5&&p.y<=r.bottom+5&&Math.min(Math.abs(p.x-r.left),Math.abs(p.x-r.right),Math.abs(p.y-r.top),Math.abs(p.y-r.bottom))<=5; + return {key:`${e.dataset.from}->${e.dataset.to}`, attached:near(p1,ar)&&near(p2,br)}; + }) + })); + assert(graph.lanes.length === 5 && new Set(graph.lanes.map(x=>x.y)).size === 5, 'five distinct horizontal lanes are required'); + const requiredNodes=['triage','waiting','doctor','lab','resuscitation','diagnosis','surgery','death','discharge','admission','transfer','ward']; + for (const id of requiredNodes) assert(graph.nodes.some(n=>n.id===id), `missing structural node ${id}`); + const laneRects=await page.evaluate(() => Object.fromEntries([...document.querySelectorAll('[data-lane]')].map(e=>{const r=e.getBoundingClientRect();return [e.dataset.lane,{left:r.left,right:r.right,top:r.top,bottom:r.bottom}]}))); + for(const n of graph.nodes){const r=laneRects[n.owner];assert(r&&n.rect.left>=r.left-1&&n.rect.right<=r.right+1&&n.rect.top>=r.top-1&&n.rect.bottom<=r.bottom+1,`node ${n.id} is outside declared lane ${n.owner}`);assert(n.stage>=1&&n.stage<=6,`node ${n.id} has invalid stage`)} + const stageX={};for(const n of graph.nodes)(stageX[n.stage]??=[]).push(n.x);let previous=-Infinity;for(const stage of [1,2,3,4,5,6]){const avg=stageX[stage].reduce((a,b)=>a+b,0)/stageX[stage].length;assert(avg>previous,`stage ${stage} is not visibly to the right`);previous=avg} + const expected=['triage->resuscitation','triage->doctor','triage->waiting','waiting->doctor','doctor->resuscitation','doctor->lab','doctor->discharge','lab->diagnosis','lab->surgery','resuscitation->diagnosis','resuscitation->resuscitation','resuscitation->death','diagnosis->discharge','diagnosis->admission','diagnosis->surgery','diagnosis->transfer','admission->ward']; + assert(graph.edges.length >= expected.length, `expected at least ${expected.length} semantic branches`); + const terminalNodes = new Set(['death', 'discharge', 'transfer']); + assert(graph.edges.every(edge => !terminalNodes.has(edge.key.split('->')[0])), + 'terminal outcomes cannot have an outgoing workflow branch'); + for (const edge of expected) { + const found=graph.edges.find(x=>x.key===edge); assert(found, `missing directed branch ${edge}`); assert(found.attached, `connector endpoints do not attach to declared nodes: ${edge}`); + } + }); + + await test('VISIBLE_DIRECTED_GRAPH',async()=>{ + const expectedOwners={triage:'triage',waiting:'triage',doctor:'doctor',diagnosis:'doctor',lab:'lab',resuscitation:'specialist',surgery:'specialist',ward:'specialist',death:'admin',discharge:'admin',admission:'admin',transfer:'admin'}; + const checks=await page.evaluate(expectedOwners=>{ + const visible=element=>{ + for(let node=element;node;node=node.parentElement){const style=getComputedStyle(node);if(style.display==='none'||style.visibility==='hidden'||+style.opacity===0)return false} + return true; + }; + const swatch = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas'); + swatch.width = swatch.height = 1; + const context = swatch.getContext('2d', {willReadFrequently: true}); + const sample = color => { + context.clearRect(0, 0, 1, 1); + context.fillStyle = 'transparent'; + context.fillStyle = color; + context.fillRect(0, 0, 1, 1); + return [...context.getImageData(0, 0, 1, 1).data]; + }; + const paintedMarker = marker => { + if (!(marker instanceof SVGMarkerElement) || !visible(marker) || + marker.markerWidth.baseVal.value <= 0 || marker.markerHeight.baseVal.value <= 0) return false; + return [...marker.querySelectorAll('path,polygon,polyline,line,rect,circle,ellipse,use,text')].some(shape => { + if (!visible(shape)) return false; + const box = shape.getBBox(); + const style = getComputedStyle(shape); + const hasPaint = (paint, opacity) => +opacity > 0 && + (paint.startsWith('url(') || paint.startsWith('context-') || sample(paint)[3] > 0); + return (box.width > 0 && box.height > 0 && hasPaint(style.fill, style.fillOpacity)) || + ((box.width > 0 || box.height > 0) && parseFloat(style.strokeWidth) > 0 && + hasPaint(style.stroke, style.strokeOpacity)); + }); + }; + const nodes=[...document.querySelectorAll('[data-node]')],edges=[...document.querySelectorAll('[data-from][data-to]')]; + const lanes=[...document.querySelectorAll('[data-lane]')].sort((a,b)=>a.getBoundingClientRect().y-b.getBoundingClientRect().y).map(e=>e.dataset.lane); + return {lanes,owners:nodes.every(node=>node.dataset.laneOwner===expectedOwners[node.dataset.node]&&visible(node)), + edges:edges.map(edge=>{ + const style=getComputedStyle(edge),match=style.markerEnd.match(/#([^")]+)/); + const marker=match&&document.getElementById(match[1]); + const paintId=style.stroke.match(/#([^\")]+)/); + const paint=paintId&&document.getElementById(paintId[1]); + const findStops = (element, seen = new Set()) => { + if (!element || seen.has(element)) return []; + seen.add(element); + const stops = [...element.querySelectorAll('stop')]; + const ref = element.getAttribute('href') || element.getAttribute('xlink:href'); + return stops.length || !ref?.startsWith('#') ? stops : findStops(document.getElementById(ref.slice(1)), seen); + }; + const stops = findStops(paint); + const strokeColors = (stops.length ? stops + .filter(stop => +getComputedStyle(stop).stopOpacity > 0) + .map(stop => getComputedStyle(stop).stopColor) : paint?.localName === 'pattern' ? [] : [style.stroke]).map(sample); + const label=[...document.querySelectorAll('[data-edge-label]')].find(item=>item.dataset.edgeLabel===edge.dataset.from+'->'+edge.dataset.to); + const obstacles=nodes.filter(node=>![edge.dataset.from,edge.dataset.to].includes(node.dataset.node)).map(node=>node.getBoundingClientRect()); + let blocked=false; + const length=edge.getTotalLength(); + for(let distance=0;distance<=length;distance+=2){ + const point=edge.getPointAtLength(distance).matrixTransform(edge.getScreenCTM()); + if(obstacles.some(box=>point.x>box.left+3&&point.xbox.top+3&&point.y 0 : strokeColors.some(color => color[3] > 0)))&&+style.strokeOpacity>0&&parseFloat(style.strokeWidth)>0, + arrow:paintedMarker(marker),label:!!label&&visible(label)&&label.textContent.trim().length>0, + text:label?.textContent||'',key:edge.dataset.from+'->'+edge.dataset.to,strokeColors,blocked}; + })}; + },expectedOwners); + assert(JSON.stringify(checks.lanes)===JSON.stringify(['triage','doctor','lab','specialist','admin']),'lane order must match roles'); + assert(checks.owners,'nodes must have correct semantic ownership and visibility'); + assert(checks.edges.every(edge=>edge.visible&&edge.arrow&&edge.label),'every edge needs visible stroke, actual arrow and labeled condition'); + assert(checks.edges.every(edge=>!edge.blocked),'connectors must not cross unrelated process nodes'); + const meanings={ + 'triage->resuscitation':/危重|critical|life[- ]threatening/i,'triage->doctor':/严重|severe|urgent|serious/i,'triage->waiting':/轻症|minor|mild|low[- ]acuity/i, + 'waiting->doctor':/候诊|初诊|wait|consult/i,'doctor->resuscitation':/急救|resusc|emerg/i,'doctor->lab':/检查|检验|test|exam/i, + 'doctor->discharge':/轻症|处方|minor|prescription/i,'lab->diagnosis':/正常|\bnormal\b|within\s+(?:the\s+)?(?:reference\s+)?range|unremarkable/i,'lab->surgery':/异常|abnormal|out(?:side|\s+of)\s+(?:the\s+)?(?:reference\s+)?range/i, + 'resuscitation->diagnosis':/稳定|stable|stabil/i,'resuscitation->resuscitation':/恶化|再次|worsen|deterior|repeat/i, + 'resuscitation->death':/无效|死亡|unsuccess|death|ineffective/i,'diagnosis->discharge':/门诊|出院|outpatient|discharge/i, + 'diagnosis->admission':/住院|admi/i,'diagnosis->surgery':/手术|surg/i,'diagnosis->transfer':/转院|transfer/i,'admission->ward':/病房|护理|ward|handover/i, + }; + for(const edge of checks.edges) if(meanings[edge.key]) assert(meanings[edge.key].test(edge.text),`incorrect branch condition ${edge.key}`); + for(const [key,index]of [['triage->resuscitation',0],['triage->doctor',1],['triage->waiting',2]]){ + const colors=checks.edges.find(edge=>edge.key===key).strokeColors; + assert(colors.length>0,'triage edge requires discernible severity paint'); + for(const [r,g,b,alpha] of colors){ + assert(alpha > 0, 'triage paint must resolve to a visible color'); + assert(index===0?r>g+20&&r>b+20:index===1?r>150&&g>100&&br+20&&g>b+20,`incorrect severity color ${key}`); + } + } + fs.mkdirSync('/logs/verifier/visual-audit',{recursive:true}); + await page.screenshot({path:'/logs/verifier/visual-audit/emergency-swimlane.png'}); + }); + await browser.close(); if (process.exitCode) process.exit(process.exitCode); +})().catch(e => { console.error(e.stack || e); process.exit(1); }); diff --git a/task_045/tests/validate_semantics.js b/task_045/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_045/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_046/acceptance_checklist.json b/task_046/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..997b19cda5b01055c83682d416e76aa3dd12d428 --- /dev/null +++ b/task_046/acceptance_checklist.json @@ -0,0 +1,17 @@ +{ + "task_id": 72, + "category": "application_development", + "language": "go", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Go sources compile and `go test ./...` passes when tests are present." + ], + "input_assets": [], + "expected_outputs": [], + "risk_notes": [ + "A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_046/environment/Dockerfile b/task_046/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f7c63c1afe472bd572b57d5a48ffd3cf28ff5c8a --- /dev/null +++ b/task_046/environment/Dockerfile @@ -0,0 +1,4 @@ +# syntax=docker/dockerfile:1.7-labs +FROM golang:1.23-bookworm@sha256:167053a2bb901972bf2c1611f8f52c44d5fe7e762e5cab213708d82c421614db +WORKDIR /app +COPY ./code /app diff --git a/task_046/environment/code/go.mod b/task_046/environment/code/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..97e0fa477e48bd17e7bf80252a35529525adfecc --- /dev/null +++ b/task_046/environment/code/go.mod @@ -0,0 +1,3 @@ +module promotion_system + +go 1.23 diff --git a/task_046/environment/code/promotion.go b/task_046/environment/code/promotion.go new file mode 100644 index 0000000000000000000000000000000000000000..80a428823ceeed2c83d62f555ade144d75f7e659 --- /dev/null +++ b/task_046/environment/code/promotion.go @@ -0,0 +1,33 @@ +package promotion + +type Order struct { + OriginalAmount float64 + UserLevel string + Category string +} + +type Strategy interface { + Discount(order Order) float64 +} + +type PromotionCalculator struct { + strategies []Strategy +} + +func NewPromotionCalculator(strategies ...Strategy) *PromotionCalculator { + return &PromotionCalculator{strategies: strategies} +} + +func (p *PromotionCalculator) FinalAmount(order Order) float64 { + // TODO: implement by summing discounts from original amount. + return order.OriginalAmount +} + +type FullReductionStrategy struct{} +func (FullReductionStrategy) Discount(order Order) float64 { return 0 } + +type UserLevelDiscountStrategy struct{} +func (UserLevelDiscountStrategy) Discount(order Order) float64 { return 0 } + +type CategoryDiscountStrategy struct{} +func (CategoryDiscountStrategy) Discount(order Order) float64 { return 0 } diff --git a/task_046/environment/code/promotion_test.go b/task_046/environment/code/promotion_test.go new file mode 100644 index 0000000000000000000000000000000000000000..941bb6a6caccae019c2fa8eeb609410ad8f87fdb --- /dev/null +++ b/task_046/environment/code/promotion_test.go @@ -0,0 +1,71 @@ +package promotion + +import "testing" + +func closeEnough(t *testing.T, got, want float64) { + t.Helper() + if got < want-0.001 || got > want+0.001 { + t.Fatalf("got %.3f want %.3f", got, want) + } +} + +func TestFullReductionDiscounts(t *testing.T) { + cases := []struct { + amount float64 + want float64 + }{ + {150, 0}, + {200, 20}, + {499, 20}, + {500, 50}, + {999, 50}, + {1000, 100}, + } + s := FullReductionStrategy{} + for _, tc := range cases { + closeEnough(t, s.Discount(Order{OriginalAmount: tc.amount}), tc.want) + } +} + +func TestUserLevelDiscountsFromOriginalPrice(t *testing.T) { + s := UserLevelDiscountStrategy{} + closeEnough(t, s.Discount(Order{OriginalAmount: 1000, UserLevel: "bronze"}), 0) + closeEnough(t, s.Discount(Order{OriginalAmount: 1000, UserLevel: "silver"}), 50) + closeEnough(t, s.Discount(Order{OriginalAmount: 1000, UserLevel: "gold"}), 100) + closeEnough(t, s.Discount(Order{OriginalAmount: 1000, UserLevel: "platinum"}), 150) +} + +func TestCategoryDiscountsFromOriginalPrice(t *testing.T) { + s := CategoryDiscountStrategy{} + closeEnough(t, s.Discount(Order{OriginalAmount: 1000, Category: "electronics"}), 80) + closeEnough(t, s.Discount(Order{OriginalAmount: 1000, Category: "clothing"}), 120) + closeEnough(t, s.Discount(Order{OriginalAmount: 1000, Category: "books"}), 200) +} + +func TestPromotionCalculatorStacksDiscounts(t *testing.T) { + calc := NewPromotionCalculator(FullReductionStrategy{}, UserLevelDiscountStrategy{}, CategoryDiscountStrategy{}) + order := Order{OriginalAmount: 1000, UserLevel: "gold", Category: "books"} + // Full reduction 100 + gold discount 100 + books discount 200, all from original price. + closeEnough(t, calc.FinalAmount(order), 600) +} + +func TestUnknownUserLevelGivesZeroDiscount(t *testing.T) { + // Map lookup for an unknown level returns the zero rate, so discount is 0. + s := UserLevelDiscountStrategy{} + closeEnough(t, s.Discount(Order{OriginalAmount: 1000, UserLevel: "diamond"}), 0) + closeEnough(t, s.Discount(Order{OriginalAmount: 1000, UserLevel: ""}), 0) +} + +func TestUnknownCategoryGivesZeroDiscount(t *testing.T) { + // Map lookup for an unknown category returns the zero rate, so discount is 0. + s := CategoryDiscountStrategy{} + closeEnough(t, s.Discount(Order{OriginalAmount: 1000, Category: "groceries"}), 0) + closeEnough(t, s.Discount(Order{OriginalAmount: 1000, Category: ""}), 0) +} + +func TestPromotionCalculatorStacksNonRoundPrice(t *testing.T) { + calc := NewPromotionCalculator(FullReductionStrategy{}, UserLevelDiscountStrategy{}, CategoryDiscountStrategy{}) + order := Order{OriginalAmount: 500, UserLevel: "silver", Category: "electronics"} + // Full reduction 50 (>=500) + silver 500*0.05=25 + electronics 500*0.08=40 = 115 off. + closeEnough(t, calc.FinalAmount(order), 385) +} diff --git a/task_046/environment/docker-compose.yaml b/task_046/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_046/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_046/instruction.md b/task_046/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d3d92c5ff0b770120f0c723c8f9487aba8411320 --- /dev/null +++ b/task_046/instruction.md @@ -0,0 +1,23 @@ +# Compose e-commerce promotion strategies + +Implement the promotion calculator in the supplied Go project, using its `promotion` package. Work offline and keep `go test ./...` passing. Local helper packages are allowed. + +## Interface + +Keep the supplied `Order{OriginalAmount float64, UserLevel string, Category string}`, `Strategy` interface with `Discount(Order) float64`, and `NewPromotionCalculator(strategies ...Strategy) *PromotionCalculator` with `FinalAmount(Order) float64`. Provide the concrete strategies below. + +## Discount rules + +| Strategy | Discount from the original amount | +| --- | --- | +| `FullReductionStrategy` | ¥100 at ¥1,000 or more, otherwise ¥50 at ¥500 or more, otherwise ¥20 at ¥200 or more, otherwise zero. Only the highest qualifying tier applies. | +| `UserLevelDiscountStrategy` | `bronze`: 0%; `silver`: 5%; `gold`: 10%; `platinum`: 15%. | +| `CategoryDiscountStrategy` | `electronics`: 8%; `clothing`: 12%; `books`: 20%. | + +Unknown or empty levels and categories get zero discount from the corresponding strategy. Amounts are finite, nonnegative floating-point numbers, including fractional amounts; the results must be finite. + +## Acceptance Checklist + +- Each configured strategy computes its discount for the original order, not for a running balance. Full reductions respect inclusive thresholds, and percentage rules also work at non-round amounts. +- A calculator accepts additional implementations through `Strategy` without needing changes to built-in strategies. Apply each supplied strategy once; sum the discounts independently of their order. +- Return the original amount with no strategies and zero when discounts exceed the amount. Zero and unknown/empty classifications do not create spurious discounts. diff --git a/task_046/quality_notes.md b/task_046/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..177ca6b7cbc2fc2f6d24f4876159792c81d4b86b --- /dev/null +++ b/task_046/quality_notes.md @@ -0,0 +1,3 @@ +# Quality Notes + +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. \ No newline at end of file diff --git a/task_046/solution/README.md b/task_046/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_046/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_046/solution/code/go.mod b/task_046/solution/code/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..97e0fa477e48bd17e7bf80252a35529525adfecc --- /dev/null +++ b/task_046/solution/code/go.mod @@ -0,0 +1,3 @@ +module promotion_system + +go 1.23 diff --git a/task_046/solution/code/promotion.go b/task_046/solution/code/promotion.go new file mode 100644 index 0000000000000000000000000000000000000000..29be7241db6d2992210038902244ea03e94db65d --- /dev/null +++ b/task_046/solution/code/promotion.go @@ -0,0 +1,60 @@ +package promotion + +type Order struct { + OriginalAmount float64 + UserLevel string + Category string +} + +type Strategy interface { + Discount(Order) float64 +} + +type FullReductionStrategy struct{} + +func (FullReductionStrategy) Discount(order Order) float64 { + switch { + case order.OriginalAmount >= 1000: + return 100 + case order.OriginalAmount >= 500: + return 50 + case order.OriginalAmount >= 200: + return 20 + default: + return 0 + } +} + +type UserLevelDiscountStrategy struct{} + +func (UserLevelDiscountStrategy) Discount(order Order) float64 { + rates := map[string]float64{"silver": 0.05, "gold": 0.10, "platinum": 0.15} + return order.OriginalAmount * rates[order.UserLevel] +} + +type CategoryDiscountStrategy struct{} + +func (CategoryDiscountStrategy) Discount(order Order) float64 { + rates := map[string]float64{"electronics": 0.08, "clothing": 0.12, "books": 0.20} + return order.OriginalAmount * rates[order.Category] +} + +type PromotionCalculator struct { + strategies []Strategy +} + +func NewPromotionCalculator(strategies ...Strategy) PromotionCalculator { + return PromotionCalculator{strategies: strategies} +} + +func (c PromotionCalculator) FinalAmount(order Order) float64 { + discount := 0.0 + for _, strategy := range c.strategies { + discount += strategy.Discount(order) + } + final := order.OriginalAmount - discount + if final < 0 { + return 0 + } + return final +} diff --git a/task_046/solution/solve.sh b/task_046/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_046/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_046/task.toml b/task_046/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_046/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_046/task_meta.json b/task_046/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..5f42302c98ec2ee9ab062726b0253930dce652e7 --- /dev/null +++ b/task_046/task_meta.json @@ -0,0 +1,26 @@ +{ + "task_id": 72, + "task_category": "application_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 1, + "language": "go", + "tool_files_from_selected_trace": [ + "calculator.go", + "category_discount.go", + "full_reduction.go", + "go.mod", + "order.go", + "product.go", + "promotion_system", + "strategy.go", + "strategy_test.go", + "user.go", + "user_level_discount.go" + ], + "input_assets": [], + "expected_outputs": [], + "source_row_id": 432, + "repair_revision": "2026-09-29", + "instruction_sha256": "60df350592fb36388706a0815d41af75b1bd69a32617ba98ba1bdb4fb5cb9770" +} diff --git a/task_046/tests/_shared/contract_checker.js b/task_046/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_046/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_046/tests/_shared/static_enhancer.sh b/task_046/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_046/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_046/tests/enhancement_cases.json b/task_046/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..2d4a755027f32771cc567638dff841a02f275ecf --- /dev/null +++ b/task_046/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","instruction_evidence":"订单满1000元减100元,满500元减50元,满200元减20元","validator":"validate_enhanced_cases.sh","behavior":"验证三个阈值本身、阈值前一合法金额及阈值以上金额"}, + {"case_id":"ENHANCED_CASE_2","instruction_evidence":"bronze: 无折扣;silver: 95折;gold: 9折;platinum: 85折;electronics: 92折;clothing: 88折;books: 8折","validator":"validate_enhanced_cases.sh","behavior":"用非整数原价验证全部等级和分类折扣表"}, + {"case_id":"ENHANCED_CASE_3","instruction_evidence":"每个策略都是在原价基础上计算折扣,折扣累加后作为总的折扣","validator":"validate_enhanced_cases.sh","behavior":"用三个策略和非整百金额验证基于原价的叠加结果"} +] diff --git a/task_046/tests/test.sh b/task_046/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..52d37cb6cc5272563de6d183905aa8e28ac288e6 --- /dev/null +++ b/task_046/tests/test.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set +e +T="$(cd "$(dirname "$0")" && pwd)"; R=/logs/verifier; mkdir -p "$R"; p=1 +command -v go >/dev/null 2>&1 || p=0 +[ "$p" = 1 ] && go test ./... || p=0 +[ "$p" = 1 ] && timeout 30s bash "$T/validate_enhanced_cases.sh" || p=0 +echo "$p" > "$R/reward.txt"; exit 0 diff --git a/task_046/tests/validate_aaav_dynamic.js b/task_046/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..084af21bd111137182b07013c5650da80e91ace3 --- /dev/null +++ b/task_046/tests/validate_aaav_dynamic.js @@ -0,0 +1,69 @@ +const fs = require('fs'); +const path = require('path'); +const child_process = require('child_process'); +const TASK_ID = 72; +const LANGUAGE = "go"; +const EXPECTED = []; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { if (!condition) throw new Error(message); } +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} +function globToRe(glob) { + return new RegExp('^' + glob.split('*').map(x => x.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') + '$'); +} +function existsPattern(files, pat) { + const re = globToRe(String(pat).replace(/\\/g, '/')); + return files.some(f => re.test(f.replace(/\\/g, '/')) || f.replace(/\\/g, '/').endsWith(String(pat).replace(/\\/g, '/'))); +} + +const files = walk(process.cwd()); +assert(files.length > 0, 'candidate workspace should contain files'); +const rel = files.map(f => path.relative(process.cwd(), f)); +const source = files.filter(f => /\.(js|jsx|ts|tsx|css|html|py|go|md|svg)$/i.test(f)); +assert(source.length > 0, 'candidate should contain source or report files'); +const totalBytes = source.reduce((n, f) => n + fs.statSync(f).size, 0); +assert(totalBytes >= 80, 'candidate source/report content is too small'); + +if (LANGUAGE === 'go') { + const goFiles = files.filter(f => f.endsWith('.go')); + assert(goFiles.length > 0, 'go task should contain .go files'); + try { + child_process.execFileSync('go', ['test', './...'], { cwd: process.cwd(), stdio: 'pipe', timeout: 120000 }); + } catch (err) { + // The benchmark's own verifier owns task-specific Go behavior. Here we + // keep go test as an opportunistic runtime probe so local module/path + // differences do not create false negatives. + const msg = Buffer.concat([err.stdout || Buffer.alloc(0), err.stderr || Buffer.alloc(0)]).toString().slice(0, 500); + console.warn('go test ./... probe failed but is non-fatal: ' + msg); + } +} else if (LANGUAGE === 'python') { + const pyFiles = files.filter(f => f.endsWith('.py')); + assert(pyFiles.length > 0 || rel.some(f => /\.(html|csv|json|txt|md|png)$/i.test(f)), 'python/data task should contain scripts or produced artifacts'); + for (const f of pyFiles.slice(0, 20)) { + child_process.execFileSync('python', ['-m', 'py_compile', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); + } +} else { + for (const f of files.filter(f => f.endsWith('.js')).slice(0, 20)) { + child_process.execFileSync('node', ['--check', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); + } +} + +for (const pat of EXPECTED) { + assert(existsPattern(rel, pat), 'missing expected artifact pattern after verifier: ' + pat); +} + +console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); diff --git a/task_046/tests/validate_enhanced_cases.sh b/task_046/tests/validate_enhanced_cases.sh new file mode 100644 index 0000000000000000000000000000000000000000..dea51549ca2ee4787c98c44f890a4496c37398bb --- /dev/null +++ b/task_046/tests/validate_enhanced_cases.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +set -euo pipefail +tmp_test="zz_enhanced_cases_test.go" +trap 'rm -f "$tmp_test"' EXIT +cat > "$tmp_test" <<'GOEOF' +package promotion +import ("testing"; "math"; "math/rand") +func enhancedClose(t *testing.T, got,want float64){t.Helper();if math.IsNaN(got)||math.IsInf(got,0)||gotwant+0.0001{t.Fatalf("got %.4f want %.4f",got,want)}} +// ENHANCED_CASE_1: full-reduction boundaries distinguish each exact threshold from the value immediately below it. +func TestEnhancedCase1FullReductionBoundaries(t *testing.T){s:=FullReductionStrategy{}; for _,c:=range []struct{a,w float64}{{199.99,0},{200,20},{499.99,20},{500,50},{999.99,50},{1000,100},{1400,100}}{enhancedClose(t,s.Discount(Order{OriginalAmount:c.a}),c.w)}} +// ENHANCED_CASE_2: every user level and category computes its discount from a non-round original price. +func TestEnhancedCase2PercentageTables(t *testing.T){a:=137.5; u:=UserLevelDiscountStrategy{}; c:=CategoryDiscountStrategy{}; for _,x:=range []struct{v string;w float64}{{"bronze",0},{"silver",6.875},{"gold",13.75},{"platinum",20.625}}{enhancedClose(t,u.Discount(Order{OriginalAmount:a,UserLevel:x.v}),x.w)}; for _,x:=range []struct{v string;w float64}{{"electronics",11},{"clothing",16.5},{"books",27.5}}{enhancedClose(t,c.Discount(Order{OriginalAmount:a,Category:x.v}),x.w)}} +// ENHANCED_CASE_3: combined strategies independently sum discounts based on original price. +func TestEnhancedCase3OriginalPriceStacking(t *testing.T){calc:=NewPromotionCalculator(FullReductionStrategy{},UserLevelDiscountStrategy{},CategoryDiscountStrategy{}); enhancedClose(t,calc.FinalAmount(Order{OriginalAmount:750,UserLevel:"platinum",Category:"clothing"}),497.5)} +type enhancedCustomStrategy struct{} +func (enhancedCustomStrategy) Discount(order Order) float64 { return order.OriginalAmount * .07 } +// ENHANCED_CASE_4: the calculator composes an external strategy and never returns a negative payable amount. +func TestEnhancedCase4ExtensibilityAndFloor(t *testing.T){ + order:=Order{OriginalAmount:315,UserLevel:"gold",Category:"books"} + enhancedClose(t,NewPromotionCalculator().FinalAmount(order),315) + enhancedClose(t,NewPromotionCalculator(enhancedCustomStrategy{}).FinalAmount(order),292.95) + enhancedClose(t,NewPromotionCalculator(FullReductionStrategy{},UserLevelDiscountStrategy{},CategoryDiscountStrategy{},enhancedCustomStrategy{}).FinalAmount(order),178.45) + many:=make([]Strategy,15);for i:=range many{many[i]=enhancedCustomStrategy{}} + enhancedClose(t,NewPromotionCalculator(many...).FinalAmount(order),0) +} +func TestEnhancedCase5UnseenAmounts(t *testing.T){ + rng:=rand.New(rand.NewSource(90472)) + levels:=[]string{"bronze","silver","gold","platinum","unknown",""} + categories:=[]string{"electronics","clothing","books","unknown",""} + for i:=0;i<180;i++{ + amount:=rng.Float64()*4000 + level:=levels[i%len(levels)];category:=categories[i%len(categories)] + order:=Order{OriginalAmount:amount,UserLevel:level,Category:category} + reduction:=0.0;if amount>=1000{reduction=100}else if amount>=500{reduction=50}else if amount>=200{reduction=20} + user:=amount*map[string]float64{"silver":.05,"gold":.1,"platinum":.15}[level] + item:=amount*map[string]float64{"electronics":.08,"clothing":.12,"books":.2}[category] + enhancedClose(t,FullReductionStrategy{}.Discount(order),reduction) + enhancedClose(t,UserLevelDiscountStrategy{}.Discount(order),user) + enhancedClose(t,CategoryDiscountStrategy{}.Discount(order),item) + enhancedClose(t,NewPromotionCalculator(CategoryDiscountStrategy{},FullReductionStrategy{},UserLevelDiscountStrategy{}).FinalAmount(order),amount-reduction-user-item) + } + enhancedClose(t,NewPromotionCalculator(FullReductionStrategy{},UserLevelDiscountStrategy{},CategoryDiscountStrategy{}).FinalAmount(Order{}),0) +} +GOEOF +GOTOOLCHAIN=local GOPROXY=off go test -v -count=1 -timeout=20s -run '^TestEnhancedCase' . diff --git a/task_047/acceptance_checklist.json b/task_047/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..eff47caeb7b319627f98b046291a5a9e83600451 --- /dev/null +++ b/task_047/acceptance_checklist.json @@ -0,0 +1,17 @@ +{ + "task_id": 74, + "category": "application_development", + "language": "go", + "acceptance_items": [ + "Implements the user-visible behavior described in the prompt, not only the file structure from a sample trajectory.", + "Keeps the solution runnable without internet access unless the task explicitly provides dependencies.", + "Go sources compile and `go test ./...` passes when tests are present." + ], + "input_assets": [], + "expected_outputs": [], + "risk_notes": [ + "A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context." + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_047/environment/Dockerfile b/task_047/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f7c63c1afe472bd572b57d5a48ffd3cf28ff5c8a --- /dev/null +++ b/task_047/environment/Dockerfile @@ -0,0 +1,4 @@ +# syntax=docker/dockerfile:1.7-labs +FROM golang:1.23-bookworm@sha256:167053a2bb901972bf2c1611f8f52c44d5fe7e762e5cab213708d82c421614db +WORKDIR /app +COPY ./code /app diff --git a/task_047/environment/code/go.mod b/task_047/environment/code/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..9c82c3833960455e77a3789ea1930061cd40adce --- /dev/null +++ b/task_047/environment/code/go.mod @@ -0,0 +1,3 @@ +module log_analyzer + +go 1.23 diff --git a/task_047/environment/code/log_analyzer.go b/task_047/environment/code/log_analyzer.go new file mode 100644 index 0000000000000000000000000000000000000000..24aca2879dc3fe0bbc5e48d5adae743f1f096bcb --- /dev/null +++ b/task_047/environment/code/log_analyzer.go @@ -0,0 +1,34 @@ +package loganalyzer + +import "net/http" + +type Log struct { + ID string `json:"id"` + Message string `json:"message"` + Level string `json:"level"` + Timestamp string `json:"timestamp"` + Tag string `json:"tag"` +} + +type Repository interface { + Save(log Log) error + Get(id string) (Log, bool) +} + +func GenerateTag(log Log) string { return "" } + +func NewMemoryRepository() Repository { return nil } + +func NewFileRepository(path string) Repository { return nil } + +func NewRepositoryFromConfig(kind string, path string) Repository { return nil } + +type Service struct { + Repo Repository +} + +func NewService(repo Repository) *Service { return &Service{Repo: repo} } + +func (s *Service) Process(log Log) (Log, error) { return log, nil } + +func NewHandler(repo Repository) http.Handler { return http.NewServeMux() } diff --git a/task_047/environment/code/log_analyzer_test.go b/task_047/environment/code/log_analyzer_test.go new file mode 100644 index 0000000000000000000000000000000000000000..14e88cfc2db713975d38ffab646770811cc00bb5 --- /dev/null +++ b/task_047/environment/code/log_analyzer_test.go @@ -0,0 +1,100 @@ +package loganalyzer + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" +) + +func TestTagGenerationAndMemoryRepository(t *testing.T) { + repo := NewMemoryRepository() + if repo == nil { + t.Fatalf("NewMemoryRepository returned nil") + } + svc := NewService(repo) + saved, err := svc.Process(Log{ID: "123", Message: "user login success", Level: "INFO", Timestamp: "2025-09-05T12:00:00Z"}) + if err != nil { + t.Fatalf("Process returned error: %v", err) + } + if saved.Tag == "" { + t.Fatalf("expected generated tag") + } + got, ok := repo.Get("123") + if !ok || got.ID != "123" || got.Tag == "" { + t.Fatalf("saved log not found or missing tag: %+v", got) + } +} + +func TestFileRepositoryPersistsJSON(t *testing.T) { + dir := t.TempDir() + repo := NewFileRepository(filepath.Join(dir, "logs.jsonl")) + if repo == nil { + t.Fatalf("NewFileRepository returned nil") + } + if err := repo.Save(Log{ID: "file-1", Message: "disk write", Level: "WARN", Timestamp: "2025-09-05T12:00:00Z", Tag: "warn"}); err != nil { + t.Fatalf("Save returned error: %v", err) + } + got, ok := repo.Get("file-1") + if !ok || got.Level != "WARN" { + t.Fatalf("file repository Get failed: %+v", got) + } + entries, err := os.ReadDir(dir) + if err != nil || len(entries) == 0 { + t.Fatalf("file repository did not create storage file") + } +} + +func TestConfigSelectsRepository(t *testing.T) { + if NewRepositoryFromConfig("memory", "") == nil { + t.Fatalf("memory config should return repository") + } + if NewRepositoryFromConfig("file", filepath.Join(t.TempDir(), "logs.jsonl")) == nil { + t.Fatalf("file config should return repository") + } +} + +func TestHTTPHandlers(t *testing.T) { + handler := NewHandler(NewMemoryRepository()) + body := []byte(`{"id":"abc","message":"user login success","level":"INFO","timestamp":"2025-09-05T12:00:00Z"}`) + post := httptest.NewRequest(http.MethodPost, "/logs", bytes.NewReader(body)) + post.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, post) + if rec.Code < 200 || rec.Code >= 300 { + t.Fatalf("POST /logs status=%d body=%s", rec.Code, rec.Body.String()) + } + var posted Log + if err := json.Unmarshal(rec.Body.Bytes(), &posted); err != nil { + t.Fatalf("POST response should be JSON Log: %v", err) + } + if posted.Tag == "" { + t.Fatalf("POST response should include generated tag") + } + + get := httptest.NewRequest(http.MethodGet, "/log/abc", nil) + rec = httptest.NewRecorder() + handler.ServeHTTP(rec, get) + if rec.Code != http.StatusOK { + t.Fatalf("GET /log/abc status=%d body=%s", rec.Code, rec.Body.String()) + } + var retrieved Log + if err := json.Unmarshal(rec.Body.Bytes(), &retrieved); err != nil { + t.Fatalf("GET response should be JSON Log: %v", err) + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(rec.Body.Bytes(), &fields); err != nil { + t.Fatalf("GET response should be a JSON object: %v", err) + } + for _, name := range []string{"id", "message", "level", "timestamp", "tag"} { + if _, ok := fields[name]; !ok { + t.Fatalf("GET response is missing JSON field %q", name) + } + } + if retrieved.ID != "abc" || retrieved.Tag != posted.Tag { + t.Fatalf("GET response missing the stored ID or tag: %+v", retrieved) + } +} diff --git a/task_047/environment/docker-compose.yaml b/task_047/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_047/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_047/instruction.md b/task_047/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..00630f6b144be5e8779f2717023c272fa2fa16d7 --- /dev/null +++ b/task_047/instruction.md @@ -0,0 +1,17 @@ +# Implement a pluggable HTTP log service + +Extend the supplied Go `loganalyzer` project. Separate log and tagging rules, application processing, persistence and the `net/http` interface so processing can be tested with an injected repository. Build and test offline with `go test ./...`. + +## Interfaces + +- Keep `Log` with its string JSON fields `id`, `message`, `level`, `timestamp` and `tag`. +- Keep `Repository` with `Save(Log) error` and `Get(id string) (Log, bool)`, and the constructors `NewMemoryRepository()`, `NewFileRepository(path)` and `NewRepositoryFromConfig(kind,path)` returning `Repository`. +- Keep `GenerateTag(Log) string`, `NewService(repo) *Service`, `Service.Process(Log) (Log,error)` and `NewHandler(repo) http.Handler`. Generate a nonempty tag from the log (for example by level); no tagging taxonomy is prescribed. +- Run the server with `go run ./cmd/server`. Default port is 8081; configure `PORT`, `STORAGE=memory|file` and the file path `LOG_FILE` through the environment. + +## Acceptance Checklist + +- `POST /logs` accepts one JSON object with nonempty `id`, `message`, `level` and RFC3339 `timestamp`. Generate a tag, save the complete record and return it as JSON with a successful 2xx status. Trailing whitespace is allowed, but extra JSON values or other junk are not. +- Malformed JSON or invalid fields return 400, leave no retrievable record, and do not disrupt later valid requests. `GET /log/:id` returns the full stored JSON record and 200 when found, or 404 when missing. Unsupported methods on either route return 405. +- Memory storage supports immediate reads; file storage persists records in JSON or CSV and loads them after reopening or restarting the server. Preserve messages of at least 100 KiB in full. +- A failed file write returns an error and leaves no unsaved record in memory. Creating missing parent directories is allowed; an unavailable destination must not give a success response. diff --git a/task_047/quality_notes.md b/task_047/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..177ca6b7cbc2fc2f6d24f4876159792c81d4b86b --- /dev/null +++ b/task_047/quality_notes.md @@ -0,0 +1,3 @@ +# Quality Notes + +- A minimal closed starter fixture is bundled for deterministic Harbor scoring; it replaces the missing original project context. \ No newline at end of file diff --git a/task_047/solution/README.md b/task_047/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b93291002b3de4830a31a202cfb408ea08ea5c93 --- /dev/null +++ b/task_047/solution/README.md @@ -0,0 +1,13 @@ +# Reference Solution Policy + +This closed-suite task reserves `solution/` for benchmark calibration. + +Before using this task for final scoring, add a known-correct implementation in +`solution/code/` and a `solution/solve.sh` that copies it into `/app`, then +verify: + +- the reference solution receives reward `1`; +- an empty or stub solution receives reward `0`; +- the requirements in `instruction.md` are covered by the executable verifier in `tests/`. + +The reference solution must not be exposed to candidate agents. diff --git a/task_047/solution/code/cmd/server/main.go b/task_047/solution/code/cmd/server/main.go new file mode 100644 index 0000000000000000000000000000000000000000..f5763d963ffda6d3631e68c450bd1f9582bd0fee --- /dev/null +++ b/task_047/solution/code/cmd/server/main.go @@ -0,0 +1,21 @@ +package main + +import ( + "log" + loganalyzer "log_analyzer" + "net/http" + "os" +) + +func main() { + port := os.Getenv("PORT") + if port == "" { + port = "8081" + } + file := os.Getenv("LOG_FILE") + if file == "" { + file = "logs.jsonl" + } + repo := loganalyzer.NewRepositoryFromConfig(os.Getenv("STORAGE"), file) + log.Fatal(http.ListenAndServe(":"+port, loganalyzer.NewHandler(repo))) +} diff --git a/task_047/solution/code/go.mod b/task_047/solution/code/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..9c82c3833960455e77a3789ea1930061cd40adce --- /dev/null +++ b/task_047/solution/code/go.mod @@ -0,0 +1,3 @@ +module log_analyzer + +go 1.23 diff --git a/task_047/solution/code/log_analyzer.go b/task_047/solution/code/log_analyzer.go new file mode 100644 index 0000000000000000000000000000000000000000..2f8fb967f481b481143601f4ffb5e0db24e9bcb8 --- /dev/null +++ b/task_047/solution/code/log_analyzer.go @@ -0,0 +1,182 @@ +package loganalyzer + +import ( + "bufio" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "strings" + "sync" + "time" +) + +type Log struct { + ID string `json:"id"` + Message string `json:"message"` + Level string `json:"level"` + Timestamp string `json:"timestamp"` + Tag string `json:"tag"` +} + +type Repository interface { + Save(log Log) error + Get(id string) (Log, bool) +} + +func GenerateTag(log Log) string { + text := strings.ToLower(log.Level + " " + log.Message) + switch { + case strings.Contains(text, "error"): + return "error" + case strings.Contains(text, "warn"): + return "warn" + case strings.Contains(text, "login"): + return "auth" + default: + return strings.ToLower(log.Level) + } +} + +type memoryRepository struct { + mu sync.RWMutex + data map[string]Log +} + +func NewMemoryRepository() Repository { return &memoryRepository{data: map[string]Log{}} } + +func (r *memoryRepository) Save(log Log) error { + r.mu.Lock() + defer r.mu.Unlock() + r.data[log.ID] = log + return nil +} + +func (r *memoryRepository) Get(id string) (Log, bool) { + r.mu.RLock() + defer r.mu.RUnlock() + log, ok := r.data[id] + return log, ok +} + +type fileRepository struct { + mu sync.Mutex + path string + mem Repository +} + +func NewFileRepository(path string) Repository { + r := &fileRepository{path: path, mem: NewMemoryRepository()} + file, err := os.Open(path) + if err == nil { + defer file.Close() + scanner := bufio.NewScanner(file) + scanner.Buffer(make([]byte, 4096), 2*1024*1024) + for scanner.Scan() { + var item Log + if json.Unmarshal(scanner.Bytes(), &item) == nil { + _ = r.mem.Save(item) + } + } + } + return r +} + +func (r *fileRepository) Save(log Log) error { + r.mu.Lock() + defer r.mu.Unlock() + file, err := os.OpenFile(r.path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644) + if err != nil { + return err + } + defer file.Close() + raw, err := json.Marshal(log) + if err != nil { + return err + } + _, err = file.Write(append(raw, '\n')) + if err != nil { + return err + } + return r.mem.Save(log) +} + +func (r *fileRepository) Get(id string) (Log, bool) { return r.mem.Get(id) } + +func NewRepositoryFromConfig(kind string, path string) Repository { + if strings.ToLower(kind) == "file" { + return NewFileRepository(path) + } + return NewMemoryRepository() +} + +type Service struct{ Repo Repository } + +var ErrInvalidLog = errors.New("invalid log") + +func NewService(repo Repository) *Service { return &Service{Repo: repo} } + +func (s *Service) Process(log Log) (Log, error) { + if strings.TrimSpace(log.ID) == "" || strings.TrimSpace(log.Message) == "" || strings.TrimSpace(log.Level) == "" || strings.TrimSpace(log.Timestamp) == "" { + return Log{}, fmt.Errorf("%w: id, message, level and timestamp are required", ErrInvalidLog) + } + if _, err := time.Parse(time.RFC3339, log.Timestamp); err != nil { + return Log{}, fmt.Errorf("%w: timestamp must be RFC3339", ErrInvalidLog) + } + if log.Tag == "" { + log.Tag = GenerateTag(log) + } + if err := s.Repo.Save(log); err != nil { + return Log{}, err + } + return log, nil +} + +func NewHandler(repo Repository) http.Handler { + svc := NewService(repo) + mux := http.NewServeMux() + mux.HandleFunc("/logs", func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + var log Log + decoder := json.NewDecoder(r.Body) + if err := decoder.Decode(&log); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if decoder.Decode(new(any)) != io.EOF { + http.Error(w, "request must contain one JSON log", http.StatusBadRequest) + return + } + saved, err := svc.Process(log) + if err != nil { + code := http.StatusInternalServerError + if errors.Is(err, ErrInvalidLog) { + code = http.StatusBadRequest + } + http.Error(w, err.Error(), code) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(saved) + }) + mux.HandleFunc("/log/", func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + id := strings.TrimPrefix(r.URL.Path, "/log/") + log, ok := repo.Get(id) + if !ok { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(log) + }) + return mux +} diff --git a/task_047/solution/solve.sh b/task_047/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_047/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_047/task.toml b/task_047/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_047/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_047/task_meta.json b/task_047/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..25e59e7ec063a86acb7b7c079677eeacecde658d --- /dev/null +++ b/task_047/task_meta.json @@ -0,0 +1,30 @@ +{ + "task_id": 74, + "task_category": "application_development", + "origin_model": "GLM-4.6", + "sample_count": 5, + "user_turns": 1, + "language": "go", + "tool_files_from_selected_trace": [ + "README.md", + "config.go", + "errors.go", + "file_repository.go", + "handlers.go", + "log.go", + "log_service.go", + "log_service_test.go", + "log_test.go", + "main.go", + "memory_repository.go", + "memory_repository_test.go", + "repository.go", + "routes.go", + "storage_factory.go" + ], + "input_assets": [], + "expected_outputs": [], + "source_row_id": 444, + "repair_revision": "2026-09-29", + "instruction_sha256": "8f3f8f91d52689e9e880db7ba1024464c2fb62560345e9668bf26f5067a5f16a" +} diff --git a/task_047/tests/_shared/contract_checker.js b/task_047/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_047/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_047/tests/_shared/static_enhancer.sh b/task_047/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_047/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_047/tests/enhancement_cases.json b/task_047/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..3fdafd72f3a163bf9aa58f7c1674c8f5815ecf92 --- /dev/null +++ b/task_047/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","scored":true,"instruction_evidence":"GET /log/:id 返回指定日志;补充 tag 字段;将日志保存到存储层","validator":"validate_enhanced_cases.sh","behavior":"POST 后 GET 完整往返验证 tag 与全部用户字段被保存"}, + {"case_id":"ENHANCED_CASE_2","scored":true,"instruction_evidence":"错误处理健壮,不因单条日志出错影响系统运行","validator":"validate_enhanced_cases.sh","behavior":"非法 JSON 被拒绝后紧接的合法请求仍成功"}, + {"case_id":"ENHANCED_CASE_3","scored":true,"instruction_evidence":"文件存储(JSON/CSV 格式);支持配置切换存储实现","validator":"validate_enhanced_cases.sh","behavior":"通过 file 配置取得仓库,验证接口读写及磁盘内容为字段完整的 JSON"} +] diff --git a/task_047/tests/review_server_test.go b/task_047/tests/review_server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..bbd21725e95b6966019df10e4b9c904fa9f03009 --- /dev/null +++ b/task_047/tests/review_server_test.go @@ -0,0 +1,91 @@ +package loganalyzer + +import ( + "bytes" + "encoding/json" + "io" + "net" + "net/http" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestReviewHTTPServer(t *testing.T) { + binary := filepath.Join(t.TempDir(), "server") + if output, err := exec.Command("go", "build", "-o", binary, "./cmd/server").CombinedOutput(); err != nil { + t.Fatalf("server build: %v %s", err, output) + } + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + port := strings.Split(listener.Addr().String(), ":")[1] + listener.Close() + store := filepath.Join(t.TempDir(), "logs.jsonl") + start := func() *exec.Cmd { + command := exec.Command(binary) + command.Env = append(os.Environ(), "PORT="+port, "STORAGE=file", "LOG_FILE="+store) + if err := command.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { command.Process.Kill(); command.Wait() }) + for i := 0; i < 100; i++ { + conn, err := net.DialTimeout("tcp", "127.0.0.1:"+port, 20*time.Millisecond) + if err == nil { + conn.Close() + return command + } + time.Sleep(20 * time.Millisecond) + } + t.Fatal("server did not bind configured port") + return command + } + client := &http.Client{Timeout: 3 * time.Second} + base := "http://127.0.0.1:" + port + request := func(method, path, body string) (int, []byte) { + t.Helper() + req, _ := http.NewRequest(method, base+path, strings.NewReader(body)) + response, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + raw, _ := io.ReadAll(response.Body) + return response.StatusCode, raw + } + command := start() + item := Log{ID: "large-valid", Message: strings.Repeat("x", 100*1024), Level: "INFO", Timestamp: "2025-09-05T12:00:00Z"} + raw, _ := json.Marshal(item) + for _, suffix := range []string{"{}", "garbage"} { + code, _ := request("POST", "/logs", string(raw)+suffix) + if code != 400 { + t.Fatalf("trailing JSON status=%d", code) + } + } + if code, _ := request("GET", "/log/large-valid", ""); code != 404 { + t.Fatal("invalid record became queryable") + } + if code, _ := request("POST", "/logs", string(raw)+" \n"); code < 200 || code >= 300 { + t.Fatalf("valid POST=%d", code) + } + for _, route := range []string{"/logs", "/log/large-valid"} { + if code, _ := request("DELETE", route, ""); code != 405 { + t.Fatalf("method %s=%d", route, code) + } + } + command.Process.Kill() + command.Wait() + start() + code, data := request("GET", "/log/large-valid", "") + var got Log + if code != 200 || json.Unmarshal(data, &got) != nil || got.Message != item.Message || got.Tag == "" { + t.Fatalf("persisted large log mismatch status=%d bytes=%d", code, len(data)) + } + if !bytes.Contains(data, []byte(item.ID)) { + t.Fatal("incorrect record returned") + } +} diff --git a/task_047/tests/test.sh b/task_047/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f15ac4c1769dcbbdd3e52c9a70f6470f9aef6a7e --- /dev/null +++ b/task_047/tests/test.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set +e +T="$(cd "$(dirname "$0")" && pwd)"; R=/logs/verifier; mkdir -p "$R"; p=1 +command -v go >/dev/null 2>&1 || p=0 +[ "$p" = 1 ] && go test ./... || p=0 +[ "$p" = 1 ] && timeout 30s bash "$T/validate_enhanced_cases.sh" || p=0 +cp "$T/review_server_test.go" zz_review_server_test.go +GOTOOLCHAIN=local GOPROXY=off go test -count=1 -timeout=40s -run '^TestReview' . || p=0 +rm -f zz_review_server_test.go +echo "$p" > "$R/reward.txt"; exit 0 diff --git a/task_047/tests/validate_aaav_dynamic.js b/task_047/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..b3e4335aebf2236ac6da419b8fbf880dc965813f --- /dev/null +++ b/task_047/tests/validate_aaav_dynamic.js @@ -0,0 +1,69 @@ +const fs = require('fs'); +const path = require('path'); +const child_process = require('child_process'); +const TASK_ID = 74; +const LANGUAGE = "go"; +const EXPECTED = []; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { if (!condition) throw new Error(message); } +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} +function globToRe(glob) { + return new RegExp('^' + glob.split('*').map(x => x.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') + '$'); +} +function existsPattern(files, pat) { + const re = globToRe(String(pat).replace(/\\/g, '/')); + return files.some(f => re.test(f.replace(/\\/g, '/')) || f.replace(/\\/g, '/').endsWith(String(pat).replace(/\\/g, '/'))); +} + +const files = walk(process.cwd()); +assert(files.length > 0, 'candidate workspace should contain files'); +const rel = files.map(f => path.relative(process.cwd(), f)); +const source = files.filter(f => /\.(js|jsx|ts|tsx|css|html|py|go|md|svg)$/i.test(f)); +assert(source.length > 0, 'candidate should contain source or report files'); +const totalBytes = source.reduce((n, f) => n + fs.statSync(f).size, 0); +assert(totalBytes >= 80, 'candidate source/report content is too small'); + +if (LANGUAGE === 'go') { + const goFiles = files.filter(f => f.endsWith('.go')); + assert(goFiles.length > 0, 'go task should contain .go files'); + try { + child_process.execFileSync('go', ['test', './...'], { cwd: process.cwd(), stdio: 'pipe', timeout: 120000 }); + } catch (err) { + // The benchmark's own verifier owns task-specific Go behavior. Here we + // keep go test as an opportunistic runtime probe so local module/path + // differences do not create false negatives. + const msg = Buffer.concat([err.stdout || Buffer.alloc(0), err.stderr || Buffer.alloc(0)]).toString().slice(0, 500); + console.warn('go test ./... probe failed but is non-fatal: ' + msg); + } +} else if (LANGUAGE === 'python') { + const pyFiles = files.filter(f => f.endsWith('.py')); + assert(pyFiles.length > 0 || rel.some(f => /\.(html|csv|json|txt|md|png)$/i.test(f)), 'python/data task should contain scripts or produced artifacts'); + for (const f of pyFiles.slice(0, 20)) { + child_process.execFileSync('python', ['-m', 'py_compile', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); + } +} else { + for (const f of files.filter(f => f.endsWith('.js')).slice(0, 20)) { + child_process.execFileSync('node', ['--check', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); + } +} + +for (const pat of EXPECTED) { + assert(existsPattern(rel, pat), 'missing expected artifact pattern after verifier: ' + pat); +} + +console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); diff --git a/task_047/tests/validate_enhanced_cases.sh b/task_047/tests/validate_enhanced_cases.sh new file mode 100644 index 0000000000000000000000000000000000000000..9959dd16b15ab932f7932ce4604e849123b112ae --- /dev/null +++ b/task_047/tests/validate_enhanced_cases.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +set -euo pipefail +tmp_test="zz_enhanced_cases_test.go" +trap 'rm -f "$tmp_test"' EXIT +cat > "$tmp_test" <<'GOEOF' +package loganalyzer +import("bytes";"encoding/json";"net/http";"net/http/httptest";"os";"path/filepath";"testing") +// ENHANCED_CASE_1: POST persists a generated tag and GET returns the same complete user log. +func TestEnhancedCase1PostGetRoundTrip(t *testing.T){h:=NewHandler(NewMemoryRepository());payload:=Log{ID:"round-trip-7",Message:"payment failed",Level:"ERROR",Timestamp:"2025-09-05T12:00:00Z"};b,_:=json.Marshal(payload);p:=httptest.NewRecorder();h.ServeHTTP(p,httptest.NewRequest(http.MethodPost,"/logs",bytes.NewReader(b)));if p.Code<200||p.Code>=300{t.Fatalf("POST=%d %s",p.Code,p.Body.String())};g:=httptest.NewRecorder();h.ServeHTTP(g,httptest.NewRequest(http.MethodGet,"/log/round-trip-7",nil));var got Log;if g.Code!=200||json.Unmarshal(g.Body.Bytes(),&got)!=nil{t.Fatalf("GET=%d %s",g.Code,g.Body.String())};if got.ID!=payload.ID||got.Message!=payload.Message||got.Level!=payload.Level||got.Timestamp!=payload.Timestamp||got.Tag==""{t.Fatalf("round trip changed log: %+v",got)}} +// ENHANCED_CASE_2: malformed input is isolated and does not prevent the next valid log request. +func TestEnhancedCase2BadLogDoesNotBreakServer(t *testing.T){h:=NewHandler(NewMemoryRepository());bad:=httptest.NewRecorder();h.ServeHTTP(bad,httptest.NewRequest(http.MethodPost,"/logs",bytes.NewBufferString("{not-json")));if bad.Code<400{t.Fatalf("malformed JSON unexpectedly accepted: %d",bad.Code)};good:=httptest.NewRecorder();h.ServeHTTP(good,httptest.NewRequest(http.MethodPost,"/logs",bytes.NewBufferString(`{"id":"after-bad","message":"ok","level":"INFO","timestamp":"2025-09-05T12:00:00Z"}`)));if good.Code<200||good.Code>=300{t.Fatalf("valid request after bad one failed: %d %s",good.Code,good.Body.String())}} +// ENHANCED_CASE_3: configured file storage writes decodable JSON and remains usable through its repository interface. +func TestEnhancedCase3ConfiguredFileRepository(t *testing.T){p:=filepath.Join(t.TempDir(),"logs.jsonl");r:=NewRepositoryFromConfig("file",p);if r==nil{t.Fatal("file config returned nil")};want:=Log{ID:"file-config-1",Message:"persist me",Level:"WARN",Timestamp:"2025-09-05T12:00:00Z",Tag:"warn"};if err:=r.Save(want);err!=nil{t.Fatal(err)};reopened:=NewRepositoryFromConfig("file",p);got,ok:=reopened.Get(want.ID);if !ok||got!=want{t.Fatalf("file repository did not survive restart: ok=%v got=%+v",ok,got)};raw,err:=os.ReadFile(p);if err!=nil||len(bytes.TrimSpace(raw))==0{t.Fatalf("storage file missing/empty: %v",err)}} +// ENHANCED_CASE_4: invalid fields yield 400 and do not become queryable; file failures do not create ghost records. +func TestEnhancedCase4ValidationAndFileFailure(t *testing.T){ + repo:=NewMemoryRepository();h:=NewHandler(repo) + for _,body:=range []string{`{"id":"","message":"m","level":"INFO","timestamp":"2025-09-05T12:00:00Z"}`,`{"id":"bad-time","message":"m","level":"INFO","timestamp":"yesterday"}`} { + rec:=httptest.NewRecorder();h.ServeHTTP(rec,httptest.NewRequest(http.MethodPost,"/logs",bytes.NewBufferString(body))) + if rec.Code!=http.StatusBadRequest {t.Fatalf("invalid log status=%d",rec.Code)} + } + if _,ok:=repo.Get("bad-time");ok {t.Fatal("invalid log was stored")} + badPath:=t.TempDir() // Opening a directory as a writable file must fail; creating missing parent dirs is valid. + fileRepo:=NewFileRepository(badPath) + if err:=fileRepo.Save(Log{ID:"ghost",Message:"m",Level:"ERROR",Timestamp:"2025-09-05T12:00:00Z"});err==nil{t.Fatal("file write unexpectedly succeeded")} + if _,ok:=fileRepo.Get("ghost");ok{t.Fatal("failed file write left a ghost in memory")} +} +GOEOF +GOTOOLCHAIN=local GOPROXY=off go test -v -count=1 -timeout=20s -run '^TestEnhancedCase' . diff --git a/task_048/acceptance_checklist.json b/task_048/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..6561bd02f99dd7b88a245fb012d6f025501519e3 --- /dev/null +++ b/task_048/acceptance_checklist.json @@ -0,0 +1,20 @@ +{ + "task_id": 77, + "items": [ + "Single offline index.html and complete Minesweeper game behavior.", + "Explicit mines remain deterministic for grading; omitted mines trigger random placement.", + "5x5, 8x8, and 12x12 choices update the board on new game.", + "Consecutive games of the same size do not reuse the same mine layout." + ], + "acceptance_items": [ + "five exact-state game behavior tiers", + "three additional adjacency/flood/flag tiers", + "size selection and nonrepeating randomized new games" + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-30", + "input_assets": [], + "expected_outputs": [ + "index.html" + ] +} diff --git a/task_048/environment/Dockerfile b/task_048/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2f855b3d12b4e80dd6cd135513202206e95ccdba --- /dev/null +++ b/task_048/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# The mcr/playwright base ships browsers but NOT the `playwright` npm package, +# which the verifier's require('playwright') needs. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_048/environment/code/.gitkeep b/task_048/environment/code/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/task_048/environment/docker-compose.yaml b/task_048/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_048/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_048/instruction.md b/task_048/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fd6e42cc62c1a91614ca73ef5b175964076f351b --- /dev/null +++ b/task_048/instruction.md @@ -0,0 +1,18 @@ +# Build an interactive Minesweeper game + +Create a single offline `index.html` in HTML/CSS/JavaScript. Provide a visible board, status, size selector and New Game button. + +## Controls and state API + +- Use `data-testid="board"`, `"status"`, `"grid-size"` and `"new-game"` on the corresponding elements. Put the state value (`playing`, `won` or `lost`) as text in the status element; any explanatory label can sit outside it. Mark every cell with zero-based `data-r` and `data-c`. Left-click reveals; right-click toggles a flag. Display a text symbol in flagged cells. +- The selector shows dimensions, including 5×5, 8×8 and 12×12; option values may vary. Default to 5×5. +- Expose `window.__game` with `init(config)`, `getState()`, `reveal(r,c)` and `toggleFlag(r,c)`. The three actions return the resulting state and drive the visible board. +- `init` accepts `{rows,cols,mines?}`. Missing dimensions use the current selected size. When `mines` is supplied, use exactly those zero-based `[r,c]` positions. When omitted, sample distinct positions uniformly, with at least one mine and at least one safe cell; consecutive same-size games must not repeat the complete layout. +- `getState()` returns an independent JSON snapshot `{rows,cols,status,cells}`, with `status` equal to `playing`, `won` or `lost`; `cells` is a row-major array of `{revealed,flagged,mine,adj}`. The first three cell fields are booleans and `adj` is the number of mines among eight neighbors. + +## Acceptance Checklist + +- A new game uses the selected size, renders the full grid, and starts with every cell hidden and unflagged. Number labels, flags and the status are readable; cells are visible and do not overlap. +- Revealing a zero-count cell opens its connected zero region and adjacent numbered boundary cells, using the eight-neighbor grid and never propagating through numbers. Hidden flags toggle on and off, and revealing a flagged cell has no effect. +- Revealing a mine sets and displays `lost` and reveals every mine. Revealing all safe cells sets and displays `won`. Once ended, further reveal or flag actions do not change the board. +- Visible actions and API calls update the same board. Changing the returned state cannot alter it; the game runs without browser errors or external dependencies. diff --git a/task_048/quality_notes.md b/task_048/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..1c0b50f9f1dc0078881e741d8d85805874d655a0 --- /dev/null +++ b/task_048/quality_notes.md @@ -0,0 +1,8 @@ +# Quality notes — harbor_077 + +2026-09-30 人工反馈修订。题面、解答与可执行 verifier 已按同一公开约定同步。 + +验证重点: +- five exact-state game behavior tiers(tests/validate_ui_behavior.js) +- three additional adjacency/flood/flag tiers(tests/validate_enhanced_cases.js) +- size selection and nonrepeating randomized new games(tests/validate_enhanced_cases.js) diff --git a/task_048/solution/README.md b/task_048/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bfe621b3cdcf72305f36cdf73f0e081a9cf16a74 --- /dev/null +++ b/task_048/solution/README.md @@ -0,0 +1,3 @@ +# Reference solution + +A correct, dependency-free Minesweeper implementation exposing the deterministic `window.__game` API required by the task. Mine positions are supplied explicitly to `init`, so all behavior (adjacency, flood-fill, win/lose) is fully deterministic with no RNG. diff --git a/task_048/solution/code/index.html b/task_048/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..4a68a9bd021b89d1490136c300f11768ef7338b3 --- /dev/null +++ b/task_048/solution/code/index.html @@ -0,0 +1,213 @@ + + + + +Minesweeper + + + +

      Minesweeper

      +
      Status: playing
      +
      + + + +

      Left-click to reveal · Right-click to flag

      +
      +
      + + + diff --git a/task_048/solution/solve.sh b/task_048/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_048/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_048/task.toml b/task_048/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_048/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_048/task_meta.json b/task_048/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..7151dd5a1d7b55a843dcded0d258133bb14d8b04 --- /dev/null +++ b/task_048/task_meta.json @@ -0,0 +1,13 @@ +{ + "task_id": 77, + "task_category": "frontend_development", + "origin_model": "authored", + "language": "javascript", + "input_assets": [], + "expected_outputs": [ + "index.html" + ], + "notes": "Authored game task with a deterministic window.__game API (explicit mine layout, no RNG) and tiered (partial-credit) behavioral verifier for discrimination.", + "repair_revision": "2026-09-30", + "instruction_sha256": "42ec6a2c15bc65a49037c87a2f6492fdd00e4b0ce23861956e06ede3e17dc762" +} diff --git a/task_048/tests/_shared/contract_checker.js b/task_048/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_048/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_048/tests/_shared/static_enhancer.sh b/task_048/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_048/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_048/tests/enhancement_cases.json b/task_048/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..f893b90eb4ea71a4b61ecb26296aa9da59252ae9 --- /dev/null +++ b/task_048/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "CASE_1", + "instruction_evidence": "five exact-state game behavior tiers", + "validator": "tests/validate_ui_behavior.js", + "behavior": "five exact-state game behavior tiers" + }, + { + "case_id": "CASE_2", + "instruction_evidence": "three additional adjacency/flood/flag tiers", + "validator": "tests/validate_enhanced_cases.js", + "behavior": "three additional adjacency/flood/flag tiers" + }, + { + "case_id": "CASE_3", + "instruction_evidence": "size selection and nonrepeating randomized new games", + "validator": "tests/validate_enhanced_cases.js", + "behavior": "size selection and nonrepeating randomized new games" + } +] diff --git a/task_048/tests/test.sh b/task_048/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f1ad54fd39e8cf36386653c15abdc3f0aef25088 --- /dev/null +++ b/task_048/tests/test.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +[ -f index.html ] || exit 0 +OUT=$(run validate_ui_behavior.js 2>&1); RC=$?; printf '%s +' "$OUT" +CORE=$(printf '%s +' "$OUT" | sed -n 's/^SCORE=//p' | tail -1) +if [ "$RC" -ne 0 ] || [ -z "$CORE" ]; then CORE=0; fi +OUT=$(run validate_enhanced_cases.js 2>&1); RC=$?; printf '%s +' "$OUT" +ENH=$(printf '%s +' "$OUT" | sed -n 's/^ENHANCED_SCORE=//p' | tail -1) +if [ "$RC" -ne 0 ] || [ -z "$ENH" ]; then ENH=0; fi +node -e 'const [a,b]=process.argv.slice(1).map(Number);if(![a,b].every(x=>Number.isFinite(x)&&x>=0&&x<=1))process.exit(1);console.log((5*a+5*b)/10)' "$CORE" "$ENH" > "$REWARD_FILE" +cat "$REWARD_FILE" diff --git a/task_048/tests/validate_aaav_dynamic.js b/task_048/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..e0e3421c3202166bb97e134a05dd65d8f0f38354 --- /dev/null +++ b/task_048/tests/validate_aaav_dynamic.js @@ -0,0 +1,150 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 77; +const KIND = "browser"; +const TESTIDS = [ + "new-game" +]; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_048/tests/validate_browser_smoke.js b/task_048/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_048/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_048/tests/validate_enhanced_cases.js b/task_048/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..6cf598834a79caa4208cca9969e36a05e73956de --- /dev/null +++ b/task_048/tests/validate_enhanced_cases.js @@ -0,0 +1,32 @@ +let enhancedFailed=0; +const fs=require('fs');const path=require('path');const{pathToFileURL}=require('url');const{chromium}=require('playwright'); +function a(x,m){if(!x)throw new Error(m)}function eq(x,y,m){a(require("node:util").isDeepStrictEqual(x,y),`${m}: got ${JSON.stringify(x)} want ${JSON.stringify(y)}`)}async function tc(id,f){try{await f();console.log(id+' PASS')}catch(e){console.error(id+' FAIL: '+e.message);enhancedFailed++}} +(async()=>{const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});const p=await b.newPage();await p.goto(pathToFileURL(path.join(process.cwd(),'index.html')).href); +// ENHANCED_CASE_1: corner, edge and center cells count all and only their eight-neighborhood mines. +await tc('ENHANCED_CASE_1',async()=>{const s=await p.evaluate(()=>__game.init({rows:4,cols:5,mines:[[0,0],[0,2],[1,1],[2,3],[3,4]]}));const at=(r,c)=>s.cells[r*s.cols+c].adj;eq([at(0,1),at(1,2),at(2,2),at(3,3)],[3,3,2,2],'adjacency counts')}); +// ENHANCED_CASE_2: flood fill crosses connected zeros and reveals number boundaries without crossing a mine wall. +await tc('ENHANCED_CASE_2',async()=>{const s=await p.evaluate(()=>{__game.init({rows:5,cols:5,mines:[[0,2],[1,2],[2,2],[3,2],[4,2]]});return __game.reveal(2,0)});const shown=[];s.cells.forEach((c,i)=>{if(c.revealed)shown.push([Math.floor(i/5),i%5])});eq(shown,[[0,0],[0,1],[1,0],[1,1],[2,0],[2,1],[3,0],[3,1],[4,0],[4,1]],'flood set');eq(s.status,'playing','flood status')}); +// ENHANCED_CASE_3: flag toggling is reversible, flagged reveal is a no-op, and losing reveals every mine. +await tc('ENHANCED_CASE_3',async()=>{const r=await p.evaluate(()=>{__game.init({rows:3,cols:4,mines:[[0,0],[2,3]]});const flagged=__game.toggleFlag(1,1);const blocked=__game.reveal(1,1);const unflagged=__game.toggleFlag(1,1);const lost=__game.reveal(0,0);return{flagged,blocked,unflagged,lost}});a(r.flagged.cells[5].flagged&&!r.flagged.cells[5].revealed,'flag failed');eq(r.blocked.cells[5],r.flagged.cells[5],'flagged reveal');a(!r.unflagged.cells[5].flagged,'unflag failed');eq(r.lost.status,'lost','loss status');a(r.lost.cells[0].revealed&&r.lost.cells[11].revealed,'not all mines revealed')}); +// ENHANCED_CASE_4: selecting a size changes the UI board; new games randomize mine locations. +await tc('ENHANCED_CASE_4',async()=>{const sizes=[['8x8',8],['12x12',12],['5x5',5]];for(const [option,n] of sizes){const choice=await p.locator('[data-testid="grid-size"] option').evaluateAll((options,n)=>options.find(item=>item.textContent.replace(/\s+/g,'').replace('×','x')===n+'x'+n)?.value,n);a(choice!==undefined,'missing size choice');await p.locator('[data-testid="grid-size"]').selectOption(choice);await p.locator('[data-testid="new-game"]').click();const states=[];for(let i=0;i<4;i++){if(i)await p.locator('[data-testid="new-game"]').click();const state=await p.evaluate(()=>__game.getState());eq([state.rows,state.cols],[n,n],'selected board dimensions');eq(await p.locator('[data-testid="board"] [data-r][data-c]').count(),n*n,'rendered cell count');const mines=state.cells.map((cell,index)=>cell.mine?index:-1).filter(index=>index>=0);a(mines.length>0&&mines.lengthindex===0||value!==states[index-1]),'consecutive games reused a layout')}}); + +await tc('VISIBLE_UI',async()=>{ + await p.evaluate(()=>__game.init({rows:3,cols:3,mines:[[0,0],[2,2]]})); + const cell=(r,c)=>p.locator('[data-testid="board"] [data-r="'+r+'"][data-c="'+c+'"]'); + await cell(1,1).click({button:'right'}); + a((await p.evaluate(()=>__game.getState())).cells[4].flagged,'right click must flag'); + a((await cell(1,1).textContent()).trim().length>0,'flag must be painted'); + await cell(1,1).click();a(!(await p.evaluate(()=>__game.getState())).cells[4].revealed,'flag blocks actual left click'); + await cell(1,1).click({button:'right'});await cell(1,1).click(); + eq((await cell(1,1).innerText()).trim(),'2','visible cell adjacency'); + const copy=await p.evaluate(()=>{const state=__game.getState();state.cells[4].adj=99;return __game.getState().cells[4].adj});eq(copy,2,'state getter copy'); + fs.mkdirSync('/logs/verifier/visual-audit',{recursive:true}); + await p.screenshot({path:'/logs/verifier/visual-audit/flag-and-reveal.png'}); + await cell(0,0).click();eq((await p.locator('[data-testid=status]').innerText()).trim(),'lost','visible loss'); + const lost=await p.evaluate(()=>__game.getState());await cell(0,1).click();eq(await p.evaluate(()=>__game.getState()),lost,'terminal board must not mutate'); + await p.screenshot({path:'/logs/verifier/visual-audit/lost-board.png'}); + const boxes=await p.locator('[data-testid=board] [data-r][data-c]').evaluateAll(nodes=>nodes.map(node=>{const b=node.getBoundingClientRect();return {x:b.x,y:b.y,w:b.width,h:b.height}})); + for(let i=0;i0&&a.h>0||(()=>{throw Error('invisible cell')})();if(Math.min(a.x+a.w,b.x+b.w)-Math.max(a.x,b.x)>.5&&Math.min(a.y+a.h,b.y+b.h)-Math.max(a.y,b.y)>.5)throw Error('overlapping cells')} +}); +await b.close();console.log('ENHANCED_SCORE='+((5-enhancedFailed)/5));})().catch(e=>{console.error(e.stack||e);process.exit(1)}); diff --git a/task_048/tests/validate_semantics.js b/task_048/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_048/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_048/tests/validate_ui_behavior.js b/task_048/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..42d4df4cc62ffa833602555a80b763f2b9eb572e --- /dev/null +++ b/task_048/tests/validate_ui_behavior.js @@ -0,0 +1,176 @@ +// Tiered, deterministic correctness verifier for the Minesweeper task. +// Drives window.__game with EXPLICIT mine layouts (no RNG) and asserts exact +// state transitions. Prints PASS/FAIL per tier and a final `SCORE=` +// used by test.sh as the (partial) reward. +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +function assert(cond, msg){ if (!cond) throw new Error(msg); } + +// --- independent reference model (mirrors the spec) ----------------------- +function buildExpected(rows, cols, mines){ + const mineSet = new Set(mines.map(m => m[0] + ',' + m[1])); + const isMine = (r,c) => mineSet.has(r + ',' + c); + const adj = (r,c) => { + let n = 0; + for (let dr=-1; dr<=1; dr++) for (let dc=-1; dc<=1; dc++){ + if (dr===0 && dc===0) continue; + const rr=r+dr, cc=c+dc; + if (rr<0||rr>=rows||cc<0||cc>=cols) continue; + if (isMine(rr,cc)) n++; + } + return n; + }; + return { isMine, adj }; +} + +// Expected revealed set from a flood-fill reveal of (sr,sc) on a board where +// nothing is flagged: BFS through zero-adj cells, including bordering numbered +// cells, never crossing a mine. +function expectedFlood(rows, cols, mines, sr, sc){ + const { isMine, adj } = buildExpected(rows, cols, mines); + const revealed = new Set(); + const stack = [[sr,sc]]; + while (stack.length){ + const [r,c] = stack.pop(); + if (r<0||r>=rows||c<0||c>=cols) continue; + const key = r + ',' + c; + if (revealed.has(key)) continue; + if (isMine(r,c)) continue; + revealed.add(key); + if (adj(r,c) === 0){ + for (let dr=-1; dr<=1; dr++) for (let dc=-1; dc<=1; dc++){ + if (dr===0 && dc===0) continue; + stack.push([r+dr, c+dc]); + } + } + } + return revealed; +} + +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 480, height: 760 } }); + const errs = []; + page.on('pageerror', e => errs.push(e.message)); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(300); + + const hasApi = await page.evaluate(() => !!(window.__game + && typeof window.__game.init === 'function' + && typeof window.__game.getState === 'function' + && typeof window.__game.reveal === 'function' + && typeof window.__game.toggleFlag === 'function')); + + // Helper to run a scripted scenario in-page and return the resulting state(s). + const run = (fn, arg) => page.evaluate(fn, arg); + + // Layouts used throughout. A 5x5 with mines clustered in the top-left corner + // plus a vertical "wall" down column 2 (rows 2-4). Flooding from the lower- + // right zero cell (4,4) reveals only the right-hand region + its numbered + // border; the left-hand region stays hidden, so the game does NOT auto-win. + const L = { rows: 5, cols: 5, mines: [[0,0],[0,1],[1,0],[2,2],[3,2],[4,2]] }; + + const tiers = [ + ['T1 API present + init known layout: rows*cols hidden cells, status playing', async () => { + assert(hasApi, 'window.__game with init/getState/reveal/toggleFlag is required'); + assert(errs.length === 0, 'no page errors allowed: ' + errs.join(' | ')); + const st = await run((L) => window.__game.init(L), L); + assert(st.rows === 5 && st.cols === 5, 'rows/cols must match init, got ' + st.rows + 'x' + st.cols); + assert(Array.isArray(st.cells) && st.cells.length === 25, 'cells must be rows*cols=25, got ' + (st.cells && st.cells.length)); + assert(st.status === 'playing', 'fresh game status must be playing, got ' + st.status); + assert(st.cells.every(c => c.revealed === false && c.flagged === false), 'all cells must start hidden and unflagged'); + }], + + ['T2 adjacency: mine flags + adj counts match independent computation', async () => { + const st = await run((L) => window.__game.init(L), L); + const { isMine, adj } = buildExpected(L.rows, L.cols, L.mines); + // Check specific cells: the mines themselves, and several numbered cells. + const checks = [ + [0,0],[0,1],[1,0], // mines + [1,1],[0,2],[2,0],[1,2],[2,1],[2,2], // border / numbered cells + [4,4],[3,3] // far zero cells + ]; + for (const [r,c] of checks){ + const cell = st.cells[r * L.cols + c]; + assert(cell.mine === isMine(r,c), 'mine flag wrong at ('+r+','+c+'): got '+cell.mine+' want '+isMine(r,c)); + assert(cell.adj === adj(r,c), 'adj wrong at ('+r+','+c+'): got '+cell.adj+' want '+adj(r,c)); + } + }], + + ['T3 flood-fill: full zero-region + numbered border revealed, rest hidden', async () => { + await run((L) => window.__game.init(L), L); + const sr = 4, sc = 4; // a zero-adj cell deep in the mine-free region + const boardView=page.locator('[data-testid=board],#board').first(); + const beforePaint=await boardView.screenshot(); + const st = await run((arg) => window.__game.reveal(arg.sr, arg.sc), + { sr, sc }); + const expected = expectedFlood(L.rows, L.cols, L.mines, sr, sc); + assert(expected.has(sr+','+sc), 'sanity: start cell must be a revealable zero cell'); + assert(expected.size > 5, 'sanity: zero-region should be sizeable, got ' + expected.size); + for (let r=0; r { + await run((L) => window.__game.init(L), L); + // flag a hidden non-mine cell + let st = await run(() => window.__game.toggleFlag(3,3)); + assert(st.cells[3*5+3].flagged === true, 'toggleFlag should set flagged=true'); + assert(st.cells[3*5+3].revealed === false, 'flagged cell must remain hidden'); + // reveal on a flagged cell is a no-op (stays hidden) + st = await run(() => window.__game.reveal(3,3)); + assert(st.cells[3*5+3].revealed === false, 'reveal on a flagged cell must be a no-op (stay hidden)'); + assert(st.cells[3*5+3].flagged === true, 'reveal on flagged cell must not clear the flag'); + // unflag + st = await run(() => window.__game.toggleFlag(3,3)); + assert(st.cells[3*5+3].flagged === false, 'second toggleFlag should unflag'); + }], + + ['T5 win/lose: revealing a mine -> lost + mines shown; clearing all -> won', async () => { + // Lose: reveal a mine; all mines become revealed, status lost. + let st = await run((L) => { window.__game.init(L); return window.__game.reveal(0,0); }, L); + assert(st.status === 'lost', 'revealing a mine must set status lost, got ' + st.status); + for (let r=0; r won. + const W = { rows: 3, cols: 3, mines: [[0,0]] }; + st = await run((W) => { + window.__game.init(W); + let s; + for (let r=0; r= height`. After game over, flap and step are no-ops. +- The same seed and actions give identical pipe sequences and trajectories; different seeds influence the sequence. Changing a returned snapshot cannot change the game. +- Display actual injected geometry and state in the canvas, using distinct colors. Real inputs update the same simulation and display. A normal page load advances play through animation frames calling `step(16)`. In a manually initialized scenario, elapsed wall time does not advance state; advance it only through explicit steps. diff --git a/task_049/quality_notes.md b/task_049/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..6ad50e49781b8c1bf5ed34d8f2afda9dacecc678 --- /dev/null +++ b/task_049/quality_notes.md @@ -0,0 +1,15 @@ +# Quality notes + +- Authored (not trajectory-derived). Designed for discrimination: the verifier drives a + mandatory deterministic `window.__game` API and grades 5 behavioral tiers with partial + credit, so stronger implementations score higher instead of a coarse pass/fail. +- The defining design constraint is **wall-clock-free verification**: physics advances only + through `step(dtMs)` with fixed-timestep integration. T2 asserts bit-identical state across + a re-init + identical step sequence, which catches implementations that couple physics to + `requestAnimationFrame`/`Date.now()`/`performance.now()`. +- The hard tiers (T4 score-exactly-once-per-pipe, T5 gap-safe-vs-crash and post-`over` halt) + are the classic Flappy Bird bugs: counting a pipe every frame, treating the gap as solid, + or continuing to integrate after game over. +- All physics constants and bird/pipe placement are injectable so the verifier can construct + exact scenarios without timing flakiness. +- A token-stuffed static page scores 0 (no working API); the reference oracle scores 1.0. diff --git a/task_049/solution/README.md b/task_049/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..796d47a14dab1453e6047c98b73f9632b3bb9beb --- /dev/null +++ b/task_049/solution/README.md @@ -0,0 +1,3 @@ +# Reference solution + +A correct, dependency-free Flappy Bird implementation exposing the deterministic `window.__game` API required by the task. Physics advances only through `step(dtMs)` (fixed-timestep, no wall-clock coupling), and all physics constants plus bird/pipe placement are injectable via `init(config)`. diff --git a/task_049/solution/code/index.html b/task_049/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..723a3a7e4699d716c2ac3956dae9ca69c994ba84 --- /dev/null +++ b/task_049/solution/code/index.html @@ -0,0 +1,296 @@ + + + + +Flappy Bird + + + +

      Flappy Bird

      +
      Score: 0 · ready
      + +
      + + +

      Press Space / click / tap to flap

      +
      + + + diff --git a/task_049/solution/solve.sh b/task_049/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_049/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_049/task.toml b/task_049/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_049/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_049/task_meta.json b/task_049/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..43c0b8b4dd08039a165e7378327b87bae06b1dd0 --- /dev/null +++ b/task_049/task_meta.json @@ -0,0 +1,13 @@ +{ + "task_id": 78, + "task_category": "frontend_development", + "origin_model": "authored", + "language": "javascript", + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "notes": "Authored game task with a deterministic, wall-clock-free window.__game API (physics via step(dtMs)) and a tiered (partial-credit) behavioral verifier for discrimination.", + "repair_revision": "2026-09-29", + "instruction_sha256": "3cdc95a2f3b09f962a6232899f5a8d0eddef3bc4727fcb3738075dc263fcbb9b" +} diff --git a/task_049/tests/_shared/contract_checker.js b/task_049/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_049/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_049/tests/_shared/static_enhancer.sh b/task_049/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_049/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_049/tests/enhancement_cases.json b/task_049/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..c4b04a9a78a6e652cb912b31cd39bbf38e33365f --- /dev/null +++ b/task_049/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","instruction_evidence":"step(dtMs)...半隐式欧拉:vy += gravity*dt/16; y += vy*dt/16,水管按 pipeSpeed*dt/16 左移","validator":"validate_enhanced_cases.js","behavior":"用 8ms 非默认步长精确验证速度、位置和水管位移"}, + {"case_id":"ENHANCED_CASE_2","instruction_evidence":"当小鸟 x 越过某水管右边沿时...passed=true 并使 score 恰好 +1 一次","validator":"validate_enhanced_cases.js","behavior":"对同一已越过水管连续推进三次,验证只计一分"}, + {"case_id":"ENHANCED_CASE_3","instruction_evidence":"鸟的中心 y>=height 或 y<=0 时结束,中心在界内时轮廓触界不会结束","validator":"validate_enhanced_cases.js","behavior":"验证触顶、落地的中心阈值,轮廓先触界时继续,结束后 flap 与 step 不修改状态"} +] diff --git a/task_049/tests/test.sh b/task_049/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f1ad54fd39e8cf36386653c15abdc3f0aef25088 --- /dev/null +++ b/task_049/tests/test.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +[ -f index.html ] || exit 0 +OUT=$(run validate_ui_behavior.js 2>&1); RC=$?; printf '%s +' "$OUT" +CORE=$(printf '%s +' "$OUT" | sed -n 's/^SCORE=//p' | tail -1) +if [ "$RC" -ne 0 ] || [ -z "$CORE" ]; then CORE=0; fi +OUT=$(run validate_enhanced_cases.js 2>&1); RC=$?; printf '%s +' "$OUT" +ENH=$(printf '%s +' "$OUT" | sed -n 's/^ENHANCED_SCORE=//p' | tail -1) +if [ "$RC" -ne 0 ] || [ -z "$ENH" ]; then ENH=0; fi +node -e 'const [a,b]=process.argv.slice(1).map(Number);if(![a,b].every(x=>Number.isFinite(x)&&x>=0&&x<=1))process.exit(1);console.log((5*a+5*b)/10)' "$CORE" "$ENH" > "$REWARD_FILE" +cat "$REWARD_FILE" diff --git a/task_049/tests/validate_aaav_dynamic.js b/task_049/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..9611cf79a75245a18821cf8384a1fae92bc290b0 --- /dev/null +++ b/task_049/tests/validate_aaav_dynamic.js @@ -0,0 +1,148 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 78; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_049/tests/validate_browser_smoke.js b/task_049/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_049/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_049/tests/validate_enhanced_cases.js b/task_049/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..7e845b7ef0f34878654445d52043db45d3278690 --- /dev/null +++ b/task_049/tests/validate_enhanced_cases.js @@ -0,0 +1,68 @@ +let enhancedFailed=0; +const fs=require('fs');const path=require('path');const{pathToFileURL}=require('url');const{chromium}=require('playwright'); +function a(x,m){if(!x)throw new Error(m)}function near(x,y,m){a(Math.abs(x-y)<1e-9,`${m}: got ${x} want ${y}`)}function eq(x,y,m){a(require("node:util").isDeepStrictEqual(x,y),`${m}: got ${JSON.stringify(x)} want ${JSON.stringify(y)}`)}async function tc(id,f){try{await f();console.log(id+' PASS')}catch(e){console.error(id+' FAIL: '+e.message);enhancedFailed++}} +(async()=>{const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});const p=await b.newPage();await p.goto(pathToFileURL(path.join(process.cwd(),'index.html')).href); +// ENHANCED_CASE_1: non-16ms fixed steps use the specified semi-implicit integration and proportional pipe motion. +await tc('ENHANCED_CASE_1',async()=>{const s=await p.evaluate(()=>{__game.init({birdX:80,birdR:12,pipeWidth:52,gravity:2,pipeSpeed:4,width:500,height:400,birdY:100,birdVy:1,pipes:[{x:300,gapY:40,gapH:200,passed:false}],status:'playing'});return __game.step(8)});near(s.bird.vy,2,'vy');near(s.bird.y,101,'y');near(s.pipes[0].x,298,'pipe x');const dims=await p.locator('[data-testid=canvas]').evaluate(c=>[c.width,c.height]);eq(dims,[500,400],'injected canvas geometry');await p.waitForTimeout(100);eq(await p.evaluate(()=>__game.getState()),s,'manual state must not advance on rAF')}); +// ENHANCED_CASE_2: each passed pipe scores exactly once across repeated fixed steps. +await tc('ENHANCED_CASE_2',async()=>{const r=await p.evaluate(()=>{__game.init({birdX:80,birdR:12,pipeWidth:52,gravity:0,pipeSpeed:10,width:500,height:400,birdY:200,birdVy:0,pipes:[{x:500,gapY:-100,gapH:800,passed:false}],status:'playing'});const scores=[];for(let i=0;i<100&&__game.getState().score===0;i++){scores.push(__game.step(16).score)}const crossed=__game.getState();for(let i=0;i<10;i++)__game.step(16);const final=__game.getState();__game.init({birdX:60,birdR:12,pipeWidth:52,gravity:0,pipeSpeed:3,width:300,height:300,birdY:250,birdVy:0,pipes:[{x:10,gapY:40,gapH:100,passed:false}],status:'playing'});const collision=__game.step(16);return{scores,crossed,final,collision}});eq(r.crossed.score,1,'score at crossing');eq(r.final.score,1,'score after crossing');a(r.crossed.pipes[0].passed,'pipe not marked passed');eq(r.collision.status,'over','unsafe crossing must collide');eq(r.collision.score,0,'unsafe crossing must not score')}); +// ENHANCED_CASE_3: ground and ceiling use the center, even when the painted bird overlaps. +await tc('ENHANCED_CASE_3', async () => { + const results = await p.evaluate(() => { + const height = 300; + const base = {birdX: 80, birdR: 12, gravity: 0, width: 500, height, pipes: [], status: 'playing'}; + return [[6, -3], [height - 6, 3]].map(([birdY, birdVy]) => { + __game.init({...base, birdY, birdVy}); + const inside = __game.step(16); + const boundary = __game.step(16); + const frozen = __game.getState(); + __game.flap(); + __game.step(16); + return {inside, boundary, frozen, after: __game.getState()}; + }); + }); + for (const [index, {inside, boundary, frozen, after}] of results.entries()) { + const edge = index === 0 ? 'ceiling' : 'ground'; + eq(inside.status, 'playing', `${edge}: an overlapping outline must not end play before the center reaches the boundary`); + eq(boundary.status, 'over', `${edge}: reaching the boundary with the center must end play`); + eq(after, frozen, `${edge}: flap and step must leave the finished game unchanged`); + } +}); + +await tc('EXACT_SEQUENCE_AND_SEEDS',async()=>{ + const result=await p.evaluate(()=>{ + const cfg={seed:19,status:'playing',gravity:.37,flapImpulse:3,pipeSpeed:1.5,birdY:150,birdVy:-1,width:600,height:900,pipes:[]}; + __game.init(cfg);let y=150,vy=-1;const steps=[4,16,7,24,0,9]; + const errors=[];for(const dt of steps){vy+=.37*dt/16;y+=vy*dt/16;const s=__game.step(dt);errors.push(Math.abs(s.bird.y-y)+Math.abs(s.bird.vy-vy))} + const one=__game.init({seed:19}).pipes,two=__game.init({seed:27}).pipes,again=__game.init({seed:19}).pipes; + const copy=__game.getState();copy.bird.y=-999;copy.pipes[0].gapY=-999; + return {errors,one,two,again,safe:__game.getState()}; + }); + a(result.errors.every(error=>error<1e-8),'every variable step must follow exact public integration'); + eq(result.one,result.again,'seed reproducibility');a(!require('util').isDeepStrictEqual(result.one,result.two),'seeds must influence pipe generation'); + a(result.safe.bird.y!==-999&&result.safe.pipes[0].gapY!==-999,'public state must be copied'); +}); +await tc('ACTUAL_CANVAS_AND_INPUT',async()=>{ + const painted=await p.evaluate(()=>{ + const cfg={gravity:0,pipeSpeed:0,birdX:80,birdR:10,pipeWidth:30,width:400,height:300,birdY:120,pipes:[],status:'playing'}; + const data=()=>Array.from(document.querySelector('[data-testid=canvas]').getContext('2d').getImageData(0,0,400,300).data); + __game.init(cfg);const first=data();__game.init({...cfg,birdY:220});const second=data(); + __game.init({...cfg,pipes:[{x:250,gapY:80,gapH:120,passed:false}]});const third=data(); + let oldBird=0,newBird=0,pipe=0; + for(let y=0;y<300;y++)for(let x=0;x<400;x++){const i=(y*400+x)*4; + const changed=(a,b)=>a.slice(i,i+4).some((v,n)=>v!==b[i+n]); + if(changed(first,second)&&Math.abs(x-80)<=12){if(Math.abs(y-120)<=12)oldBird++;if(Math.abs(y-220)<=12)newBird++} + if(changed(first,third)&&x>=250&&x<280&&(y<80||y>200))pipe++; + } + return {oldBird,newBird,pipe}; + }); + a(painted.oldBird>100&&painted.newBird>100&&painted.pipe>100,'render must follow bird and pipe geometry'); + fs.mkdirSync('/logs/verifier/visual-audit',{recursive:true});await p.screenshot({path:'/logs/verifier/visual-audit/injected-scene.png'}); + await p.evaluate(()=>__game.init({flapImpulse:3,gravity:0,birdY:150,pipes:[]})); + await p.locator('[data-testid=flap]').click();near((await p.evaluate(()=>__game.getState())).bird.vy,-3,'real flap button'); + await p.keyboard.press('Space');near((await p.evaluate(()=>__game.getState())).bird.vy,-3,'space key'); + await p.evaluate(()=>__game.init({gravity:0,birdY:0,status:'playing',pipes:[]})); + await p.evaluate(()=>__game.step(0));eq((await p.locator('[data-testid=status]').innerText()).trim(),'over','visible game over'); + await p.screenshot({path:'/logs/verifier/visual-audit/game-over.png'}); +}); +await b.close();console.log('ENHANCED_SCORE='+((5-enhancedFailed)/5));})().catch(e=>{console.error(e.stack||e);process.exit(1)}); diff --git a/task_049/tests/validate_semantics.js b/task_049/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_049/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_049/tests/validate_ui_behavior.js b/task_049/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..8c24b23c19f9055ee6ef35e8c9a7884c67bbd65d --- /dev/null +++ b/task_049/tests/validate_ui_behavior.js @@ -0,0 +1,246 @@ +// Tiered, deterministic correctness verifier for the Flappy Bird task. +// Drives window.__game and asserts exact state transitions WITHOUT real time: +// physics advances only through step(dtMs) calls. Prints PASS/FAIL per tier and +// a final `SCORE=` used by test.sh as the (partial) reward. +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +function assert(cond, msg){ if (!cond) throw new Error(msg); } +function eq(a, b){ return require("node:util").isDeepStrictEqual(a,b); } + +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 480, height: 760 } }); + const errs = []; + page.on('pageerror', e => errs.push(e.message)); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(300); + + const hasApi = await page.evaluate(() => !!(window.__game + && typeof window.__game.init === 'function' + && typeof window.__game.getState === 'function' + && typeof window.__game.flap === 'function' + && typeof window.__game.step === 'function')); + + // Helper: run an in-page function with one argument, return its result. + const run = (fn, arg) => page.evaluate(fn, arg); + + const tiers = [ + ['T1 API present + canvas + getState has bird & a pipe + status ready', async () => { + assert(hasApi, 'window.__game with init/getState/flap/step is required'); + assert(errs.length === 0, 'no page errors allowed: ' + errs.join(' | ')); + const canvasOk = await run(() => { + const c = document.querySelector('canvas[data-testid="canvas"]') || document.querySelector('canvas'); + return !!c && c.width >= 100 && c.height >= 100; + }); + assert(canvasOk, 'a >=100x100 canvas must render'); + const st = await run(() => window.__game.init({ seed: 1 })); + assert(st && st.bird && typeof st.bird.y === 'number' && typeof st.bird.vy === 'number', 'getState must expose bird {y,vy}'); + assert(Array.isArray(st.pipes) && st.pipes.length >= 1, 'getState must expose at least one upcoming pipe'); + const p = st.pipes[0]; + assert(typeof p.x === 'number' && typeof p.gapY === 'number' && typeof p.gapH === 'number' && typeof p.passed === 'boolean', + 'pipe must have {x, gapY, gapH, passed}'); + assert(st.status === 'ready', 'fresh game status must be "ready", got ' + st.status); + // Canvas-paint anti-fake: a real renderer paints the sky, pipes, ground and + // bird, so the canvas pixels must contain several distinct colors. An engine + // that updates state but never draws leaves a blank/uniform canvas. + const distinctColors = await run(() => { + window.__game.init({seed:1,gravity:0.2,flapImpulse:4,width:500,height:600,birdY:300,pipes:[]}); + window.__game.flap(); // start play so pipes/bird animate + for (let i = 0; i < 5; i++) window.__game.step(16); + const c = document.querySelector('canvas[data-testid="canvas"]') || document.querySelector('canvas'); + const ctx = c.getContext('2d'); + const data = ctx.getImageData(0, 0, c.width, c.height).data; + const seen = new Set(); + for (let i = 0; i < data.length; i += 4){ + seen.add(data[i] + ',' + data[i+1] + ',' + data[i+2]); + if (seen.size >= 8) break; + } + return seen.size; + }); + assert(distinctColors >= 2, 'canvas must paint multiple visible colors, got ' + distinctColors); + // restore the fresh "ready" state for any later assumptions + await run(() => window.__game.init({ seed: 1 })); + }], + + ['T2 gravity makes bird fall + full determinism across re-init', async () => { + // gravity/flapImpulse are INJECTABLE params (the instruction only requires + // "sensible defaults"), so we must NOT reverse-engineer the reference's + // default constant. Instead drive gravity via the documented injection API + // (as T4/T5 already do) with a KNOWN value and start already 'playing' with + // no flap, so the only vertical force is the injected gravity. Then assert + // the bird falls under THAT injected gravity. + const GRAVITY = 0.5; // value we INJECT, not an assumed default + const a = await run((G) => { + window.__game.init({ seed: 1, status: 'playing', width: 500, height: 600, birdX: 80, birdR: 12, pipeWidth: 52, pipeSpeed: 0, gravity: G, birdY: 60, birdVy: 0, pipes: [] }); + const ys = [], vys = []; + for (let i = 0; i < 30; i++){ + const s = window.__game.step(16); + ys.push(s.bird.y); vys.push(s.bird.vy); + } + return { ys, vys, final: window.__game.getState().bird }; + }, GRAVITY); + const EPS = 1e-9; + // vy must be NON-DECREASING each step (a terminal-velocity clamp that holds + // vy constant is acceptable). + for (let i = 1; i < a.vys.length; i++){ + assert(a.vys[i] >= a.vys[i-1] - EPS, 'vy must be non-decreasing under gravity at step ' + i + ' (' + a.vys[i-1] + ' -> ' + a.vys[i] + ')'); + } + // With no flap, the bird must net-fall: both vy and y increase over the run. + // We also allow (but do not require) the precise semi-implicit-Euler net + // increase under the INJECTED gravity, accepting either as evidence of fall. + const netVy = a.vys[a.vys.length - 1] - a.vys[0]; + const minNet = GRAVITY * (a.vys.length - 1); + assert(netVy > EPS || netVy >= minNet - EPS, + 'vy must increase (bird accelerates downward) under injected gravity, net=' + netVy); + for (let i = 1; i < a.ys.length; i++){ + assert(a.ys[i] >= a.ys[i-1] - EPS, 'with no flap, bird.y must move downward (increase) at step ' + i); + } + assert(a.ys[a.ys.length - 1] > a.ys[0], 'bird should net fall downward over the run'); + + // Determinism: identical init + identical step sequence -> identical state. + const b = await run((G) => { + window.__game.init({ seed: 1, status: 'playing', width: 500, height: 600, birdX: 80, birdR: 12, pipeWidth: 52, pipeSpeed: 0, gravity: G, birdY: 60, birdVy: 0, pipes: [] }); + for (let i = 0; i < 30; i++) window.__game.step(16); + return window.__game.getState().bird; + }, GRAVITY); + assert(eq(a.final, b), 'determinism failed: same seed + same steps must give identical bird, got ' + + JSON.stringify(a.final) + ' vs ' + JSON.stringify(b)); + }], + + ['T3 flap pushes the bird up (vy negative; ends higher than baseline)', async () => { + const r = await run((K) => { + // Baseline: start play with a flap, then step K times. + window.__game.init({seed:1,gravity:0.2,flapImpulse:4,width:500,height:600,birdY:300,pipes:[]}); + window.__game.flap(); + for (let i = 0; i < K; i++) window.__game.step(16); + const baselineY = window.__game.getState().bird.y; + + // Flapped run: same start, but flap AGAIN partway through to push up. + window.__game.init({seed:1,gravity:0.2,flapImpulse:4,width:500,height:600,birdY:300,pipes:[]}); + window.__game.flap(); + const flapState = window.__game.getState(); // vy right after flap + const half = Math.floor(K / 2); + for (let i = 0; i < half; i++) window.__game.step(16); + window.__game.flap(); // extra upward impulse + const vyAfterMidFlap = window.__game.getState().bird.vy; + for (let i = half; i < K; i++) window.__game.step(16); + const flappedY = window.__game.getState().bird.y; + return { baselineY, flappedY, vyAfterFirstFlap: flapState.bird.vy, vyAfterMidFlap }; + }, 20); + assert(r.vyAfterFirstFlap < 0, 'immediately after flap() vy must be negative (upward), got ' + r.vyAfterFirstFlap); + assert(r.vyAfterMidFlap < 0, 'after a mid-run flap vy must be negative (upward), got ' + r.vyAfterMidFlap); + assert(r.flappedY < r.baselineY, 'flapping must push the bird UP (smaller y) vs baseline: flapped ' + + r.flappedY + ' should be < baseline ' + r.baselineY); + }], + + ['T4 score increments exactly once per pipe across a multi-step pass', async () => { + const r = await run(() => { + // Single explicit pipe placed just to the right of the bird, with a wide + // gap aligned to the bird so the pass is safe. autoPipes off so no new + // pipes interfere. Bird kept aligned in the gap. + window.__game.init({ + seed: 1, + status: 'playing', birdX:80,birdR:12,pipeWidth:52,width:500,height:400, // start in play without a flap (vy stays 0) + gravity: 0, // remove vertical drift so the bird stays in the gap + pipeSpeed: 4, + birdY: 200, + birdVy: 0, + pipes: [{ x: 80, gapY: 140, gapH: 140, passed: false }] + }); + const scores = []; + for (let i = 0; i < 40; i++){ + const s = window.__game.step(16); + scores.push(s.score); + if (s.status === 'over') break; + } + const afterPass = window.__game.getState(); + // step further (no other pipe) -> score must not change. + for (let i = 0; i < 10; i++) window.__game.step(16); + const later = window.__game.getState(); + return { scores, afterPassScore: afterPass.score, afterPassStatus: afterPass.status, + laterScore: later.score, laterStatus: later.status }; + }); + // Score should reach exactly 1 and never exceed 1 (one pipe, counted once). + const maxScore = Math.max.apply(null, r.scores); + assert(maxScore === 1, 'score must reach exactly 1 after passing one pipe, got max ' + maxScore + ' (statuses: ' + r.afterPassStatus + ')'); + assert(r.afterPassScore === 1, 'score after the pass must be exactly 1, got ' + r.afterPassScore); + // The increment must be a single +1 step (never +2 in one frame, never re-counted). + let increments = 0; + for (let i = 1; i < r.scores.length; i++){ + const d = r.scores[i] - r.scores[i-1]; + assert(d === 0 || d === 1, 'score must change by at most 1 per step, saw delta ' + d); + if (d === 1) increments++; + } + assert(increments === 1, 'exactly one scoring event expected, saw ' + increments); + assert(r.laterScore === 1, 'stepping further without a new pipe must keep score at 1, got ' + r.laterScore); + }], + + ['T5 collision: gap is safe; crash ends game; over halts step/flap', async () => { + // (a) Bird aligned inside a pipe gap; step past the pipe -> stays playing. + const safe = await run(() => { + window.__game.init({ + seed:1,status:'playing',gravity:0,pipeSpeed:4,birdX:80,birdR:12,pipeWidth:52,width:500,height:400, + birdY: 200, birdVy: 0, // aligned inside the gap, no drift + pipes: [{ x: 120, gapY: 150, gapH: 120, passed: false }] + }); + const states = []; + for (let i = 0; i < 60; i++){ + const s = window.__game.step(16); + states.push(s.status); + if (s.status === 'over') break; + } + return { final: window.__game.getState().status, everOver: states.includes('over') }; + }); + assert(!safe.everOver && safe.final === 'playing', + 'passing through the gap must NOT end the game, got final ' + safe.final + ' everOver=' + safe.everOver); + + // (b) Force a collision: bird outside the gap (below it) hits the pipe column. + const crash = await run(() => { + window.__game.init({ + seed:1,status:'playing',gravity:0,pipeSpeed:4,birdX:80,birdR:12,pipeWidth:52,width:500,height:400, + birdY: 360, birdVy: 0, // well below the gap + pipes: [{ x: 80, gapY: 120, gapH: 100, passed: false }] + }); + let st = 'playing'; + for (let i = 0; i < 40; i++){ + const s = window.__game.step(16); + st = s.status; + if (st === 'over') break; + } + return st; + }); + assert(crash === 'over', 'hitting a pipe column outside the gap must set status "over", got ' + crash); + + // (c) Ground collision and post-over freeze. + const frozen = await run(() => { + window.__game.init({ seed: 1, status: 'playing', gravity:1,width:500,height:400,birdX:80,birdR:12,pipeWidth:52,birdY:380, pipes: [] }); + for (let i = 0; i < 60; i++){ + const s = window.__game.step(16); + if (s.status === 'over') break; + } + const over = window.__game.getState(); + // After over, step()/flap() must not change bird or score. + window.__game.step(16); window.__game.step(16); + window.__game.flap(); + const after = window.__game.getState(); + return { overStatus: over.status, sameBird: over.bird.y===after.bird.y && over.bird.vy===after.bird.vy, + sameScore: over.score === after.score, sameStatus: after.status }; + }); + assert(frozen.overStatus === 'over', 'falling to the ground must end the game, got ' + frozen.overStatus); + assert(frozen.sameStatus === 'over', 'status must stay "over" after further calls, got ' + frozen.sameStatus); + assert(frozen.sameBird, 'step()/flap() after "over" must not move the bird'); + assert(frozen.sameScore, 'step()/flap() after "over" must not change score'); + }], + ]; + + let passed = 0; + for (const [name, fn] of tiers){ + try { await fn(); passed++; console.log('PASS ' + name); } + catch (e){ console.log('FAIL ' + name + ': ' + (e && e.message || e)); } + } + console.log('TIERS ' + passed + '/' + tiers.length); + console.log('SCORE=' + (passed / tiers.length).toFixed(3)); + await browser.close(); +})().catch(e => { console.log('FATAL ' + (e && e.stack || e)); console.log('SCORE=0'); }); diff --git a/task_050/acceptance_checklist.json b/task_050/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..22ae9a788a27bb43c36a6161c8aecdf3ef5fdfe5 --- /dev/null +++ b/task_050/acceptance_checklist.json @@ -0,0 +1,16 @@ +{ + "task_id": 79, + "items": [ + "Single offline index.html, no external dependencies or network.", + "Exposes window.__game with init()/setState(board,turn)/getState()/legalMoves()/play(r,c) as specified.", + "init() sets the standard opening (center 4 discs) with Black to move and counts {B:2,W:2}.", + "legalMoves() returns every cell that brackets >=1 opponent disc in at least one of 8 directions.", + "play() flips all bracketed opponent discs in ALL 8 directions, then switches turn.", + "play() on an illegal or occupied cell is a no-op (board and turn unchanged).", + "If the next player has no legal move it passes; if neither can move status becomes 'over' with winner by disc count (or 'draw').", + "Renders an 8x8 board (data-testid=\"board\") plus current turn/counts for human view." + ], + "acceptance_items": [], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "repair_revision": "2026-09-29" +} diff --git a/task_050/environment/Dockerfile b/task_050/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2f855b3d12b4e80dd6cd135513202206e95ccdba --- /dev/null +++ b/task_050/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# The mcr/playwright base ships browsers but NOT the `playwright` npm package, +# which the verifier's require('playwright') needs. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_050/environment/code/.gitkeep b/task_050/environment/code/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/task_050/environment/docker-compose.yaml b/task_050/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_050/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_050/instruction.md b/task_050/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..634a258f3192ddee825b8f4143451ce973657f3c --- /dev/null +++ b/task_050/instruction.md @@ -0,0 +1,19 @@ +# Build a playable Reversi board + +Create a single offline `index.html` for Reversi (Othello). Render a uniform 8×8 board with clickable cells and a display of the turn, piece counts and outcome. DOM, canvas or SVG rendering is fine. + +## Interface + +Expose `window.__game` with `init()`, `setState(board, turn)`, `getState()`, `legalMoves()` and `play(r,c)`. Use zero-based coordinates. + +- A board is an 8×8 array of `'B'`, `'W'` and `null`. Start with white at `[3,3]` and `[4,4]`, black at `[3,4]` and `[4,3]`; Black moves first. +- `init`, `setState` and `play` return the resulting state. `getState()` returns `{board,turn,status,counts:{B,W},winner}`, with status `playing` or `over`, and winner null while playing or `B`, `W` or `draw` when over. +- `legalMoves()` returns all legal positions for the current turn as `[r,c]` pairs, in any order, or an empty list when the game is over. +- Use `data-testid` values `board`, `count-b`, `count-w`, `turn`, `status`, `winner` and `new-game` for the corresponding elements. Put the decimal count, turn symbol, and status value alone in their respective elements; explanatory labels can sit outside them. The New Game button resets the opening. + +## Acceptance Checklist + +- A move into an empty cell is legal only if it brackets one or more consecutive opponent pieces with a friendly piece along at least one of eight directions. Place the piece and flip every bracketed piece along all such directions. An occupied or non-flipping move leaves the board and turn unchanged. +- After a valid move, switch turns, passing back automatically if the opponent cannot move. If neither can move, end the game even on a non-full board. The higher piece count wins; equal counts draw. +- `setState` immediately recognizes a position with no moves for either side as terminal. If only the specified side has no moves, retain that turn for inspection with an empty move list; automatic passing is part of `play`, not single-sided state injection. +- Neither the supplied board nor a returned state shares mutable arrays with the engine. Real clicks and API calls update the same visible discs, turn and counts; status and winner reflect terminal positions. The offline page runs without browser errors. diff --git a/task_050/quality_notes.md b/task_050/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..5a7ca1eb4e9b2c986433964bdc286565335ccea4 --- /dev/null +++ b/task_050/quality_notes.md @@ -0,0 +1,8 @@ +# Quality notes + +- Authored (not trajectory-derived). Designed for discrimination: the verifier drives a + mandatory deterministic `window.__game` API and grades 5 behavioral tiers with partial + credit, so stronger implementations score higher instead of a coarse pass/fail. +- The hard tiers (T3 multi-direction flip, T5 pass + terminal/winner detection) are the + classic Reversi/Othello bugs. +- A token-stuffed static page scores 0 (no working API); the reference oracle scores 1.0. diff --git a/task_050/solution/README.md b/task_050/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d4c3cd5e6598d5ac614bff968f7f60dd11519e9b --- /dev/null +++ b/task_050/solution/README.md @@ -0,0 +1,3 @@ +# Reference solution + +A correct, dependency-free Reversi/Othello implementation exposing the deterministic `window.__game` API required by the task. diff --git a/task_050/solution/code/index.html b/task_050/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..e8e627decc49d92f1daae6b8f35446542e9ace86 --- /dev/null +++ b/task_050/solution/code/index.html @@ -0,0 +1,176 @@ + + + + +Reversi / Othello + + + +

      Reversi / Othello

      +
      + Turn: B · + Black: 2 · + White: 2 · + Status: playing + +
      +
      +
      + +

      Click a highlighted square to place a piece.

      +
      + + + diff --git a/task_050/solution/solve.sh b/task_050/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_050/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_050/task.toml b/task_050/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_050/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_050/task_meta.json b/task_050/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..60d5d768055ef4b840c2b362fefb341d6caf64d8 --- /dev/null +++ b/task_050/task_meta.json @@ -0,0 +1,13 @@ +{ + "task_id": 79, + "task_category": "frontend_development", + "origin_model": "authored", + "language": "javascript", + "input_assets": [], + "expected_outputs": [ + "*.html" + ], + "notes": "Authored game task with a deterministic window.__game API and tiered (partial-credit) behavioral verifier for discrimination.", + "repair_revision": "2026-09-29", + "instruction_sha256": "3c584c6691263362f4175f295eb05af6f69808b755c0adb723da92479b250436" +} diff --git a/task_050/tests/_shared/contract_checker.js b/task_050/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_050/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_050/tests/_shared/static_enhancer.sh b/task_050/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_050/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_050/tests/enhancement_cases.json b/task_050/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..503d9748f55ef4bb99f7e3a4407956650994de22 --- /dev/null +++ b/task_050/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","instruction_evidence":"8×8 棋盘。开局中央 4 子的标准布局...由黑棋 (B) 先手","validator":"validate_enhanced_cases.js","behavior":"验证标准中心布局、轮次、计数和四个初始合法步"}, + {"case_id":"ENHANCED_CASE_2","instruction_evidence":"落子后,所有被夹住的对方棋子(在全部 8 个方向上)都要翻转","validator":"validate_enhanced_cases.js","behavior":"构造中心空位的八方向夹击局面并验证一次翻转全部方向"}, + {"case_id":"ENHANCED_CASE_3","instruction_evidence":"如果轮到的一方没有任何合法落子,则自动跳过;若双方都无合法落子,游戏结束并按棋子数量判定胜者","validator":"validate_enhanced_cases.js","behavior":"构造连续两步局面,验证自动 pass 后终局、计数与胜者"} +] diff --git a/task_050/tests/test.sh b/task_050/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4d56311c78e5287caa7bd8cdd692648b18248ccc --- /dev/null +++ b/task_050/tests/test.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +[ -f index.html ] || exit 0 +OUT=$(run validate_ui_behavior.js 2>&1); RC=$?; printf '%s +' "$OUT" +CORE=$(printf '%s +' "$OUT" | sed -n 's/^SCORE=//p' | tail -1) +if [ "$RC" -ne 0 ] || [ -z "$CORE" ]; then CORE=0; fi +OUT=$(run validate_enhanced_cases.js 2>&1); RC=$?; printf '%s +' "$OUT" +ENH=$(printf '%s +' "$OUT" | sed -n 's/^ENHANCED_SCORE=//p' | tail -1) +if [ "$RC" -ne 0 ] || [ -z "$ENH" ]; then ENH=0; fi +node -e 'const [a,b]=process.argv.slice(1).map(Number);if(![a,b].every(x=>Number.isFinite(x)&&x>=0&&x<=1))process.exit(1);console.log((5*a+4*b)/9)' "$CORE" "$ENH" > "$REWARD_FILE" +cat "$REWARD_FILE" diff --git a/task_050/tests/validate_aaav_dynamic.js b/task_050/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..c1cb6c383e526c01d0d8578feda82c083548fd33 --- /dev/null +++ b/task_050/tests/validate_aaav_dynamic.js @@ -0,0 +1,148 @@ +const fs = require('fs'); +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +const TASK_ID = 79; +const KIND = "browser"; +const TESTIDS = []; +const HAS_QUESTION_WORKFLOW = false; +const SKIP_DIRS = new Set([ + "tests", + "logs", + "node_modules", + ".git" +]); + +function assert(condition, message) { + if (!condition) throw new Error(message); +} + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function findEntry() { + const files = walk(process.cwd()); + if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg')); + return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg')); +} + +async function snapshot(page) { + return await page.evaluate(() => JSON.stringify({ + text: document.body?.innerText || '', + htmlLength: document.body?.innerHTML?.length || 0, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + storage: window.localStorage ? window.localStorage.length : 0, + canvas: Array.from(document.querySelectorAll('canvas')).map(c => { + try { return c.toDataURL().slice(0, 80); } catch { return ''; } + }), + })); +} + +async function runQuestionWorkflow(page) { + const input = page.locator('[data-testid="question-input"]'); + const upload = page.locator('[data-testid="upload-question"]'); + const items = page.locator('[data-testid="question-item"]'); + const before = await items.count(); + const text = 'AAAV dynamic question ' + Date.now(); + await input.fill(text); + await upload.click(); + await page.waitForTimeout(150); + assert(await items.count() > before, 'upload-question should add a question item'); + const first = items.first(); + if (await first.locator('[data-testid="offline-question"]').count()) { + const oldStatus = await first.getAttribute('data-status'); + await first.locator('[data-testid="offline-question"]').click(); + await page.waitForTimeout(100); + assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status'); + } + if (await first.locator('[data-testid="edit-question"]').count()) { + await first.locator('[data-testid="edit-question"]').click(); + await page.waitForTimeout(100); + assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited'); + } + if (await page.locator('[data-testid="role-select"]').count()) { + await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {}); + await page.waitForTimeout(100); + assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user'); + await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {}); + await page.waitForTimeout(100); + assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin'); + } +} + +(async () => { + const entry = findEntry(); + assert(entry, 'no browser-openable entrypoint found'); + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); }); + await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | ')); + + if (KIND === 'svg') { + const stats = await page.evaluate(() => ({ + svg: document.querySelectorAll('svg').length, + elems: document.querySelectorAll('svg *').length, + text: (document.body?.innerText || '').trim().length, + })); + assert(stats.svg >= 1, 'svg task should render an svg root'); + assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure'); + } else { + const stats = await page.evaluate(() => ({ + visible: Array.from(document.querySelectorAll('body *')).filter(el => { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; + }).length, + text: (document.body?.innerText || '').trim().length, + controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length, + })); + assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content'); + + for (const id of TESTIDS) { + const count = await page.locator(`[data-testid="${id}"]`).count(); + assert(count > 0, `missing required data-testid: ${id}`); + } + if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page); + + const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]'); + if (controls.length) { + const before = await snapshot(page); + for (const control of controls.slice(0, 6)) { + const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => ''); + if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {}); + else if (tag === 'select') { + const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => ''); + if (value) await control.selectOption(value).catch(() => {}); + } else { + await control.click({ force: true }).catch(() => {}); + } + } + await page.keyboard.press('Enter').catch(() => {}); + await page.keyboard.press('Space').catch(() => {}); + await page.waitForTimeout(200); + await snapshot(page); + // State changes are informative but not mandatory: static dashboards and + // diagrams may be valid even when generic clicks do not mutate state. + void before; + } + } + assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | ')); + await browser.close(); + console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); +})().catch(err => { + console.error(err && err.stack || err); + process.exit(1); +}); diff --git a/task_050/tests/validate_browser_smoke.js b/task_050/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_050/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_050/tests/validate_enhanced_cases.js b/task_050/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..2e28469700edbe73fbfd591daada8aed239bc0fa --- /dev/null +++ b/task_050/tests/validate_enhanced_cases.js @@ -0,0 +1,30 @@ +let enhancedFailed=0; +const fs=require('fs');const path=require('path');const{pathToFileURL}=require('url');const{chromium}=require('playwright'); +function a(x,m){if(!x)throw new Error(m)}function eq(x,y,m){a(require("node:util").isDeepStrictEqual(x,y),`${m}: got ${JSON.stringify(x)} want ${JSON.stringify(y)}`)}async function tc(id,f){try{await f();console.log(id+' PASS')}catch(e){console.error(id+' FAIL: '+e.message);enhancedFailed++}} +(async()=>{const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});const p=await b.newPage();await p.goto(pathToFileURL(path.join(process.cwd(),'index.html')).href); +// ENHANCED_CASE_1: standard opening has the exact four pieces, black turn, counts and legal move set. +await tc('ENHANCED_CASE_1',async()=>{const s=await p.evaluate(()=>{__game.init();return{state:__game.getState(),moves:__game.legalMoves()}});eq([s.state.board[3][3],s.state.board[3][4],s.state.board[4][3],s.state.board[4][4]],['W','B','B','W'],'opening center');eq([s.state.turn,s.state.counts.B,s.state.counts.W],['B',2,2],'opening state');eq(s.moves.sort(),[[2,3],[3,2],[4,5],[5,4]].sort(),'opening legal moves')}); +// ENHANCED_CASE_2: one legal play flips enclosed opponent pieces in all eight directions. +await tc('ENHANCED_CASE_2',async()=>{const s=await p.evaluate(()=>{const z=Array.from({length:8},()=>Array(8).fill(null));for(const[dr,dc]of[[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]]){z[3+dr][3+dc]='W';z[3+2*dr][3+2*dc]='B'}__game.setState(z,'B');return __game.play(3,3)});a(s.board.flat().filter(x=>x==='B').length===17,'not all eight directions flipped');a(s.board.flat().filter(x=>x==='W').length===0,'opponent pieces remained')}); +// ENHANCED_CASE_3: no-move opponent is automatically passed, then the final move ends the game with the counted winner. +await tc('ENHANCED_CASE_3',async()=>{const r=await p.evaluate(()=>{const z=Array.from({length:8},()=>Array(8).fill('B'));z[0]=['B','W',null,'B','W',null,'B','B'];__game.setState(z,'B');const passed=__game.play(0,2);const over=__game.play(0,5);return{passed,over}});eq([r.passed.status,r.passed.turn],['playing','B'],'automatic pass');eq(r.over.status,'over','terminal status');eq(r.over.winner,'B','winner');eq(r.over.counts,{B:64,W:0},'terminal counts')}); + +await tc('COPY_AND_REAL_PLAY',async()=>{ + await p.evaluate(()=>__game.init()); + const board=p.locator('[data-testid=board]'), before=await board.screenshot(),bounds=await board.boundingBox(); + await p.mouse.click(bounds.x+bounds.width*3.5/8,bounds.y+bounds.height*2.5/8); + const current=await p.evaluate(()=>__game.getState()); + eq(current.board[2][3],'B','real mouse move');eq(current.counts,{B:4,W:1},'real flip counts');eq(current.turn,'W','real turn'); + a(!before.equals(await board.screenshot()),'real move must visibly change discs'); + for(const [id,value]of [['count-b','4'],['count-w','1'],['turn','W']])eq((await p.locator('[data-testid='+id+']').innerText()).trim(),value,'visible HUD '+id); + const copy=await p.evaluate(()=>{const input=__game.getState().board;const state=__game.setState(input,'W');input[2][3]='W';state.board[2][3]=null;return __game.getState()}); + eq(copy.board,current.board,'input and output arrays may not alias engine'); + fs.mkdirSync('/logs/verifier/visual-audit',{recursive:true});await p.screenshot({path:'/logs/verifier/visual-audit/played-and-flipped.png'}); + const terminal=await p.evaluate(()=>{const board=Array.from({length:8},()=>Array(8).fill('W'));board[0][0]=null;return __game.setState(board,'B')}); + eq(terminal.status,'over','non-full terminal');eq(terminal.winner,'W','white terminal victory'); + eq((await p.locator('[data-testid=status]').innerText()).trim(),'over','visible terminal status'); + a((await p.locator('[data-testid=winner]').innerText()).includes('W'),'visible winner'); + await p.screenshot({path:'/logs/verifier/visual-audit/white-victory.png'}); + await p.locator('[data-testid=new-game]').click();eq((await p.evaluate(()=>__game.getState())).counts,{B:2,W:2},'new game resets counts'); +}); +await b.close();console.log('ENHANCED_SCORE='+((4-enhancedFailed)/4));})().catch(e=>{console.error(e.stack||e);process.exit(1)}); diff --git a/task_050/tests/validate_semantics.js b/task_050/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_050/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_050/tests/validate_ui_behavior.js b/task_050/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..6620f3d50a2ddde4970b6f151a3bfabb24ce01e5 --- /dev/null +++ b/task_050/tests/validate_ui_behavior.js @@ -0,0 +1,239 @@ +// Tiered, deterministic correctness verifier for the Reversi/Othello task. +// Drives window.__game and asserts exact state transitions. Prints PASS/FAIL per +// tier and a final `SCORE=` used by test.sh as the (partial) reward. +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +function eq(a, b){ return require("node:util").isDeepStrictEqual(a,b); } +function assert(cond, msg){ if (!cond) throw new Error(msg); } + +// ---------- reference Reversi engine (used to compute expected outcomes) ---------- +const DIRS = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]]; +function emptyBoard(){ return Array.from({length:8}, () => Array(8).fill(null)); } +function clone(b){ return b.map(r => r.slice()); } +function opp(t){ return t === 'B' ? 'W' : 'B'; } +function inB(r,c){ return r>=0 && r<8 && c>=0 && c<8; } +// flips that move (r,c) by `turn` would cause; [] if illegal / occupied. +function flipsFor(board, r, c, turn){ + if (!inB(r,c) || board[r][c] !== null) return []; + const o = opp(turn); + const all = []; + for (const [dr,dc] of DIRS){ + const line = []; + let nr = r+dr, nc = c+dc; + while (inB(nr,nc) && board[nr][nc] === o){ line.push([nr,nc]); nr+=dr; nc+=dc; } + if (line.length && inB(nr,nc) && board[nr][nc] === turn) all.push(...line); + } + return all; +} +function refLegalMoves(board, turn){ + const out = []; + for (let r=0;r<8;r++) for (let c=0;c<8;c++) if (flipsFor(board,r,c,turn).length) out.push([r,c]); + return out; +} +function counts(board){ + let B=0,W=0; + for (const row of board) for (const v of row){ if (v==='B') B++; else if (v==='W') W++; } + return { B, W }; +} + +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 640, height: 760 } }); + const errs = []; + page.on('pageerror', e => errs.push(e.message)); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(300); + + const hasApi = await page.evaluate(() => !!(window.__game + && typeof window.__game.init === 'function' + && typeof window.__game.getState === 'function' + && typeof window.__game.legalMoves === 'function' + && typeof window.__game.play === 'function' + && typeof window.__game.setState === 'function')); + + const run = (fn, arg) => page.evaluate(fn, arg); + const sortMoves = ms => ms.map(m => m.slice()).sort((a,b)=> a[0]-b[0] || a[1]-b[1]); + + // ---------- standard opening (for T1) ---------- + const opening = emptyBoard(); + opening[3][3]='W'; opening[3][4]='B'; opening[4][3]='B'; opening[4][4]='W'; + + // ---------- T3 fixture: a Black move flipping in MULTIPLE directions ---------- + // Black plays at (4,4). It must bracket White in 3 distinct directions: + // up: (3,4)=W flanked by (2,4)=B + // left: (4,3)=W flanked by (4,2)=B + // down-right:(5,5)=W flanked by (6,6)=B + const t3 = emptyBoard(); + t3[2][4]='B'; t3[3][4]='W'; // vertical up + t3[4][2]='B'; t3[4][3]='W'; // horizontal left + t3[6][6]='B'; t3[5][5]='W'; // diagonal down-right + // give White a guaranteed reply (off every ray from (4,4)) so the turn must + // genuinely switch to W (no auto-pass): W can play (0,2) flanking B at (0,1). + t3[0][0]='W'; t3[0][1]='B'; + const t3move = [4,4]; + const t3flips = flipsFor(t3, t3move[0], t3move[1], 'B'); + const t3expected = clone(t3); + t3expected[t3move[0]][t3move[1]] = 'B'; + for (const [fr,fc] of t3flips) t3expected[fr][fc] = 'B'; + + // ---------- T5a fixture: current side (B) has NO legal move; W does -> pass ---------- + // Tiny corner cluster, rest empty. With only B and W discs and lots of empties, + // we engineer it so legalMoves('B') is empty but legalMoves('W') is non-empty, + // and after W plays, B still has no move and play passes back to W. + // Layout (rows 0..2, cols 0..2): + // (0,0)=W (0,1)=B + // (1,0)=B + // For B: needs to flank a W between B and B. (0,0)=W neighbours: (0,1)=B and (1,0)=B, + // but the cell on the far side of W from each B is off-board -> B has no move. + // For W: e.g. play (0,2): left neighbour (0,1)=B, (0,0)=W flanks -> legal, flips (0,1). + const t5a = emptyBoard(); + t5a[0][0]='W'; t5a[0][1]='B'; t5a[1][0]='B'; + const t5aLegalB = refLegalMoves(t5a, 'B'); + const t5aLegalW = refLegalMoves(t5a, 'W'); + + // ---------- T5b fixtures: terminal boards, neither side can move ---------- + // (i) Full board, Black has more discs -> winner 'B'. + const t5bWin = emptyBoard(); + for (let r=0;r<8;r++) for (let c=0;c<8;c++) t5bWin[r][c] = (r*8+c) < 40 ? 'B' : 'W'; // 40 B, 24 W + const winCounts = counts(t5bWin); // {B:40, W:24} + // (ii) Full board, exact tie -> winner 'draw'. + const t5bDraw = emptyBoard(); + for (let r=0;r<8;r++) for (let c=0;c<8;c++) t5bDraw[r][c] = (r*8+c) < 32 ? 'B' : 'W'; // 32/32 + const drawCounts = counts(t5bDraw); + // sanity: full board => no legal moves for either side + assert(refLegalMoves(t5bWin,'B').length===0 && refLegalMoves(t5bWin,'W').length===0, 'fixture: win board not terminal'); + assert(refLegalMoves(t5bDraw,'B').length===0 && refLegalMoves(t5bDraw,'W').length===0, 'fixture: draw board not terminal'); + + const tiers = [ + ['T1 API present + no errors + standard opening', async () => { + assert(hasApi, 'window.__game with init/getState/legalMoves/play/setState is required'); + assert(errs.length === 0, 'no page errors allowed: ' + errs.join(' | ')); + const st = await run(() => window.__game.init()); + assert(Array.isArray(st.board) && st.board.length === 8 && st.board.every(r => Array.isArray(r) && r.length === 8), 'board must be 8x8'); + assert(eq(st.board, opening), 'init must produce the standard 4-disc opening, got ' + JSON.stringify(st.board)); + assert(st.turn === 'B', 'opening turn must be B, got ' + st.turn); + assert(st.status === 'playing', 'opening status must be playing, got ' + st.status); + assert(eq(st.counts, {B:2, W:2}), 'opening counts must be {B:2,W:2}, got ' + JSON.stringify(st.counts)); + assert(st.winner === null, 'opening winner must be null, got ' + JSON.stringify(st.winner)); + // Require visible opening pieces without imposing private CSS/DOM names. + const view=page.locator('[data-testid="board"],#board').first(); + assert(await view.isVisible(),'visible playable board required'); + const openingPaint=await view.screenshot(); + await run(()=>window.__game.setState(Array.from({length:8},()=>Array(8).fill(null)),'B')); + const emptyPaint=await view.screenshot(); + assert(!openingPaint.equals(emptyPaint),'opening discs must be visibly painted, independent of DOM tags, CSS names or canvas'); + await run(()=>window.__game.init({})); + + }], + + ['T2 legalMoves from opening for Black', async () => { + const moves = await run(() => { window.__game.init(); return window.__game.legalMoves(); }); + const got = sortMoves(moves); + const expected = sortMoves([[2,3],[3,2],[4,5],[5,4]]); + assert(eq(got, expected), 'opening Black legal moves must be {[2,3],[3,2],[4,5],[5,4]}, got ' + JSON.stringify(got)); + }], + + ['T3 multi-direction flip', async () => { + assert(t3flips.length >= 3, 'fixture sanity: expected >=3 flips, got ' + t3flips.length); + const st = await run((args) => { + window.__game.setState(args.board, 'B'); + return window.__game.play(args.move[0], args.move[1]); + }, { board: t3, move: t3move }); + assert(eq(st.board, t3expected), 'after the multi-direction move, board must match expected (all bracketed discs flipped). got ' + + JSON.stringify(st.board) + ' expected ' + JSON.stringify(t3expected)); + assert(st.turn === 'W', 'turn must switch to W after a legal move, got ' + st.turn); + assert(eq(st.counts, counts(t3expected)), 'counts must match flipped board, got ' + JSON.stringify(st.counts)); + }], + + ['T4 illegal play is a no-op', async () => { + // (a) a cell that flips nothing -> no-op (board + turn unchanged) + const a = await run((board) => { + const before = window.__game.setState(board, 'B'); + const after = window.__game.play(0, 7); // empty corner, brackets nothing in this fixture + return { before, after }; + }, t3); + assert(eq(a.after.board, a.before.board), 'flips-nothing play must leave board unchanged'); + assert(a.after.turn === a.before.turn && a.after.turn === 'B', 'flips-nothing play must leave turn unchanged (B)'); + // (b) playing on an occupied cell -> no-op + const b = await run((board) => { + const before = window.__game.setState(board, 'B'); + const after = window.__game.play(3, 4); // already 'W' in fixture + return { before, after }; + }, t3); + assert(eq(b.after.board, b.before.board), 'play on an occupied cell must leave board unchanged'); + assert(b.after.turn === b.before.turn && b.after.turn === 'B', 'play on an occupied cell must leave turn unchanged (B)'); + }], + + ['T5 pass + terminal/winner', async () => { + assert(t5aLegalB.length === 0, 'fixture sanity: B should have no legal move'); + assert(t5aLegalW.length > 0, 'fixture sanity: W should have a legal move'); + // (a) current turn = B with no legal move -> legalMoves() empty. + const la = await run((board) => { window.__game.setState(board, 'B'); return window.__game.legalMoves(); }, t5a); + assert(Array.isArray(la) && la.length === 0, 'side-to-move (B) with no move must report empty legalMoves(), got ' + JSON.stringify(la)); + // pass rule: set turn to W (who can move), play a W move; afterwards B has no move, + // so the engine must pass back -> turn returns to W (not stuck on B). + const wMove = t5aLegalW[0]; + const afterPlay = await run((args) => { + window.__game.setState(args.board, 'W'); + return window.__game.play(args.m[0], args.m[1]); + }, { board: t5a, m: wMove }); + // compute expected board after W's move via reference engine + const expBoard = clone(t5a); + const wf = flipsFor(t5a, wMove[0], wMove[1], 'W'); + expBoard[wMove[0]][wMove[1]] = 'W'; + for (const [fr,fc] of wf) expBoard[fr][fc] = 'W'; + const bAfter = refLegalMoves(expBoard, 'B'); + assert(eq(afterPlay.board, expBoard), 'W move must flip correctly, got ' + JSON.stringify(afterPlay.board)); + if (bAfter.length === 0 && refLegalMoves(expBoard, 'W').length > 0){ + assert(afterPlay.turn === 'W', 'when B cannot move after W, turn must pass back to W, got ' + afterPlay.turn); + assert(afterPlay.status === 'playing', 'game should still be playing after a pass, got ' + afterPlay.status); + } else { + assert(afterPlay.turn === 'B', 'turn should switch to B when B has a move, got ' + afterPlay.turn); + } + // (b-i) terminal full board, Black ahead. + // The instruction documents the terminal/winner determination inside play() + // (not as a setState side-effect). A full board has no playable move, so we + // accept EITHER an engine that eagerly reports terminal on setState (over + + // winner) OR one that correctly reports no legal moves for either side + // (terminal by the documented rules). We only require the winner when the + // engine itself declares the game over. + const w = await run((board) => { + const st = window.__game.setState(board, 'B'); + const movesB = window.__game.legalMoves().length; + window.__game.setState(board, 'W'); + const movesW = window.__game.legalMoves().length; + return { st, movesB, movesW }; + }, t5bWin); + assert(eq(w.st.counts, winCounts), 'counts must match terminal board, got ' + JSON.stringify(w.st.counts)); + const wNoMoves = w.movesB === 0 && w.movesW === 0; + assert(w.st.status === 'over' && wNoMoves, + 'full terminal board must be reported "over" OR have no legal moves for either side; got status ' + w.st.status + ' movesB=' + w.movesB + ' movesW=' + w.movesW); + if (w.st.status === 'over') assert(w.st.winner === 'B', 'winner must be B (more discs), got ' + JSON.stringify(w.st.winner)); + assert(la.length === 0, 'guard'); // keep la referenced + // (b-ii) terminal full board, tie. + const d = await run((board) => { + const st = window.__game.setState(board, 'W'); + const movesB = (window.__game.setState(board, 'B'), window.__game.legalMoves().length); + window.__game.setState(board, 'W'); + const movesW = window.__game.legalMoves().length; + return { st, movesB, movesW }; + }, t5bDraw); + assert(eq(d.st.counts, drawCounts), 'tie counts must be {B:32,W:32}, got ' + JSON.stringify(d.st.counts)); + const dNoMoves = d.movesB === 0 && d.movesW === 0; + assert(d.st.status === 'over' && dNoMoves, + 'full tie board must be reported "over" OR have no legal moves for either side; got status ' + d.st.status + ' movesB=' + d.movesB + ' movesW=' + d.movesW); + if (d.st.status === 'over') assert(d.st.winner === 'draw', 'winner must be draw on a tie, got ' + JSON.stringify(d.st.winner)); + }], + ]; + + let passed = 0; + for (const [name, fn] of tiers){ + try { await fn(); passed++; console.log('PASS ' + name); } + catch (e){ console.log('FAIL ' + name + ': ' + (e && e.message || e)); } + } + console.log('TIERS ' + passed + '/' + tiers.length); + console.log('SCORE=' + (passed / tiers.length).toFixed(3)); + await browser.close(); +})().catch(e => { console.log('FATAL ' + (e && e.stack || e)); console.log('SCORE=0'); }); diff --git a/task_051/acceptance_checklist.json b/task_051/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..27e6c7858539a87315f16f39f5aa3fd640f8761b --- /dev/null +++ b/task_051/acceptance_checklist.json @@ -0,0 +1,25 @@ +{ + "task_id": 83, + "category": "build_deployment", + "language": "python", + "acceptance_items": [ + "An env file missing one required key and having one empty value exits non-zero and prints both offending key names.", + "A complete env file (all required keys present and non-empty) exits 0.", + "A key appended to .env.example at runtime is reported as missing when omitted (required set derived dynamically).", + "Uses only the Python standard library; runs without internet.", + "Python files compile.", + "Template keys, whitespace, duplicate assignments, literal values and empty templates." + ], + "input_assets": [ + ".env.example" + ], + "expected_outputs": [ + "validate_env.py" + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "risk_notes": [ + "Verifier appends a new required key to the template at runtime to defeat hardcoded key lists; temp files cleaned up." + ], + "repair_revision": "2026-09-29", + "review_revision": "2026-10-07" +} diff --git a/task_051/environment/Dockerfile b/task_051/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2bd34b80ad954f5177a9066cedb797e932ed68ae --- /dev/null +++ b/task_051/environment/Dockerfile @@ -0,0 +1,4 @@ +# syntax=docker/dockerfile:1.7-labs +FROM python:3.12-slim@sha256:090ba77e2958f6af52a5341f788b50b032dd4ca28377d2893dcf1ecbdfdfe203 +WORKDIR /app +COPY ./code /app diff --git a/task_051/environment/code/.env.example b/task_051/environment/code/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..56ba8d0216bd0722ff51ed333571f1641c5531b3 --- /dev/null +++ b/task_051/environment/code/.env.example @@ -0,0 +1,6 @@ +DATABASE_URL= +API_KEY= +PORT= +LOG_LEVEL= +# this is a comment, ignore +SECRET_TOKEN= diff --git a/task_051/environment/code/README.md b/task_051/environment/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..257e6ec88a82f84bd2f509d46d8a82315149deb4 --- /dev/null +++ b/task_051/environment/code/README.md @@ -0,0 +1,24 @@ +# Env template validator starter + +`.env.example` is the template listing the REQUIRED key names (one per line as +`KEY=`, value ignored): + +``` +DATABASE_URL= +API_KEY= +PORT= +LOG_LEVEL= +SECRET_TOKEN= +``` + +Implement `validate_env.py [template]` so that it: + +- derives the required key set dynamically from the template (default + `.env.example`); blank lines and `#` comments are ignored, +- parses the target env file, and reports keys that are **MISSING** and keys + present but with an **EMPTY** value (printing the offending key names), +- exits 0 only if every required key is present and non-empty, otherwise exits + non-zero. + +Keys added to the template later must be enforced automatically. Standard library +only. diff --git a/task_051/environment/docker-compose.yaml b/task_051/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_051/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_051/instruction.md b/task_051/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e511b355ad41ae01ed38878d2fedb9a6f195657b --- /dev/null +++ b/task_051/instruction.md @@ -0,0 +1,13 @@ +# Validate environment files against a template + +Implement `python3 validate_env.py ENV_PATH [TEMPLATE_PATH]` using the Python standard library. Read the target file at the required `ENV_PATH`. When `TEMPLATE_PATH` is omitted, use the supplied `.env.example` in the current directory. No network or extra dependency is needed. + +## Parsing + +Use the same rules for both files: ignore blank lines, comments beginning with `#` after leading whitespace, lines without `=` and empty key names. Split each assignment at the first `=`, trim whitespace around key and value, and preserve literal `=` and `#` within the value. If a key appears more than once, use the last assignment. Template values do not set defaults or affect what is required. + +## Acceptance Checklist + +- Derive the required keys from the selected template on every invocation. A changed template changes the required set, and an empty template imposes no requirements. +- For each required key absent from the target, report `MISSING` and its name on stdout. For each required key present with an empty final value, report `EMPTY` and its name. Extra keys, including empty ones, do not affect validation. +- Exit 0 only when all required keys are present and nonempty; otherwise report both kinds of issue when present and exit nonzero. diff --git a/task_051/quality_notes.md b/task_051/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..4d260b87858b43ddb1e957f359acb0e7a0105a3f --- /dev/null +++ b/task_051/quality_notes.md @@ -0,0 +1,10 @@ +# Quality notes — task_083 + +- Closed/self-contained: pure Python stdlib (`pathlib`), no network, no extra deps. +- Discrimination: a validator with a hardcoded required-key list fails the + append-new-key-to-template check; one that only checks presence (not empty + value) fails the EMPTY-value check; one that always exits 0 fails the + incomplete-env check. +- Verifier independently parses the template, constructs missing/empty env files, + and asserts both exit code and that the offending key names appear in stdout, + rather than grepping source. Temp files are cleaned up. diff --git a/task_051/solution/README.md b/task_051/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d6b01e6b4e6feec48cd8bab4cb1cf26a1b895002 --- /dev/null +++ b/task_051/solution/README.md @@ -0,0 +1,8 @@ +# Reference solution — task_083 + +`validate_env.py` parses `.env.example` to derive the required key set (ignoring +blanks and `#` comments), parses the target env file the same way, and reports +`MISSING` (absent) and `EMPTY` (present but blank) keys. It exits non-zero when any +required key is missing or empty, printing the offending names, and exits 0 only +when all required keys are present and non-empty. The required set is derived +dynamically from the template, so keys added later are enforced automatically. diff --git a/task_051/solution/code/.env.example b/task_051/solution/code/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..56ba8d0216bd0722ff51ed333571f1641c5531b3 --- /dev/null +++ b/task_051/solution/code/.env.example @@ -0,0 +1,6 @@ +DATABASE_URL= +API_KEY= +PORT= +LOG_LEVEL= +# this is a comment, ignore +SECRET_TOKEN= diff --git a/task_051/solution/code/validate_env.py b/task_051/solution/code/validate_env.py new file mode 100644 index 0000000000000000000000000000000000000000..954724673cf63477c22b613b8f5d7c9e1329cbb4 --- /dev/null +++ b/task_051/solution/code/validate_env.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Validate an env file against a `.env.example` template. + +Usage: python validate_env.py [template] + +The template (default `.env.example`) lists the REQUIRED key names, one per line +as `KEY=` (any value after `=` in the template is ignored; only the key matters). +Blank lines and lines starting with `#` are ignored. + +The target env file is parsed the same way. The validator reports: + - MISSING: required keys absent from the target file. + - EMPTY: required keys present in the target but with an empty value. + +Exit 0 only if every required key is present with a non-empty value; otherwise +exit non-zero and print the offending key names. +""" +import pathlib +import sys + +DEFAULT_TEMPLATE = ".env.example" + + +def parse_env(path): + """Return an ordered dict of KEY -> value (str) from an env-style file. + + Lines without '=' or starting with '#' (after strip) are ignored. + """ + result = {} + text = pathlib.Path(path).read_text(encoding="utf-8") + for raw in text.splitlines(): + line = raw.strip() + if not line or line.startswith("#"): + continue + if "=" not in line: + continue + key, _, value = line.partition("=") + key = key.strip() + if not key: + continue + result[key] = value.strip() + return result + + +def required_keys(template): + # derive the required set dynamically from the template file + return list(parse_env(template).keys()) + + +def main(argv): + if len(argv) < 2: + print("usage: python validate_env.py [template]") + return 2 + env_file = argv[1] + template = argv[2] if len(argv) > 2 else DEFAULT_TEMPLATE + + required = required_keys(template) + actual = parse_env(env_file) + + missing = [k for k in required if k not in actual] + empty = [k for k in required if k in actual and actual[k] == ""] + + if missing: + print("MISSING: " + " ".join(missing)) + if empty: + print("EMPTY: " + " ".join(empty)) + + if missing or empty: + print(f"validation FAILED: {len(missing)} missing, {len(empty)} empty") + return 1 + print(f"validation OK: all {len(required)} required key(s) present and non-empty") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/task_051/solution/solve.sh b/task_051/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_051/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_051/task.toml b/task_051/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_051/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_051/task_meta.json b/task_051/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..c64f56696fa39675e11f12223c3d376dcbe761b9 --- /dev/null +++ b/task_051/task_meta.json @@ -0,0 +1,17 @@ +{ + "task_id": 83, + "task_category": "build_deployment", + "origin_model": "authored", + "sample_count": 0, + "user_turns": 0, + "language": "python", + "input_assets": [ + ".env.example" + ], + "expected_outputs": [ + "validate_env.py" + ], + "source_row_id": null, + "repair_revision": "2026-09-29", + "instruction_sha256": "6aac718c9b5939b6276cdd1d8ac2b7faa8fb31d1be9d31bae318d741646faea5" +} diff --git a/task_051/tests/_shared/contract_checker.js b/task_051/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_051/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_051/tests/_shared/static_enhancer.sh b/task_051/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_051/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_051/tests/enhancement_cases.json b/task_051/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..29845723e12147526119180674ac00b36459fa36 --- /dev/null +++ b/task_051/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +{ + "task_id": "task_083", + "cases": [ + { + "id": "ENHANCED_CASE_1", + "instruction_evidence": "模板动态解析;忽略空行、注释、无等号行和值", + "assertion": "custom template proves only valid left-hand keys become requirements" + }, + { + "id": "ENHANCED_CASE_2", + "instruction_evidence": "同时报告MISSING与EMPTY并非零退出", + "assertion": "one target containing both conditions reports both exact keys and fails" + }, + { + "id": "ENHANCED_CASE_3", + "instruction_evidence": "完整env成功;模板新增键动态纳入", + "assertion": "complete file passes, then runtime-added template key makes same file fail as missing" + } + ] +} diff --git a/task_051/tests/review_hard.py b/task_051/tests/review_hard.py new file mode 100644 index 0000000000000000000000000000000000000000..403374fd9cdf7a4cc9523e4b63581d4b59019d6c --- /dev/null +++ b/task_051/tests/review_hard.py @@ -0,0 +1,33 @@ +"""Exercise published parsing boundaries through the CLI, not private APIs.""" +import subprocess +import sys +import tempfile +from pathlib import Path + + +def main(root): + with tempfile.TemporaryDirectory() as temporary: + workspace = Path(temporary) + template, target = workspace / 'template', workspace / 'candidate.env' + cases = [ + ('A=\nB=\nC=\n', 'A=old\nA=new=with=equal\nB=x\nC=y\nEXTRA=\n#comment\nnotassignment\n', True, ''), + ('A=\nB=\nC=\n', 'A=x\nB=x\nC=y\nA=\n', False, 'EMPTY'), + ('A=\nB=\nC=\n', 'A=x\nC=y\n', False, 'MISSING'), + (' # note\n = ignored\n TOKEN = ignored\nTOKEN=last\n', ' TOKEN = #literal=a=b \n', True, ''), + ('TOKEN=\n', 'TOKEN= \t \n', False, 'EMPTY'), + (' # no requirements\ninvalid line\n=ignored\n', '', True, ''), + ] + for index, (requirements, content, succeeds, label) in enumerate(cases): + template.write_text(requirements) + target.write_text(content) + result = subprocess.run([sys.executable, str(root / 'validate_env.py'), + str(target), str(template)], cwd=root, + text=True, capture_output=True, timeout=30) + assert (result.returncode == 0) == succeeds, (index, result.stdout, result.stderr) + if label: + assert label in result.stdout, (index, result.stdout) + print(f'Parsing boundary {index + 1}: PASS; stdout={result.stdout.strip()!r}') + + +if __name__ == '__main__': + main(Path(sys.argv[1]).resolve()) diff --git a/task_051/tests/review_legacy.sh b/task_051/tests/review_legacy.sh new file mode 100644 index 0000000000000000000000000000000000000000..f0a3b424193bde75827199bf39ee5fa82eb06733 --- /dev/null +++ b/task_051/tests/review_legacy.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +set -euo pipefail +set +e +TASK_ID='83' +source "$(cd "$(dirname "$0")" && pwd)/_shared/static_enhancer.sh" +LOG_DIR="/logs/verifier" +if ! mkdir -p "$LOG_DIR" 2>/dev/null; then LOG_DIR="logs/verifier"; mkdir -p "$LOG_DIR"; fi +REWARD_FILE="$LOG_DIR/reward.txt" +PASS=1 +CHECKS=0 +FAILS=0 + +note() { echo "[Task $TASK_ID] $*"; } +fail() { note "FAIL: $*"; PASS=0; FAILS=$((FAILS+1)); } +check() { CHECKS=$((CHECKS+1)); "$@"; local code=$?; if [ $code -ne 0 ]; then fail "$*"; fi; } +have_any() { local pattern="$1"; compgen -G "$pattern" >/dev/null 2>&1; } +grep_any() { local pattern="$1"; shift; grep -REiq -- "$pattern" "$@" 2>/dev/null; } +source_files() { find . -type f \( -name '*.html' -o -name '*.js' -o -name '*.jsx' -o -name '*.ts' -o -name '*.tsx' -o -name '*.css' -o -name '*.py' -o -name '*.go' -o -name '*.swift' -o -name '*.svg' \) ! -path './tests/*' ! -path './logs/*'; } + +note "enhanced deterministic verifier start" +static_enhance_check "${TASK_ID}" "$(pwd)" +mapfile -t py_files < <(find . -type f -name '*.py' ! -path './tests/*') +if [ ${#py_files[@]} -eq 0 ]; then fail "no Python source found"; fi +if command -v python3 >/dev/null 2>&1; then + for f in "${py_files[@]}"; do python3 -m py_compile "$f" >/tmp/harbor_py_compile.log 2>&1 || fail "python compile failed: $f"; done +fi + +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +if command -v python3 >/dev/null 2>&1; then + check python3 "$TEST_DIR/validate_outputs.py" +else + fail "python3 unavailable for output validation" +fi +# BEGIN ENHANCED_CASES_081_088 +if command -v python3 >/dev/null 2>&1; then + check python3 "$TEST_DIR/validate_enhanced.py" 83 "$(pwd)" +else + fail "python3 unavailable for enhanced validation" +fi +# END ENHANCED_CASES_081_088 +# BEGIN AAAV_DYNAMIC_TEST +if [ -f "$TEST_DIR/validate_aaav_dynamic.js" ]; then + if command -v node >/dev/null 2>&1; then + check node "$TEST_DIR/validate_aaav_dynamic.js" + else + note "AAAV dynamic validation skipped (node unavailable in this runtime)" + fi +fi +# END AAAV_DYNAMIC_TEST +note "checks=$CHECKS fails=$FAILS" +if [ "$PASS" -eq 1 ]; then + echo 1 > "$REWARD_FILE" + note "PASS" + exit 0 +fi +echo 0 > "$REWARD_FILE" +note "FAIL" +exit 0 diff --git a/task_051/tests/test.sh b/task_051/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56b0776f3ccad7f2da017c3b6e7cd69a9a1454e6 --- /dev/null +++ b/task_051/tests/test.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -uo pipefail +bash /tests/review_legacy.sh +CORE=$(cat /logs/verifier/reward.txt 2>/dev/null || echo 0) +mkdir -p /logs/verifier +python3 /tests/review_hard.py /app 2>&1 | tee /logs/verifier/review_hard.log +RC=${PIPESTATUS[0]} +if [ "$RC" -ne 0 ]; then echo "REVIEW_HARD failed with exit code $RC"; fi +if [ "$RC" -eq 0 ]; then echo "$CORE"; else echo 0; fi > /logs/verifier/reward.txt +exit 0 diff --git a/task_051/tests/validate_aaav_dynamic.js b/task_051/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..f48d5657c9770d3ae95bf11bba17327f54e086e7 --- /dev/null +++ b/task_051/tests/validate_aaav_dynamic.js @@ -0,0 +1,27 @@ +const fs = require('fs'); +const path = require('path'); +const child_process = require('child_process'); +const TASK_ID = 83; +const LANGUAGE = "python"; +const EXPECTED = []; +const SKIP_DIRS = new Set(["tests","logs","node_modules",".git"]); +function assert(condition, message) { if (!condition) throw new Error(message); } +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} +const files = walk(process.cwd()); +assert(files.length > 0, 'candidate workspace should contain files'); +const source = files.filter(f => /\.(js|jsx|ts|tsx|css|html|py|go|md|svg)$/i.test(f)); +assert(source.length > 0, 'candidate should contain source or report files'); +const pyFiles = files.filter(f => f.endsWith('.py')); +for (const f of pyFiles.slice(0, 20)) { + child_process.execFileSync('python3', ['-m', 'py_compile', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); +} +console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); diff --git a/task_051/tests/validate_enhanced.py b/task_051/tests/validate_enhanced.py new file mode 100644 index 0000000000000000000000000000000000000000..5af4c3ed8dc3066b7835a5e7ec3c53c5b3f910c6 --- /dev/null +++ b/task_051/tests/validate_enhanced.py @@ -0,0 +1,333 @@ +#!/usr/bin/env python3 +import base64 +import gzip +import hashlib +import json +import os +import pathlib +import re +import shutil +import subprocess +import sys +import tempfile +import time +import zipfile + +TIMEOUT = 8 + + +def run(root, script, *args, timeout=TIMEOUT): + env = os.environ.copy() + for key in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"): + env.pop(key, None) + env["PYTHONHASHSEED"] = "0" + return subprocess.run( + [sys.executable, str(root / script), *map(str, args)], cwd=root, + text=True, capture_output=True, timeout=timeout, env=env, + ) + + +def workspace(candidate): + td = tempfile.TemporaryDirectory(prefix="glm-enhanced-") + root = pathlib.Path(td.name) / "code" + shutil.copytree(pathlib.Path(candidate).resolve(), root) + return td, root + + +def lines(proc): + return [x.strip() for x in proc.stdout.splitlines() if x.strip()] + + +def exact_actions(proc, expected): + assert proc.returncode == 0, proc.stdout + proc.stderr + assert lines(proc) == expected, f"status lines {lines(proc)!r} != {expected!r}" + + +def case81(candidate): + td, root = workspace(candidate) + try: + (root / "src/deep").mkdir(parents=True, exist_ok=True) + data = { + "targets": [ + {"name": "alpha-x", "inputs": ["src/a.txt", "src/deep/b.txt"], "output": "out/deep/a.bin"}, + {"name": "beta_9", "inputs": ["src/c.txt"], "output": "out/b.txt"}, + {"name": "empty", "inputs": [], "output": "out/empty.txt"}, + ] + } + (root / "build.json").write_text(json.dumps(data), encoding="utf-8") + (root / "src/a.txt").write_bytes(b"A\nA") + (root / "src/deep/b.txt").write_bytes(b"B\x00B") + (root / "src/c.txt").write_bytes(b"C") + for p in (root / ".buildcache.json", root / "out"): + if p.is_dir(): shutil.rmtree(p) + elif p.exists(): p.unlink() + # ENHANCED_CASE_1: every declared target builds with exact ordered bytes. + p1 = run(root, "builder.py") + exact_actions(p1, ["BUILD alpha-x", "BUILD beta_9", "BUILD empty"]) + assert (root / "out/deep/a.bin").read_bytes() == b"A\nA\nB\x00B" + assert (root / "out/b.txt").read_bytes() == b"C" + assert (root / "out/empty.txt").read_bytes() == b"" + print("ENHANCED_CASE_1 PASS") + mtimes = {p: (root / p).stat().st_mtime_ns for p in ("out/deep/a.bin", "out/b.txt", "out/empty.txt")} + time.sleep(0.02) + # ENHANCED_CASE_2: unchanged inputs and existing outputs are skipped and untouched. + p2 = run(root, "builder.py") + exact_actions(p2, ["SKIP alpha-x", "SKIP beta_9", "SKIP empty"]) + assert mtimes == {p: (root / p).stat().st_mtime_ns for p in mtimes} + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: one target's content mutation invalidates only that target. + (root / "src/deep/b.txt").write_bytes(b"changed") + p3 = run(root, "builder.py") + exact_actions(p3, ["BUILD alpha-x", "SKIP beta_9", "SKIP empty"]) + assert (root / "out/deep/a.bin").read_bytes() == b"A\nA\nchanged" + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def manifest_oracle(dist): + return {p.relative_to(dist).as_posix(): {"sha256": hashlib.sha256(p.read_bytes()).hexdigest(), "size": p.stat().st_size} + for p in sorted(dist.rglob("*")) if p.is_file()} + + +def case82(candidate): + td, root = workspace(candidate) + try: + dist = root / "payload"; (dist / "a/b").mkdir(parents=True, exist_ok=True) + (dist / "zero").write_bytes(b""); (dist / "a/b/data.bin").write_bytes(b"\x00\xffx"); (dist / "sp ace.txt").write_bytes(b"hello") + mf = root / "custom-manifest.json" + # ENHANCED_CASE_1: recursive POSIX keys, SHA256 and byte sizes exactly match. + g = run(root, "manifest.py", "generate", dist, mf); assert g.returncode == 0, g.stdout + g.stderr + assert json.loads(mf.read_text()) == manifest_oracle(dist) + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: clean passes; changed, missing, and extra files fail and identify paths. + assert run(root, "manifest.py", "verify", dist, mf).returncode == 0 + target = dist / "a/b/data.bin"; original = target.read_bytes() + for mode, name in (("changed", "a/b/data.bin"), ("missing", "a/b/data.bin"), ("extra", "surprise.new")): + if mode == "changed": target.write_bytes(b"different") + elif mode == "missing": target.unlink() + else: (dist / name).write_bytes(b"extra") + p = run(root, "manifest.py", "verify", dist, mf) + assert p.returncode != 0 and name in p.stdout + p.stderr, (mode, p.stdout, p.stderr) + if mode in ("changed", "missing"): target.write_bytes(original) + else: (dist / name).unlink() + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: newly added nested files appear after regeneration. + (dist / "a/new/deeper").mkdir(parents=True); (dist / "a/new/deeper/z").write_bytes(b"z") + assert run(root, "manifest.py", "generate", dist, mf).returncode == 0 + assert json.loads(mf.read_text()) == manifest_oracle(dist) + assert run(root, "manifest.py", "verify", dist, mf).returncode == 0 + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def case83(candidate): + td, root = workspace(candidate) + try: + template = root / "custom.example" + template.write_text("# ignored\n\n BAD LINE\n FIRST = ignored\nSECOND=template-value\nTHIRD=\n", encoding="utf-8") + env = root / "candidate.env" + # ENHANCED_CASE_1: only valid left-hand template keys are requirements. + env.write_text("FIRST=one\nSECOND=two\nTHIRD=three\n", encoding="utf-8") + p = run(root, "validate_env.py", env, template); assert p.returncode == 0, p.stdout + p.stderr + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: missing and empty keys are both named on failure. + env.write_text("SECOND=\nTHIRD=ok\n", encoding="utf-8") + p = run(root, "validate_env.py", env, template) + assert p.returncode != 0 and "FIRST" in p.stdout and "SECOND" in p.stdout + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: a runtime-added template key is dynamically required. + env.write_text("FIRST=1\nSECOND=2\nTHIRD=3\n", encoding="utf-8") + assert run(root, "validate_env.py", env, template).returncode == 0 + template.write_text(template.read_text() + "RUNTIME_NEW=ignored\n", encoding="utf-8") + p = run(root, "validate_env.py", env, template) + assert p.returncode != 0 and "RUNTIME_NEW" in p.stdout + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def stage_logs(root, numbers): + d = root / "fixture-logs" + if d.exists(): shutil.rmtree(d) + d.mkdir() + originals = {} + for n in numbers: + originals[n] = f"log-{n}\n".encode() + bytes([n % 256]) + (d / f"app.log.{n}").write_bytes(originals[n]) + return d, originals + + +def case84(candidate): + td, root = workspace(candidate) + try: + d, original = stage_logs(root, [1, 2, 4, 5, 9]) + # ENHANCED_CASE_1: exact delete/plain/gzip partition for arbitrary thresholds. + p = run(root, "rotate.py", d, "--keep", 5, "--compress-after", 2); assert p.returncode == 0, p.stdout + p.stderr + assert sorted(x.name for x in d.iterdir()) == ["app.log.1", "app.log.2", "app.log.4.gz", "app.log.5.gz"] + assert (d / "app.log.1").read_bytes() == original[1] and (d / "app.log.2").read_bytes() == original[2] + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: every gzip payload is byte-identical to its source. + assert gzip.decompress((d / "app.log.4.gz").read_bytes()) == original[4] + assert gzip.decompress((d / "app.log.5.gz").read_bytes()) == original[5] + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: fresh sparse numbers and different thresholds are scanned dynamically. + d, original = stage_logs(root, [2, 7, 11]) + p = run(root, "rotate.py", d, "--keep", 10, "--compress-after", 3); assert p.returncode == 0 + assert sorted(x.name for x in d.iterdir()) == ["app.log.2", "app.log.7.gz"] + assert (d / "app.log.2").read_bytes() == original[2] + assert gzip.decompress((d / "app.log.7.gz").read_bytes()) == original[7] + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def write_checks(path, checks, timeout=.3): + path.write_text(json.dumps({"timeout_sec": timeout, "checks": checks}), encoding="utf-8") + + +def assert_statuses(proc, expected): + ls = lines(proc) + for status in expected: + assert sum(line == status or line.startswith(status + " ") for line in ls) == 1, (status, ls) + assert len(ls) == len(expected) + 1, f"expected one status/check plus one summary: {ls}" + + +def case85(candidate): + td, root = workspace(candidate) + try: + cfg = root / "alt checks.json" + # ENHANCED_CASE_1: stdout substring alone cannot hide nonzero exit or absence. + checks = [ + {"name":"good", "command":[sys.executable,"-c","print('needle here')"], "expect_substring":"needle"}, + {"name":"missing", "command":[sys.executable,"-c","print('other')"], "expect_substring":"needle"}, + {"name":"bad-exit", "command":[sys.executable,"-c","print('needle');raise SystemExit(7)"], "expect_substring":"needle"}, + ] + write_checks(cfg, checks); p = run(root, "smoke.py", cfg) + assert p.returncode != 0; assert_statuses(p, ["PASS good", "FAIL missing", "FAIL bad-exit"]) + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: timeout is per-check and later checks still execute. + checks = [ + {"name":"slow", "command":[sys.executable,"-c","import time;time.sleep(1);print('ok')"], "expect_substring":"ok", "timeout_sec":.08}, + {"name":"after", "command":[sys.executable,"-c","print('after-ok')"], "expect_substring":"after-ok"}, + ] + write_checks(cfg, checks); started=time.monotonic(); p=run(root,"smoke.py",cfg,timeout=3) + assert time.monotonic()-started < 2 and p.returncode != 0 + assert_statuses(p, ["FAIL slow", "PASS after"]) + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: specified config produces exactly one status/check and one summary. + checks = [{"name":"punctuation name", "command":[sys.executable,"-c","print('x-y-z')"], "expect_substring":"x-y"}] + write_checks(cfg, checks); p=run(root,"smoke.py",cfg) + assert p.returncode == 0; assert_statuses(p,["PASS punctuation name"]) + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def file_snapshot(root): + return {p.relative_to(root).as_posix(): p.read_bytes() for p in root.rglob("*") if p.is_file()} + + +def case86(candidate): + td, root = workspace(candidate) + try: + history = ["1.9.0", "1.10.0", "0.5.0", "release-z"] + (root / "releases.json").write_text(json.dumps({"history":[{"version":v,"artifact":v+".tgz"} for v in history]}), encoding="utf-8") + current = root / "current.txt" + # ENHANCED_CASE_1: previous follows history position, not lexical/semantic sorting. + for old, expected in (("release-z","0.5.0"),("0.5.0","1.10.0")): + current.write_text(old+"\n"); p=run(root,"rollback.py","previous") + assert p.returncode == 0 and current.read_text().strip() == expected, p.stdout+p.stderr + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: explicit rollback updates current and appends a persistent record somewhere. + current.write_text("release-z\n"); before=file_snapshot(root); p=run(root,"rollback.py","1.9.0") + assert p.returncode == 0 and current.read_text().strip() == "1.9.0" + after=file_snapshot(root) + changed=[k for k,v in after.items() if k not in ("current.txt",) and (k not in before or len(v)>len(before[k]))] + assert changed, "successful rollback did not append a persistent record" + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: all stated invalid targets fail and preserve current bytes. + for old,arg in ((history[0],"previous"),("release-z","9.9.9"),("0.5.0","0.5.0")): + raw=(old+"\n").encode(); current.write_bytes(raw); p=run(root,"rollback.py",arg) + assert p.returncode != 0 and current.read_bytes() == raw + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def expected_asset(rel, content): + p=pathlib.PurePosixPath(rel); return str(p.with_name(f"{p.stem}.{hashlib.sha256(content).hexdigest()[:8]}{p.suffix}")) + + +def case87(candidate): + td, root = workspace(candidate) + try: + src=root/"src"; (src/"assets").mkdir(parents=True,exist_ok=True) + assets={"assets/app.js":b"console.log('edge');\n", "assets/style.css":b"body{color:#123456}\n"} + for rel,data in assets.items(): (src/rel).write_bytes(data) + (src/"index.html").write_text('',encoding="utf-8") + if (root/"dist").exists(): shutil.rmtree(root/"dist") + p=run(root,"build.py"); assert p.returncode==0,p.stdout+p.stderr + manifest=json.loads((root/"dist/manifest.json").read_text()) + expected={rel:expected_asset(rel,data) for rel,data in assets.items()} + # ENHANCED_CASE_1: independently hashed names and copied bytes match. + assert manifest == expected + for rel,hrel in expected.items(): assert (root/"dist"/hrel).read_bytes()==assets[rel] + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: HTML uses every manifest target and no original reference. + html=(root/"dist/index.html").read_text() + assert all(h in html and rel not in html for rel,h in expected.items()) + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: mutating one asset changes only its independently calculated mapping. + assets["assets/app.js"] += b"// mutation\n"; (src/"assets/app.js").write_bytes(assets["assets/app.js"]) + assert run(root,"build.py").returncode==0 + newer=json.loads((root/"dist/manifest.json").read_text()) + assert newer["assets/app.js"]==expected_asset("assets/app.js",assets["assets/app.js"]) + assert newer["assets/app.js"]!=expected["assets/app.js"] and newer["assets/style.css"]==expected["assets/style.css"] + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def record_digest(data): + return "sha256="+base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode() + + +def inspect_wheel(root,name,version): + wheels=list((root/"dist").glob("*.whl")); assert len(wheels)==1,wheels + wheel=wheels[0]; assert wheel.name==f"{name}-{version}-py3-none-any.whl" and zipfile.is_zipfile(wheel) + with zipfile.ZipFile(wheel) as z: + names=z.namelist(); required={f"{name}/__init__.py",f"{name}/ops.py",f"{name}-{version}.dist-info/METADATA",f"{name}-{version}.dist-info/WHEEL",f"{name}-{version}.dist-info/RECORD"} + assert required <= set(names) + meta=z.read(f"{name}-{version}.dist-info/METADATA").decode(); assert re.search(rf"(?m)^Name:\s*{re.escape(name)}\s*$",meta) and re.search(rf"(?m)^Version:\s*{re.escape(version)}\s*$",meta) + rows={line.split(",",2)[0]:line.split(",",2)[1:] for line in z.read(f"{name}-{version}.dist-info/RECORD").decode().splitlines()} + assert set(names) <= set(rows) + for member in names: + if member.endswith("/RECORD"): continue + assert rows[member]==[record_digest(z.read(member)),str(len(z.read(member)))] + return wheel + + +def case88(candidate): + td, root = workspace(candidate) + try: + (root/"mathkit").mkdir(exist_ok=True); (root/"mathkit/__init__.py").write_text("VALUE=1\n"); (root/"mathkit/ops.py").write_text("def add(a,b): return a+b\n") + (root/"pyproject.toml").write_text('[project]\nname="mathkit"\nversion="0.2.0"\n') + if (root/"dist").exists(): shutil.rmtree(root/"dist") + # ENHANCED_CASE_1: metadata-derived name/version and exactly one valid wheel. + assert run(root,"build_wheel.py").returncode==0; wheel=inspect_wheel(root,"mathkit","0.2.0") + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: required members and PEP 427 RECORD hashes/sizes are valid. + assert wheel.exists() + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: version mutation controls filename, dist-info, and METADATA. + (root/"pyproject.toml").write_text('[project]\nname="mathkit"\nversion="0.3.0"\n') + shutil.rmtree(root/"dist"); assert run(root,"build_wheel.py").returncode==0; inspect_wheel(root,"mathkit","0.3.0") + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +CASES={81:case81,82:case82,83:case83,84:case84,85:case85,86:case86,87:case87,88:case88} + + +def main(argv): + if len(argv)!=3 or argv[1] not in {str(x) for x in CASES}: + raise SystemExit("usage: enhanced_suite.py TASK_ID CANDIDATE_DIR") + CASES[int(argv[1])](argv[2]) + + +if __name__ == "__main__": main(sys.argv) diff --git a/task_051/tests/validate_outputs.py b/task_051/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..5140c5c0f68ad2e00a31e0c54a1a32f1812fc8f7 --- /dev/null +++ b/task_051/tests/validate_outputs.py @@ -0,0 +1,109 @@ +import pathlib +import subprocess +import sys + +root = pathlib.Path.cwd() + +def _py_sources(): + _skip = {"tests", "logs", "output", "__pycache__", "node_modules", ".git"} + return [p for p in root.rglob("*.py") + if not (set(p.relative_to(root).parts) & _skip) + and p.name != "validate_outputs.py"] + + +# locate the validator (allow common names; must read the template + report missing/empty) +candidates = [p for p in _py_sources() if "env" in p.name.lower() and "valid" in p.name.lower()] +if not candidates: + candidates = [p for p in _py_sources() if ".env.example" in p.read_text(encoding="utf-8", errors="ignore")] +assert candidates, "missing env validator (e.g. validate_env.py)" +tool = candidates[0] + +src = tool.read_text(encoding="utf-8", errors="ignore").lower() + +template = root / ".env.example" +assert template.exists(), "missing .env.example template" + +# independently parse the template to learn the required key set (anti-hardcode reference) +def parse_keys(text): + keys = [] + for raw in text.splitlines(): + line = raw.strip() + if not line or line.startswith("#") or "=" not in line: + continue + k = line.partition("=")[0].strip() + if k: + keys.append(k) + return keys + +required = parse_keys(template.read_text(encoding="utf-8")) +assert len(required) >= 3, f"expected at least 3 required keys in template, got {required}" + + +def run(env_file): + return subprocess.run( + [sys.executable, str(tool), str(env_file)], + cwd=root, capture_output=True, text=True, timeout=30, + ) + + +tmp_files = [] + + +def write_env(name, lines): + p = root / name + p.write_text("\n".join(lines) + "\n", encoding="utf-8") + tmp_files.append(p) + return p + + +try: + # --- incomplete env: drop one required key, leave one with empty value --- + missing_key = required[0] + empty_key = required[1] + lines = [] + for k in required: + if k == missing_key: + continue # omit entirely -> MISSING + if k == empty_key: + lines.append(f"{k}=") # present but empty -> EMPTY + else: + lines.append(f"{k}=somevalue_{k.lower()}") + bad = write_env(".env", lines) + rb = run(bad) + assert rb.returncode != 0, f"incomplete env should fail (nonzero):\n{rb.stdout}\n{rb.stderr}" + assert missing_key in rb.stdout, f"missing key '{missing_key}' not reported:\n{rb.stdout}" + assert empty_key in rb.stdout, f"empty key '{empty_key}' not reported:\n{rb.stdout}" + + # --- complete env: every required key present and non-empty --- + good_lines = [f"{k}=val_{k.lower()}" for k in required] + good = write_env(".env.good", good_lines) + rg = run(good) + assert rg.returncode == 0, f"complete env should pass (exit 0):\n{rg.stdout}\n{rg.stderr}" + + # --- anti-hardcode: append a NEW required key to the template, omit it from a complete env --- + new_key = "RUNTIME_INJECTED_KEY" + original_template = template.read_text(encoding="utf-8") + template.write_text(original_template + f"{new_key}=\n", encoding="utf-8") + try: + # this env satisfies the ORIGINAL keys but not the newly added one + partial = write_env(".env.partial", [f"{k}=val_{k.lower()}" for k in required]) + rp = run(partial) + assert rp.returncode != 0, ( + "validator did not flag a newly added template key (expected nonzero); " + f"it may hardcode the required set:\n{rp.stdout}\n{rp.stderr}" + ) + assert new_key in rp.stdout, ( + f"newly added required key '{new_key}' not reported -> validator hardcodes keys:\n{rp.stdout}" + ) + # and an env that DOES include the new key passes + full = write_env(".env.full", [f"{k}=val_{k.lower()}" for k in required] + [f"{new_key}=present"]) + rf = run(full) + assert rf.returncode == 0, f"env including the new key should pass:\n{rf.stdout}\n{rf.stderr}" + finally: + template.write_text(original_template, encoding="utf-8") +finally: + for p in tmp_files: + if p.exists(): + p.unlink() + +print("validate_outputs OK: task_083 env validator derives required keys dynamically and flags missing/empty") diff --git a/task_052/acceptance_checklist.json b/task_052/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..b8c7cbd49b0770a107e143fdbbf7dfb1a262d0bc --- /dev/null +++ b/task_052/acceptance_checklist.json @@ -0,0 +1,27 @@ +{ + "task_id": 84, + "category": "build_deployment", + "language": "python", + "acceptance_items": [ + "rotate logs --keep 4 --compress-after 2 deletes app.log.5 and app.log.6.", + "app.log.1 and app.log.2 remain uncompressed with original content.", + "app.log.3 and app.log.4 become app.log.3.gz/.4.gz whose decompressed bytes equal the originals.", + "A different threshold set (keep=5, compress-after=1) yields the corresponding delete/compress result (thresholds not hardcoded).", + "Uses only the Python standard library; runs without internet.", + "Python files compile.", + "Sparse and repeated rotation, gzip byte identity, threshold reversal and unrelated paths." + ], + "input_assets": [ + "logs/app.log.1..6" + ], + "expected_outputs": [ + "rotate.py" + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "risk_notes": [ + "Verifier mutates logs/; it captures pristine bytes first and re-stages them at the end so it is repeatable.", + "Two threshold combinations defeat hardcoded keep/compress-after handling." + ], + "repair_revision": "2026-09-29", + "review_revision": "2026-10-07" +} diff --git a/task_052/environment/Dockerfile b/task_052/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2bd34b80ad954f5177a9066cedb797e932ed68ae --- /dev/null +++ b/task_052/environment/Dockerfile @@ -0,0 +1,4 @@ +# syntax=docker/dockerfile:1.7-labs +FROM python:3.12-slim@sha256:090ba77e2958f6af52a5341f788b50b032dd4ca28377d2893dcf1ecbdfdfe203 +WORKDIR /app +COPY ./code /app diff --git a/task_052/environment/code/README.md b/task_052/environment/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ae604ce91d8ba481a4e3fa3c3963a51263f99048 --- /dev/null +++ b/task_052/environment/code/README.md @@ -0,0 +1,15 @@ +# Log rotation tool starter + +The `logs/` directory contains numbered log files `app.log.1` .. `app.log.6`, +where `N=1` is the newest and each file has distinct content. + +Implement `rotate.py --keep K --compress-after C` so that it: + +- deletes every log whose `N > K` (retention), +- among the kept logs (`N <= K`), gzip-compresses those with `N > C` to + `app.log.N.gz` (removing the uncompressed original) and leaves logs with + `N <= C` uncompressed. + +Use the stdlib `gzip` module; the decompressed bytes of each `.gz` must equal the +original log content. Discover the log files dynamically by name. Standard library +only. diff --git a/task_052/environment/code/logs/app.log.1 b/task_052/environment/code/logs/app.log.1 new file mode 100644 index 0000000000000000000000000000000000000000..9e7a373a229a8ac05e174414b605c8091eaa02f9 --- /dev/null +++ b/task_052/environment/code/logs/app.log.1 @@ -0,0 +1 @@ +Original log 1: startup completed. diff --git a/task_052/environment/code/logs/app.log.2 b/task_052/environment/code/logs/app.log.2 new file mode 100644 index 0000000000000000000000000000000000000000..0c13fa92de31898697d71936a256431992e6554c --- /dev/null +++ b/task_052/environment/code/logs/app.log.2 @@ -0,0 +1 @@ +Original log 2: request accepted. diff --git a/task_052/environment/code/logs/app.log.3 b/task_052/environment/code/logs/app.log.3 new file mode 100644 index 0000000000000000000000000000000000000000..ae82d5f552df92e6217a0ccc6f92bf1c2a92c819 --- /dev/null +++ b/task_052/environment/code/logs/app.log.3 @@ -0,0 +1 @@ +Original log 3: worker connected. diff --git a/task_052/environment/code/logs/app.log.4 b/task_052/environment/code/logs/app.log.4 new file mode 100644 index 0000000000000000000000000000000000000000..b904fed48ab7473afcf82dc5c952985e6352d0d4 --- /dev/null +++ b/task_052/environment/code/logs/app.log.4 @@ -0,0 +1 @@ +Original log 4: retry succeeded. diff --git a/task_052/environment/code/logs/app.log.5 b/task_052/environment/code/logs/app.log.5 new file mode 100644 index 0000000000000000000000000000000000000000..3bc9b17400579b09019e6874284ab6b5d6c3c2ea --- /dev/null +++ b/task_052/environment/code/logs/app.log.5 @@ -0,0 +1 @@ +Original log 5: checkpoint written. diff --git a/task_052/environment/code/logs/app.log.6 b/task_052/environment/code/logs/app.log.6 new file mode 100644 index 0000000000000000000000000000000000000000..03323f976e3f5c0758e089d30537d50e4675cc3e --- /dev/null +++ b/task_052/environment/code/logs/app.log.6 @@ -0,0 +1 @@ +Original log 6: shutdown completed. diff --git a/task_052/environment/docker-compose.yaml b/task_052/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_052/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_052/instruction.md b/task_052/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5db1e37f635cf40f8f3aee170f19cce5a4a60f07 --- /dev/null +++ b/task_052/instruction.md @@ -0,0 +1,15 @@ +# Rotate numbered logs with lossless gzip compression + +Implement `python3 rotate.py LOGDIR --keep K --compress-after C` using only the Python standard library, including `gzip`. The starter's `logs/` directory holds sample numbered logs. + +## Requirements + +Process only ordinary files directly inside `LOGDIR` whose entire names match `app.log.N` or `app.log.N.gz`, with positive integer `N` (1 is newest). Numbering can be sparse. There is at most one input form per number. Do not renumber logs or touch unrelated paths, directories or nested files. + +## Acceptance Checklist + +- Remove both plaintext or compressed entries whose number exceeds `K`. +- Among retained logs, use gzip when `N > C` and plaintext when `N <= C`. Convert existing entries in either direction as needed, removing the original form so only the target form remains. +- Preserve binary contents exactly after compression or decompression. Keep already-correct files without changing their contents. +- Read the live directory and use the supplied thresholds, not the sample file list. Repeating the same run preserves the resulting layout, and changing the threshold can restore a previously compressed file to plaintext. +- Leave misleading names (such as backups) and subdirectory contents untouched; succeed for valid inputs without network access. diff --git a/task_052/quality_notes.md b/task_052/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..1ecb9c47e1a27065cefe5279d413f5b2ee711f6e --- /dev/null +++ b/task_052/quality_notes.md @@ -0,0 +1,12 @@ +# Quality notes — task_084 + +- Closed/self-contained: pure Python stdlib (`gzip`, `pathlib`, `argparse`), no + network, no extra deps. +- Discrimination: a tool that ignores `--keep`/`--compress-after` (hardcoded + thresholds) fails the second knob-set check; one that "compresses" without real + gzip fails the decompress-equals-original byte comparison; one that deletes the + wrong files fails the exact remaining-file-set assertion. +- Verifier captures original log bytes before running, recomputes the expected + delete/keep/compress sets for two threshold combinations, and decompresses each + `.gz` to compare against the originals, rather than grepping source. Pristine + fixtures are re-staged at the end so the verifier is repeatable. diff --git a/task_052/solution/README.md b/task_052/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4d4ee1815192cd7a1aaf6af17b6aeeeea1513731 --- /dev/null +++ b/task_052/solution/README.md @@ -0,0 +1,8 @@ +# Reference solution — task_084 + +`rotate.py` rotates numbered `app.log.N` files in a log directory. It discovers +the files by name, deletes those with `N > keep`, gzip-compresses kept files with +`N > compress_after` to `app.log.N.gz` (removing the original), and leaves files +with `N <= compress_after` uncompressed. Compression uses the stdlib `gzip` module +so the decompressed bytes equal the original content. The scan is dynamic and the +operation is safe to re-run. diff --git a/task_052/solution/code/rotate.py b/task_052/solution/code/rotate.py new file mode 100644 index 0000000000000000000000000000000000000000..4e889c47f20afdac5f392ab3660fdc6eacd99fae --- /dev/null +++ b/task_052/solution/code/rotate.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +"""Log rotation tool. + +Usage: + python rotate.py --keep K --compress-after C + +Operates on numbered log files `app.log.N` in where N=1 is the newest. + + - Delete every log whose N > K (retention). + - Among the kept logs (N <= K), gzip-compress those with N > C to + `app.log.N.gz` (removing the uncompressed original), and leave logs with + N <= C uncompressed. + +Uses the stdlib `gzip` module. Already-compressed `app.log.N.gz` files are taken +into account so the tool is safe to run repeatedly. +""" +import argparse +import gzip +import pathlib +import re +import sys + +NAME_RE = re.compile(r"^app\.log\.(\d+)(\.gz)?$") + + +def discover(logdir): + """Return list of (N, path, is_gz) for app.log.N[.gz] files in logdir.""" + out = [] + for p in sorted(pathlib.Path(logdir).iterdir()): + if not p.is_file(): + continue + m = NAME_RE.match(p.name) + if not m: + continue + out.append((int(m.group(1)), p, bool(m.group(2)))) + return out + + +def gzip_file(src, dst): + data = src.read_bytes() + with gzip.open(dst, "wb") as fh: + fh.write(data) + src.unlink() + + +def rotate(logdir, keep, compress_after): + logdir = pathlib.Path(logdir) + deleted, compressed, kept = [], [], [] + for n, path, is_gz in discover(logdir): + if n > keep: + path.unlink() + deleted.append(path.name) + continue + if n > compress_after: + if is_gz: + kept.append(path.name) # already compressed + else: + gz = logdir / f"app.log.{n}.gz" + gzip_file(path, gz) + compressed.append(gz.name) + else: + # must stay uncompressed; if a stale .gz exists, decompress it back + if is_gz: + raw = logdir / f"app.log.{n}" + raw.write_bytes(gzip.decompress(path.read_bytes())) + path.unlink() + kept.append(raw.name) + else: + kept.append(path.name) + return deleted, compressed, kept + + +def main(argv): + parser = argparse.ArgumentParser(description="rotate numbered app.log files") + parser.add_argument("logdir") + parser.add_argument("--keep", type=int, required=True) + parser.add_argument("--compress-after", type=int, required=True) + args = parser.parse_args(argv[1:]) + + deleted, compressed, kept = rotate(args.logdir, args.keep, args.compress_after) + print(f"deleted={sorted(deleted)} compressed={sorted(compressed)} kept={sorted(kept)}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/task_052/solution/solve.sh b/task_052/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_052/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_052/task.toml b/task_052/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_052/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_052/task_meta.json b/task_052/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..a0b678e270cae959048cdb061d293a3c6fb32e48 --- /dev/null +++ b/task_052/task_meta.json @@ -0,0 +1,22 @@ +{ + "task_id": 84, + "task_category": "build_deployment", + "origin_model": "authored", + "sample_count": 0, + "user_turns": 0, + "language": "python", + "input_assets": [ + "logs/app.log.1", + "logs/app.log.2", + "logs/app.log.3", + "logs/app.log.4", + "logs/app.log.5", + "logs/app.log.6" + ], + "expected_outputs": [ + "rotate.py" + ], + "source_row_id": null, + "repair_revision": "2026-09-29", + "instruction_sha256": "b5a6067056f16f38c8af86a34cc8948807876f78e1668c9c2926e1575f91e12b" +} diff --git a/task_052/tests/_shared/contract_checker.js b/task_052/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_052/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_052/tests/_shared/static_enhancer.sh b/task_052/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_052/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_052/tests/enhancement_cases.json b/task_052/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..e05d7a18cad131c921a10e716c1c43aac8ae463f --- /dev/null +++ b/task_052/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +{ + "task_id": "task_084", + "cases": [ + { + "id": "ENHANCED_CASE_1", + "instruction_evidence": "N>K删除;N<=C保留;C/dev/null; then LOG_DIR="logs/verifier"; mkdir -p "$LOG_DIR"; fi +REWARD_FILE="$LOG_DIR/reward.txt" +PASS=1 +CHECKS=0 +FAILS=0 + +note() { echo "[Task $TASK_ID] $*"; } +fail() { note "FAIL: $*"; PASS=0; FAILS=$((FAILS+1)); } +check() { CHECKS=$((CHECKS+1)); "$@"; local code=$?; if [ $code -ne 0 ]; then fail "$*"; fi; } +have_any() { local pattern="$1"; compgen -G "$pattern" >/dev/null 2>&1; } +grep_any() { local pattern="$1"; shift; grep -REiq -- "$pattern" "$@" 2>/dev/null; } +source_files() { find . -type f \( -name '*.html' -o -name '*.js' -o -name '*.jsx' -o -name '*.ts' -o -name '*.tsx' -o -name '*.css' -o -name '*.py' -o -name '*.go' -o -name '*.swift' -o -name '*.svg' \) ! -path './tests/*' ! -path './logs/*'; } + +note "enhanced deterministic verifier start" +static_enhance_check "${TASK_ID}" "$(pwd)" +mapfile -t py_files < <(find . -type f -name '*.py' ! -path './tests/*') +if [ ${#py_files[@]} -eq 0 ]; then fail "no Python source found"; fi +if command -v python3 >/dev/null 2>&1; then + for f in "${py_files[@]}"; do python3 -m py_compile "$f" >/tmp/harbor_py_compile.log 2>&1 || fail "python compile failed: $f"; done +fi + +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +if command -v python3 >/dev/null 2>&1; then + check python3 "$TEST_DIR/validate_outputs.py" +else + fail "python3 unavailable for output validation" +fi +# BEGIN ENHANCED_CASES_081_088 +if command -v python3 >/dev/null 2>&1; then + check python3 "$TEST_DIR/validate_enhanced.py" 84 "$(pwd)" +else + fail "python3 unavailable for enhanced validation" +fi +# END ENHANCED_CASES_081_088 +# BEGIN AAAV_DYNAMIC_TEST +if [ -f "$TEST_DIR/validate_aaav_dynamic.js" ]; then + if command -v node >/dev/null 2>&1; then + check node "$TEST_DIR/validate_aaav_dynamic.js" + else + note "AAAV dynamic validation skipped (node unavailable in this runtime)" + fi +fi +# END AAAV_DYNAMIC_TEST +note "checks=$CHECKS fails=$FAILS" +if [ "$PASS" -eq 1 ]; then + echo 1 > "$REWARD_FILE" + note "PASS" + exit 0 +fi +echo 0 > "$REWARD_FILE" +note "FAIL" +exit 0 diff --git a/task_052/tests/test.sh b/task_052/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56b0776f3ccad7f2da017c3b6e7cd69a9a1454e6 --- /dev/null +++ b/task_052/tests/test.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -uo pipefail +bash /tests/review_legacy.sh +CORE=$(cat /logs/verifier/reward.txt 2>/dev/null || echo 0) +mkdir -p /logs/verifier +python3 /tests/review_hard.py /app 2>&1 | tee /logs/verifier/review_hard.log +RC=${PIPESTATUS[0]} +if [ "$RC" -ne 0 ]; then echo "REVIEW_HARD failed with exit code $RC"; fi +if [ "$RC" -eq 0 ]; then echo "$CORE"; else echo 0; fi > /logs/verifier/reward.txt +exit 0 diff --git a/task_052/tests/validate_aaav_dynamic.js b/task_052/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..76a97cfbe4e21518a3edcd3bbf9810126a385334 --- /dev/null +++ b/task_052/tests/validate_aaav_dynamic.js @@ -0,0 +1,27 @@ +const fs = require('fs'); +const path = require('path'); +const child_process = require('child_process'); +const TASK_ID = 84; +const LANGUAGE = "python"; +const EXPECTED = []; +const SKIP_DIRS = new Set(["tests","logs","node_modules",".git"]); +function assert(condition, message) { if (!condition) throw new Error(message); } +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} +const files = walk(process.cwd()); +assert(files.length > 0, 'candidate workspace should contain files'); +const source = files.filter(f => /\.(js|jsx|ts|tsx|css|html|py|go|md|svg)$/i.test(f)); +assert(source.length > 0, 'candidate should contain source or report files'); +const pyFiles = files.filter(f => f.endsWith('.py')); +for (const f of pyFiles.slice(0, 20)) { + child_process.execFileSync('python3', ['-m', 'py_compile', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); +} +console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); diff --git a/task_052/tests/validate_enhanced.py b/task_052/tests/validate_enhanced.py new file mode 100644 index 0000000000000000000000000000000000000000..3af5a20ddee270b10c5649f5f73170c634c7c262 --- /dev/null +++ b/task_052/tests/validate_enhanced.py @@ -0,0 +1,341 @@ +#!/usr/bin/env python3 +import base64 +import gzip +import hashlib +import json +import os +import pathlib +import re +import shutil +import subprocess +import sys +import tempfile +import time +import zipfile + +TIMEOUT = 8 + + +def run(root, script, *args, timeout=TIMEOUT): + env = os.environ.copy() + for key in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"): + env.pop(key, None) + env["PYTHONHASHSEED"] = "0" + return subprocess.run( + [sys.executable, str(root / script), *map(str, args)], cwd=root, + text=True, capture_output=True, timeout=timeout, env=env, + ) + + +def workspace(candidate): + td = tempfile.TemporaryDirectory(prefix="glm-enhanced-") + root = pathlib.Path(td.name) / "code" + shutil.copytree(pathlib.Path(candidate).resolve(), root) + return td, root + + +def lines(proc): + return [x.strip() for x in proc.stdout.splitlines() if x.strip()] + + +def exact_actions(proc, expected): + assert proc.returncode == 0, proc.stdout + proc.stderr + assert lines(proc) == expected, f"status lines {lines(proc)!r} != {expected!r}" + + +def case81(candidate): + td, root = workspace(candidate) + try: + (root / "src/deep").mkdir(parents=True, exist_ok=True) + data = { + "targets": [ + {"name": "alpha-x", "inputs": ["src/a.txt", "src/deep/b.txt"], "output": "out/deep/a.bin"}, + {"name": "beta_9", "inputs": ["src/c.txt"], "output": "out/b.txt"}, + {"name": "empty", "inputs": [], "output": "out/empty.txt"}, + ] + } + (root / "build.json").write_text(json.dumps(data), encoding="utf-8") + (root / "src/a.txt").write_bytes(b"A\nA") + (root / "src/deep/b.txt").write_bytes(b"B\x00B") + (root / "src/c.txt").write_bytes(b"C") + for p in (root / ".buildcache.json", root / "out"): + if p.is_dir(): shutil.rmtree(p) + elif p.exists(): p.unlink() + # ENHANCED_CASE_1: every declared target builds with exact ordered bytes. + p1 = run(root, "builder.py") + exact_actions(p1, ["BUILD alpha-x", "BUILD beta_9", "BUILD empty"]) + assert (root / "out/deep/a.bin").read_bytes() == b"A\nA\nB\x00B" + assert (root / "out/b.txt").read_bytes() == b"C" + assert (root / "out/empty.txt").read_bytes() == b"" + print("ENHANCED_CASE_1 PASS") + mtimes = {p: (root / p).stat().st_mtime_ns for p in ("out/deep/a.bin", "out/b.txt", "out/empty.txt")} + time.sleep(0.02) + # ENHANCED_CASE_2: unchanged inputs and existing outputs are skipped and untouched. + p2 = run(root, "builder.py") + exact_actions(p2, ["SKIP alpha-x", "SKIP beta_9", "SKIP empty"]) + assert mtimes == {p: (root / p).stat().st_mtime_ns for p in mtimes} + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: one target's content mutation invalidates only that target. + (root / "src/deep/b.txt").write_bytes(b"changed") + p3 = run(root, "builder.py") + exact_actions(p3, ["BUILD alpha-x", "SKIP beta_9", "SKIP empty"]) + assert (root / "out/deep/a.bin").read_bytes() == b"A\nA\nchanged" + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def manifest_oracle(dist): + return {p.relative_to(dist).as_posix(): {"sha256": hashlib.sha256(p.read_bytes()).hexdigest(), "size": p.stat().st_size} + for p in sorted(dist.rglob("*")) if p.is_file()} + + +def case82(candidate): + td, root = workspace(candidate) + try: + dist = root / "payload"; (dist / "a/b").mkdir(parents=True, exist_ok=True) + (dist / "zero").write_bytes(b""); (dist / "a/b/data.bin").write_bytes(b"\x00\xffx"); (dist / "sp ace.txt").write_bytes(b"hello") + mf = root / "custom-manifest.json" + # ENHANCED_CASE_1: recursive POSIX keys, SHA256 and byte sizes exactly match. + g = run(root, "manifest.py", "generate", dist, mf); assert g.returncode == 0, g.stdout + g.stderr + assert json.loads(mf.read_text()) == manifest_oracle(dist) + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: clean passes; changed, missing, and extra files fail and identify paths. + assert run(root, "manifest.py", "verify", dist, mf).returncode == 0 + target = dist / "a/b/data.bin"; original = target.read_bytes() + for mode, name in (("changed", "a/b/data.bin"), ("missing", "a/b/data.bin"), ("extra", "surprise.new")): + if mode == "changed": target.write_bytes(b"different") + elif mode == "missing": target.unlink() + else: (dist / name).write_bytes(b"extra") + p = run(root, "manifest.py", "verify", dist, mf) + assert p.returncode != 0 and name in p.stdout + p.stderr, (mode, p.stdout, p.stderr) + if mode in ("changed", "missing"): target.write_bytes(original) + else: (dist / name).unlink() + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: newly added nested files appear after regeneration. + (dist / "a/new/deeper").mkdir(parents=True); (dist / "a/new/deeper/z").write_bytes(b"z") + assert run(root, "manifest.py", "generate", dist, mf).returncode == 0 + assert json.loads(mf.read_text()) == manifest_oracle(dist) + assert run(root, "manifest.py", "verify", dist, mf).returncode == 0 + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def case83(candidate): + td, root = workspace(candidate) + try: + template = root / "custom.example" + template.write_text("# ignored\n\n BAD LINE\n FIRST = ignored\nSECOND=template-value\nTHIRD=\n", encoding="utf-8") + env = root / "candidate.env" + # ENHANCED_CASE_1: only valid left-hand template keys are requirements. + env.write_text("FIRST=one\nSECOND=two\nTHIRD=three\n", encoding="utf-8") + p = run(root, "validate_env.py", env, template); assert p.returncode == 0, p.stdout + p.stderr + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: missing and empty keys are both named on failure. + env.write_text("SECOND=\nTHIRD=ok\n", encoding="utf-8") + p = run(root, "validate_env.py", env, template) + assert p.returncode != 0 and "FIRST" in p.stdout and "SECOND" in p.stdout + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: a runtime-added template key is dynamically required. + env.write_text("FIRST=1\nSECOND=2\nTHIRD=3\n", encoding="utf-8") + assert run(root, "validate_env.py", env, template).returncode == 0 + template.write_text(template.read_text() + "RUNTIME_NEW=ignored\n", encoding="utf-8") + p = run(root, "validate_env.py", env, template) + assert p.returncode != 0 and "RUNTIME_NEW" in p.stdout + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def stage_logs(root, numbers): + d = root / "fixture-logs" + if d.exists(): shutil.rmtree(d) + d.mkdir() + originals = {} + for n in numbers: + originals[n] = f"log-{n}\n".encode() + bytes([n % 256]) + (d / f"app.log.{n}").write_bytes(originals[n]) + return d, originals + + +def case84(candidate): + td, root = workspace(candidate) + try: + d, original = stage_logs(root, [1, 2, 4, 5, 9]) + # ENHANCED_CASE_1: exact delete/plain/gzip partition for arbitrary thresholds. + p = run(root, "rotate.py", d, "--keep", 5, "--compress-after", 2); assert p.returncode == 0, p.stdout + p.stderr + assert sorted(x.name for x in d.iterdir()) == ["app.log.1", "app.log.2", "app.log.4.gz", "app.log.5.gz"] + assert (d / "app.log.1").read_bytes() == original[1] and (d / "app.log.2").read_bytes() == original[2] + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: every gzip payload is byte-identical to its source. + assert gzip.decompress((d / "app.log.4.gz").read_bytes()) == original[4] + assert gzip.decompress((d / "app.log.5.gz").read_bytes()) == original[5] + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: fresh sparse numbers and different thresholds are scanned dynamically. + d, original = stage_logs(root, [2, 7, 11]) + p = run(root, "rotate.py", d, "--keep", 10, "--compress-after", 3); assert p.returncode == 0 + assert sorted(x.name for x in d.iterdir()) == ["app.log.2", "app.log.7.gz"] + assert (d / "app.log.2").read_bytes() == original[2] + assert gzip.decompress((d / "app.log.7.gz").read_bytes()) == original[7] + print("ENHANCED_CASE_3 PASS") + # ENHANCED_CASE_4: rerun is stable; moving the threshold restores low-numbered plain bytes. + before = {p.name: p.read_bytes() for p in d.iterdir()} + assert run(root, "rotate.py", d, "--keep", 10, "--compress-after", 3).returncode == 0 + assert {p.name: p.read_bytes() for p in d.iterdir()} == before + assert run(root, "rotate.py", d, "--keep", 10, "--compress-after", 7).returncode == 0 + assert (d / "app.log.7").read_bytes() == original[7] + assert not (d / "app.log.7.gz").exists() + print("ENHANCED_CASE_4 PASS") + finally: td.cleanup() + + +def write_checks(path, checks, timeout=.3): + path.write_text(json.dumps({"timeout_sec": timeout, "checks": checks}), encoding="utf-8") + + +def assert_statuses(proc, expected): + ls = lines(proc) + for status in expected: + assert sum(line == status or line.startswith(status + " ") for line in ls) == 1, (status, ls) + assert len(ls) == len(expected) + 1, f"expected one status/check plus one summary: {ls}" + + +def case85(candidate): + td, root = workspace(candidate) + try: + cfg = root / "alt checks.json" + # ENHANCED_CASE_1: stdout substring alone cannot hide nonzero exit or absence. + checks = [ + {"name":"good", "command":[sys.executable,"-c","print('needle here')"], "expect_substring":"needle"}, + {"name":"missing", "command":[sys.executable,"-c","print('other')"], "expect_substring":"needle"}, + {"name":"bad-exit", "command":[sys.executable,"-c","print('needle');raise SystemExit(7)"], "expect_substring":"needle"}, + ] + write_checks(cfg, checks); p = run(root, "smoke.py", cfg) + assert p.returncode != 0; assert_statuses(p, ["PASS good", "FAIL missing", "FAIL bad-exit"]) + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: timeout is per-check and later checks still execute. + checks = [ + {"name":"slow", "command":[sys.executable,"-c","import time;time.sleep(1);print('ok')"], "expect_substring":"ok", "timeout_sec":.08}, + {"name":"after", "command":[sys.executable,"-c","print('after-ok')"], "expect_substring":"after-ok"}, + ] + write_checks(cfg, checks); started=time.monotonic(); p=run(root,"smoke.py",cfg,timeout=3) + assert time.monotonic()-started < 2 and p.returncode != 0 + assert_statuses(p, ["FAIL slow", "PASS after"]) + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: specified config produces exactly one status/check and one summary. + checks = [{"name":"punctuation name", "command":[sys.executable,"-c","print('x-y-z')"], "expect_substring":"x-y"}] + write_checks(cfg, checks); p=run(root,"smoke.py",cfg) + assert p.returncode == 0; assert_statuses(p,["PASS punctuation name"]) + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def file_snapshot(root): + return {p.relative_to(root).as_posix(): p.read_bytes() for p in root.rglob("*") if p.is_file()} + + +def case86(candidate): + td, root = workspace(candidate) + try: + history = ["1.9.0", "1.10.0", "0.5.0", "release-z"] + (root / "releases.json").write_text(json.dumps({"history":[{"version":v,"artifact":v+".tgz"} for v in history]}), encoding="utf-8") + current = root / "current.txt" + # ENHANCED_CASE_1: previous follows history position, not lexical/semantic sorting. + for old, expected in (("release-z","0.5.0"),("0.5.0","1.10.0")): + current.write_text(old+"\n"); p=run(root,"rollback.py","previous") + assert p.returncode == 0 and current.read_text().strip() == expected, p.stdout+p.stderr + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: explicit rollback updates current and appends a persistent record somewhere. + current.write_text("release-z\n"); before=file_snapshot(root); p=run(root,"rollback.py","1.9.0") + assert p.returncode == 0 and current.read_text().strip() == "1.9.0" + after=file_snapshot(root) + changed=[k for k,v in after.items() if k not in ("current.txt",) and (k not in before or len(v)>len(before[k]))] + assert changed, "successful rollback did not append a persistent record" + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: all stated invalid targets fail and preserve current bytes. + for old,arg in ((history[0],"previous"),("release-z","9.9.9"),("0.5.0","0.5.0")): + raw=(old+"\n").encode(); current.write_bytes(raw); p=run(root,"rollback.py",arg) + assert p.returncode != 0 and current.read_bytes() == raw + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def expected_asset(rel, content): + p=pathlib.PurePosixPath(rel); return str(p.with_name(f"{p.stem}.{hashlib.sha256(content).hexdigest()[:8]}{p.suffix}")) + + +def case87(candidate): + td, root = workspace(candidate) + try: + src=root/"src"; (src/"assets").mkdir(parents=True,exist_ok=True) + assets={"assets/app.js":b"console.log('edge');\n", "assets/style.css":b"body{color:#123456}\n"} + for rel,data in assets.items(): (src/rel).write_bytes(data) + (src/"index.html").write_text('',encoding="utf-8") + if (root/"dist").exists(): shutil.rmtree(root/"dist") + p=run(root,"build.py"); assert p.returncode==0,p.stdout+p.stderr + manifest=json.loads((root/"dist/manifest.json").read_text()) + expected={rel:expected_asset(rel,data) for rel,data in assets.items()} + # ENHANCED_CASE_1: independently hashed names and copied bytes match. + assert manifest == expected + for rel,hrel in expected.items(): assert (root/"dist"/hrel).read_bytes()==assets[rel] + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: HTML uses every manifest target and no original reference. + html=(root/"dist/index.html").read_text() + assert all(h in html and rel not in html for rel,h in expected.items()) + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: mutating one asset changes only its independently calculated mapping. + assets["assets/app.js"] += b"// mutation\n"; (src/"assets/app.js").write_bytes(assets["assets/app.js"]) + assert run(root,"build.py").returncode==0 + newer=json.loads((root/"dist/manifest.json").read_text()) + assert newer["assets/app.js"]==expected_asset("assets/app.js",assets["assets/app.js"]) + assert newer["assets/app.js"]!=expected["assets/app.js"] and newer["assets/style.css"]==expected["assets/style.css"] + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def record_digest(data): + return "sha256="+base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode() + + +def inspect_wheel(root,name,version): + wheels=list((root/"dist").glob("*.whl")); assert len(wheels)==1,wheels + wheel=wheels[0]; assert wheel.name==f"{name}-{version}-py3-none-any.whl" and zipfile.is_zipfile(wheel) + with zipfile.ZipFile(wheel) as z: + names=z.namelist(); required={f"{name}/__init__.py",f"{name}/ops.py",f"{name}-{version}.dist-info/METADATA",f"{name}-{version}.dist-info/WHEEL",f"{name}-{version}.dist-info/RECORD"} + assert required <= set(names) + meta=z.read(f"{name}-{version}.dist-info/METADATA").decode(); assert re.search(rf"(?m)^Name:\s*{re.escape(name)}\s*$",meta) and re.search(rf"(?m)^Version:\s*{re.escape(version)}\s*$",meta) + rows={line.split(",",2)[0]:line.split(",",2)[1:] for line in z.read(f"{name}-{version}.dist-info/RECORD").decode().splitlines()} + assert set(names) <= set(rows) + for member in names: + if member.endswith("/RECORD"): continue + assert rows[member]==[record_digest(z.read(member)),str(len(z.read(member)))] + return wheel + + +def case88(candidate): + td, root = workspace(candidate) + try: + (root/"mathkit").mkdir(exist_ok=True); (root/"mathkit/__init__.py").write_text("VALUE=1\n"); (root/"mathkit/ops.py").write_text("def add(a,b): return a+b\n") + (root/"pyproject.toml").write_text('[project]\nname="mathkit"\nversion="0.2.0"\n') + if (root/"dist").exists(): shutil.rmtree(root/"dist") + # ENHANCED_CASE_1: metadata-derived name/version and exactly one valid wheel. + assert run(root,"build_wheel.py").returncode==0; wheel=inspect_wheel(root,"mathkit","0.2.0") + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: required members and PEP 427 RECORD hashes/sizes are valid. + assert wheel.exists() + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: version mutation controls filename, dist-info, and METADATA. + (root/"pyproject.toml").write_text('[project]\nname="mathkit"\nversion="0.3.0"\n') + shutil.rmtree(root/"dist"); assert run(root,"build_wheel.py").returncode==0; inspect_wheel(root,"mathkit","0.3.0") + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +CASES={81:case81,82:case82,83:case83,84:case84,85:case85,86:case86,87:case87,88:case88} + + +def main(argv): + if len(argv)!=3 or argv[1] not in {str(x) for x in CASES}: + raise SystemExit("usage: enhanced_suite.py TASK_ID CANDIDATE_DIR") + CASES[int(argv[1])](argv[2]) + + +if __name__ == "__main__": main(sys.argv) diff --git a/task_052/tests/validate_outputs.py b/task_052/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..accc0b77c903d62b7d1df5afd85faf761632375f --- /dev/null +++ b/task_052/tests/validate_outputs.py @@ -0,0 +1,108 @@ +import gzip +import pathlib +import subprocess +import sys + +root = pathlib.Path.cwd() + +def _py_sources(): + _skip = {"tests", "logs", "output", "__pycache__", "node_modules", ".git"} + return [p for p in root.rglob("*.py") + if not (set(p.relative_to(root).parts) & _skip) + and p.name != "validate_outputs.py"] + + +# locate the rotation tool (allow common names; must use gzip + scan logdir) +candidates = [p for p in _py_sources() if "rotate" in p.name.lower()] +if not candidates: + candidates = [ + p for p in _py_sources() + if "gzip" in p.read_text(encoding="utf-8", errors="ignore").lower() + and "app.log" in p.read_text(encoding="utf-8", errors="ignore").lower() + ] +assert candidates, "missing rotation tool (e.g. rotate.py)" +tool = candidates[0] + + +logdir = root / "logs" +if not logdir.exists(): + logdir.mkdir(parents=True) + for fixture_n in range(1, 7): + (logdir / f"app.log.{fixture_n}").write_bytes( + f"deterministic fixture log {fixture_n}\n".encode("utf-8") + ) + +# --- capture pristine originals (so we can recompute and re-stage) --- +ORIGINALS = {} +for n in range(1, 7): + f = logdir / f"app.log.{n}" + assert f.exists(), f"fixture {f.name} missing before rotation" + ORIGINALS[n] = f.read_bytes() + + +def stage(): + # remove anything in logdir, then write back the 6 pristine fixtures + for p in list(logdir.iterdir()): + if p.is_file(): + p.unlink() + for n, data in ORIGINALS.items(): + (logdir / f"app.log.{n}").write_bytes(data) + + +def run(*args): + return subprocess.run( + [sys.executable, str(tool), str(logdir), *args], + cwd=root, capture_output=True, text=True, timeout=60, + ) + + +try: + stage() + r = run("--keep", "4", "--compress-after", "2") + assert r.returncode == 0, f"rotate failed:\n{r.stdout}\n{r.stderr}" + + # N > keep (5,6) deleted entirely (neither plain nor .gz) + for n in (5, 6): + assert not (logdir / f"app.log.{n}").exists(), f"app.log.{n} should be deleted (N>keep)" + assert not (logdir / f"app.log.{n}.gz").exists(), f"app.log.{n}.gz should not exist (N>keep)" + + # N <= compress_after (1,2) remain uncompressed with ORIGINAL content + for n in (1, 2): + plain = logdir / f"app.log.{n}" + assert plain.exists(), f"app.log.{n} should remain uncompressed (N<=compress_after)" + assert not (logdir / f"app.log.{n}.gz").exists(), f"app.log.{n}.gz should not exist (N<=compress_after)" + assert plain.read_bytes() == ORIGINALS[n], f"app.log.{n} content changed unexpectedly" + + # compress_after < N <= keep (3,4) replaced by .gz whose decompressed bytes == originals + for n in (3, 4): + assert not (logdir / f"app.log.{n}").exists(), f"app.log.{n} should be replaced by .gz" + gz = logdir / f"app.log.{n}.gz" + assert gz.exists(), f"app.log.{n}.gz should exist (compress_after newest**: + + ```json + {"history": [{"version": "1.0.0", "artifact": "app-1.0.0.tar.gz"}, ...]} + ``` + +- `current.txt` holds the currently deployed version (a single line). + +Implement `rollback.py`: + +- `python rollback.py previous` — set `current.txt` to the version immediately + **before** the current one in history order. +- `python rollback.py ` — set `current.txt` to that specific version, + if it exists in history and is not already current. +- On an unknown / invalid target, exit with a **nonzero** code and leave + `current.txt` unchanged. +- Append a rollback record (e.g. to `rollback_log.jsonl`) on each successful + rollback. + +Use only the Python standard library; no network access required. diff --git a/task_053/environment/code/current.txt b/task_053/environment/code/current.txt new file mode 100644 index 0000000000000000000000000000000000000000..227cea215648b1af34a87c9acf5b707fe02d2072 --- /dev/null +++ b/task_053/environment/code/current.txt @@ -0,0 +1 @@ +2.0.0 diff --git a/task_053/environment/code/releases.json b/task_053/environment/code/releases.json new file mode 100644 index 0000000000000000000000000000000000000000..7d17f64ac2a894e875269764b0c28a1eff954594 --- /dev/null +++ b/task_053/environment/code/releases.json @@ -0,0 +1,9 @@ +{ + "history": [ + {"version": "1.0.0", "artifact": "app-1.0.0.tar.gz"}, + {"version": "1.1.0", "artifact": "app-1.1.0.tar.gz"}, + {"version": "1.2.0", "artifact": "app-1.2.0.tar.gz"}, + {"version": "1.2.1", "artifact": "app-1.2.1.tar.gz"}, + {"version": "2.0.0", "artifact": "app-2.0.0.tar.gz"} + ] +} diff --git a/task_053/environment/docker-compose.yaml b/task_053/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_053/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_053/instruction.md b/task_053/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fa4c0b2c7038ade036de125687b268fe507276b9 --- /dev/null +++ b/task_053/instruction.md @@ -0,0 +1,15 @@ +# Roll back a deployed release and audit changes + +Implement `python3 rollback.py previous` and `python3 rollback.py VERSION`. Read `releases.json` and `current.txt` from the current working directory. Use only the Python standard library. + +## Inputs and outputs + +- `releases.json` has a `history` array ordered oldest to newest. Each entry has a `version` string and may include artifact metadata. +- `current.txt` contains one deployed version. Use the order in history, not version-string sorting, to find its predecessor. +- On success, update `current.txt` to the target and append exactly one JSON line to `rollback_log.jsonl`. Each line includes `from`, `to`, `mode` (`previous` or `explicit`), and `at` (an ISO timestamp for this operation with UTC offset). Additional fields are allowed. + +## Acceptance Checklist + +- `previous` selects the version immediately before the current entry. An explicit version selects any different entry that exists. +- Return success for a valid target. Each success preserves all existing log bytes and appends a record with the actual prior version, target, operation mode and current UTC time. +- Unknown or already-current targets, and attempting `previous` at the oldest release, return nonzero and leave both the version file and log unchanged. diff --git a/task_053/quality_notes.md b/task_053/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..8799d2dd12aa1903763d12f369e0b6c47639acc9 --- /dev/null +++ b/task_053/quality_notes.md @@ -0,0 +1,9 @@ +# Quality notes — task_086 + +- Closed/self-contained: pure Python stdlib (`json`, `pathlib`), no network. +- Discrimination: a tool that hardcodes the rollback target fails the explicit + `` case; one that ignores validation fails the unknown-version + case (must exit nonzero and leave current.txt unchanged). The `previous` + target is recomputed from history order, not assumed. +- Verifier re-stages `current.txt` before every run for determinism and reads + the actual file state rather than grepping source. diff --git a/task_053/solution/README.md b/task_053/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8e8c4918db9e69bd2fdd5abf9b46571978bd5ff8 --- /dev/null +++ b/task_053/solution/README.md @@ -0,0 +1,8 @@ +# Reference solution — task_086 + +`rollback.py` reads `releases.json` (history oldest -> newest) and +`current.txt`. `previous` resolves to the version immediately before the +current one; an explicit `` resolves to that version if it exists and +differs from current. On success it rewrites `current.txt` and appends a JSON +record to `rollback_log.jsonl`. Invalid targets (unknown version, already at +oldest, target equals current) exit nonzero and leave `current.txt` untouched. diff --git a/task_053/solution/code/current.txt b/task_053/solution/code/current.txt new file mode 100644 index 0000000000000000000000000000000000000000..227cea215648b1af34a87c9acf5b707fe02d2072 --- /dev/null +++ b/task_053/solution/code/current.txt @@ -0,0 +1 @@ +2.0.0 diff --git a/task_053/solution/code/releases.json b/task_053/solution/code/releases.json new file mode 100644 index 0000000000000000000000000000000000000000..7d17f64ac2a894e875269764b0c28a1eff954594 --- /dev/null +++ b/task_053/solution/code/releases.json @@ -0,0 +1,9 @@ +{ + "history": [ + {"version": "1.0.0", "artifact": "app-1.0.0.tar.gz"}, + {"version": "1.1.0", "artifact": "app-1.1.0.tar.gz"}, + {"version": "1.2.0", "artifact": "app-1.2.0.tar.gz"}, + {"version": "1.2.1", "artifact": "app-1.2.1.tar.gz"}, + {"version": "2.0.0", "artifact": "app-2.0.0.tar.gz"} + ] +} diff --git a/task_053/solution/code/rollback.py b/task_053/solution/code/rollback.py new file mode 100644 index 0000000000000000000000000000000000000000..1ed1b5f48acc845b133acf177eaedbfc9c530be6 --- /dev/null +++ b/task_053/solution/code/rollback.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""Release rollback tool. + +Usage: + python rollback.py previous # roll back to the version just before current + python rollback.py # roll back to a specific version in history + +Reads `releases.json` (history ordered oldest -> newest) and `current.txt` +(the deployed version). On success, rewrites `current.txt` and appends a +record to `rollback_log.jsonl`. On an unknown target it exits nonzero and +leaves `current.txt` unchanged. +""" +import datetime +import json +import pathlib +import sys + +RELEASES = pathlib.Path("releases.json") +CURRENT = pathlib.Path("current.txt") +LOG = pathlib.Path("rollback_log.jsonl") + + +def load_history(): + data = json.loads(RELEASES.read_text(encoding="utf-8")) + return [entry["version"] for entry in data["history"]] + + +def read_current(): + return CURRENT.read_text(encoding="utf-8").strip() + + +def write_current(version): + CURRENT.write_text(version + "\n", encoding="utf-8") + + +def append_log(from_version, to_version, mode): + record = { + "from": from_version, + "to": to_version, + "mode": mode, + "at": datetime.datetime.now(datetime.timezone.utc).isoformat(), + } + with LOG.open("a", encoding="utf-8") as fh: + fh.write(json.dumps(record) + "\n") + + +def resolve_target(arg, history, current): + if arg == "previous": + if current not in history: + return None, f"current version {current!r} not found in history" + idx = history.index(current) + if idx == 0: + return None, "already at the oldest release; cannot roll back further" + return history[idx - 1], None + # explicit version + if arg not in history: + return None, f"unknown version {arg!r}" + if arg == current: + return None, f"version {arg!r} is already current" + return arg, None + + +def main(argv): + if len(argv) < 2: + print("usage: rollback.py previous|", file=sys.stderr) + return 2 + + arg = argv[1] + history = load_history() + current = read_current() + + target, err = resolve_target(arg, history, current) + if target is None: + print(f"ERROR {err}", file=sys.stderr) + return 1 + + write_current(target) + append_log(current, target, "previous" if arg == "previous" else "explicit") + print(f"ROLLBACK {current} -> {target}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/task_053/solution/solve.sh b/task_053/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_053/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_053/task.toml b/task_053/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_053/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_053/task_meta.json b/task_053/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..3f2324fc95db63fe870471144cdaea6b81721b3d --- /dev/null +++ b/task_053/task_meta.json @@ -0,0 +1,18 @@ +{ + "task_id": 86, + "task_category": "build_deployment", + "origin_model": "authored", + "sample_count": 0, + "user_turns": 0, + "language": "python", + "input_assets": [ + "releases.json", + "current.txt" + ], + "expected_outputs": [ + "rollback.py" + ], + "source_row_id": null, + "repair_revision": "2026-09-29", + "instruction_sha256": "1e23e3195d354c0299d34c909ba727627bb312c762fc67be582bcce8ced1d106" +} diff --git a/task_053/tests/_shared/contract_checker.js b/task_053/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_053/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_053/tests/_shared/static_enhancer.sh b/task_053/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_053/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_053/tests/enhancement_cases.json b/task_053/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..9e8a8904df6b22077415b453d213d88ad43c5852 --- /dev/null +++ b/task_053/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +{ + "task_id": "task_086", + "cases": [ + { + "id": "ENHANCED_CASE_1", + "instruction_evidence": "previous按旧到新history回滚到当前前一版", + "assertion": "multiple current positions resolve previous from fixture ordering, not lexical version order" + }, + { + "id": "ENHANCED_CASE_2", + "instruction_evidence": "指定存在且不同版本可回滚;成功追加记录", + "assertion": "valid explicit target updates current and appends exactly one record identifying transition" + }, + { + "id": "ENHANCED_CASE_3", + "instruction_evidence": "最旧previous、不存在、等于当前均失败且current不变", + "assertion": "each invalid mode exits nonzero, preserves exact current bytes, and appends no success record" + } + ] +} diff --git a/task_053/tests/review_hard.py b/task_053/tests/review_hard.py new file mode 100644 index 0000000000000000000000000000000000000000..e14759e0d507ccfe33bb44de66df372cfbb7638e --- /dev/null +++ b/task_053/tests/review_hard.py @@ -0,0 +1,46 @@ +"""Append-only history records and side-effect-free invalid requests.""" +import datetime +import json +import subprocess +import sys +import tempfile +from pathlib import Path + + +def main(root): + with tempfile.TemporaryDirectory() as temporary: + workspace = Path(temporary) + (workspace / 'releases.json').write_text(json.dumps({'history': [{'version': v} for v in ('v1', 'v2', 'v3')]})) + current, log = workspace / 'current.txt', workspace / 'rollback_log.jsonl' + current.write_text('v3\n') + prefix = b'{"from":"prior","to":"v3","extra":"preserve this record"}\n' + log.write_bytes(prefix) + for target, before, after, mode in [('previous', 'v3', 'v2', 'previous'), ('v1', 'v2', 'v1', 'explicit')]: + started = datetime.datetime.now(datetime.timezone.utc) + result = subprocess.run([sys.executable, str(root / 'rollback.py'), target], cwd=workspace, + text=True, capture_output=True, timeout=30) + finished = datetime.datetime.now(datetime.timezone.utc) + assert result.returncode == 0, (result.stdout, result.stderr) + assert current.read_text().strip() == after + content = log.read_bytes() + assert content.startswith(prefix), 'existing records were overwritten' + added = content[len(prefix):].splitlines() + assert len(added) == 1, 'each success must append exactly one JSON record' + record = json.loads(added[0]) + assert (record['from'], record['to'], record['mode']) == (before, after, mode) + stamp = datetime.datetime.fromisoformat(record['at']) + assert stamp.utcoffset() == datetime.timedelta(0), 'timestamp must include UTC timezone' + tolerance = datetime.timedelta(seconds=2) + assert started - tolerance <= stamp <= finished + tolerance, 'timestamp does not describe this rollback' + prefix = content + for invalid in ('previous', 'v1', 'absent'): + original = current.read_bytes(), log.read_bytes() + result = subprocess.run([sys.executable, str(root / 'rollback.py'), invalid], cwd=workspace, + text=True, capture_output=True, timeout=30) + assert result.returncode != 0 + assert original == (current.read_bytes(), log.read_bytes()) + print('Append-only records, event UTC timestamps and unchanged invalid-request state: PASS') + + +if __name__ == '__main__': + main(Path(sys.argv[1]).resolve()) diff --git a/task_053/tests/review_legacy.sh b/task_053/tests/review_legacy.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a3feb71d9fbd5ae03b9e99fd196dca7e8d62120 --- /dev/null +++ b/task_053/tests/review_legacy.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +set -euo pipefail +set +e +TASK_ID='86' +source "$(cd "$(dirname "$0")" && pwd)/_shared/static_enhancer.sh" +LOG_DIR="/logs/verifier" +if ! mkdir -p "$LOG_DIR" 2>/dev/null; then LOG_DIR="logs/verifier"; mkdir -p "$LOG_DIR"; fi +REWARD_FILE="$LOG_DIR/reward.txt" +PASS=1 +CHECKS=0 +FAILS=0 + +note() { echo "[Task $TASK_ID] $*"; } +fail() { note "FAIL: $*"; PASS=0; FAILS=$((FAILS+1)); } +check() { CHECKS=$((CHECKS+1)); "$@"; local code=$?; if [ $code -ne 0 ]; then fail "$*"; fi; } +have_any() { local pattern="$1"; compgen -G "$pattern" >/dev/null 2>&1; } +grep_any() { local pattern="$1"; shift; grep -REiq -- "$pattern" "$@" 2>/dev/null; } +source_files() { find . -type f \( -name '*.html' -o -name '*.js' -o -name '*.jsx' -o -name '*.ts' -o -name '*.tsx' -o -name '*.css' -o -name '*.py' -o -name '*.go' -o -name '*.swift' -o -name '*.svg' \) ! -path './tests/*' ! -path './logs/*'; } + +note "enhanced deterministic verifier start" +static_enhance_check "${TASK_ID}" "$(pwd)" +mapfile -t py_files < <(find . -type f -name '*.py' ! -path './tests/*') +if [ ${#py_files[@]} -eq 0 ]; then fail "no Python source found"; fi +if command -v python3 >/dev/null 2>&1; then + for f in "${py_files[@]}"; do python3 -m py_compile "$f" >/tmp/harbor_py_compile.log 2>&1 || fail "python compile failed: $f"; done +fi + +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +if command -v python3 >/dev/null 2>&1; then + check python3 "$TEST_DIR/validate_outputs.py" +else + fail "python3 unavailable for output validation" +fi +# BEGIN ENHANCED_CASES_081_088 +if command -v python3 >/dev/null 2>&1; then + check python3 "$TEST_DIR/validate_enhanced.py" 86 "$(pwd)" +else + fail "python3 unavailable for enhanced validation" +fi +# END ENHANCED_CASES_081_088 +# BEGIN AAAV_DYNAMIC_TEST +if [ -f "$TEST_DIR/validate_aaav_dynamic.js" ]; then + if command -v node >/dev/null 2>&1; then + check node "$TEST_DIR/validate_aaav_dynamic.js" + else + note "AAAV dynamic validation skipped (node unavailable in this runtime)" + fi +fi +# END AAAV_DYNAMIC_TEST +note "checks=$CHECKS fails=$FAILS" +if [ "$PASS" -eq 1 ]; then + echo 1 > "$REWARD_FILE" + note "PASS" + exit 0 +fi +echo 0 > "$REWARD_FILE" +note "FAIL" +exit 0 diff --git a/task_053/tests/test.sh b/task_053/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56b0776f3ccad7f2da017c3b6e7cd69a9a1454e6 --- /dev/null +++ b/task_053/tests/test.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -uo pipefail +bash /tests/review_legacy.sh +CORE=$(cat /logs/verifier/reward.txt 2>/dev/null || echo 0) +mkdir -p /logs/verifier +python3 /tests/review_hard.py /app 2>&1 | tee /logs/verifier/review_hard.log +RC=${PIPESTATUS[0]} +if [ "$RC" -ne 0 ]; then echo "REVIEW_HARD failed with exit code $RC"; fi +if [ "$RC" -eq 0 ]; then echo "$CORE"; else echo 0; fi > /logs/verifier/reward.txt +exit 0 diff --git a/task_053/tests/validate_aaav_dynamic.js b/task_053/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..53e1d3920a848f7af374c8760111e79a2942aad2 --- /dev/null +++ b/task_053/tests/validate_aaav_dynamic.js @@ -0,0 +1,27 @@ +const fs = require('fs'); +const path = require('path'); +const child_process = require('child_process'); +const TASK_ID = 86; +const LANGUAGE = "python"; +const EXPECTED = []; +const SKIP_DIRS = new Set(["tests","logs","node_modules",".git"]); +function assert(condition, message) { if (!condition) throw new Error(message); } +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} +const files = walk(process.cwd()); +assert(files.length > 0, 'candidate workspace should contain files'); +const source = files.filter(f => /\.(js|jsx|ts|tsx|css|html|py|go|md|svg)$/i.test(f)); +assert(source.length > 0, 'candidate should contain source or report files'); +const pyFiles = files.filter(f => f.endsWith('.py')); +for (const f of pyFiles.slice(0, 20)) { + child_process.execFileSync('python3', ['-m', 'py_compile', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); +} +console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); diff --git a/task_053/tests/validate_enhanced.py b/task_053/tests/validate_enhanced.py new file mode 100644 index 0000000000000000000000000000000000000000..70a6d5b439e0b022fb42feaa0676f1eae2c48e1a --- /dev/null +++ b/task_053/tests/validate_enhanced.py @@ -0,0 +1,339 @@ +#!/usr/bin/env python3 +import base64 +import datetime +import gzip +import hashlib +import json +import os +import pathlib +import re +import shutil +import subprocess +import sys +import tempfile +import time +import zipfile + +TIMEOUT = 8 + + +def run(root, script, *args, timeout=TIMEOUT): + env = os.environ.copy() + for key in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"): + env.pop(key, None) + env["PYTHONHASHSEED"] = "0" + return subprocess.run( + [sys.executable, str(root / script), *map(str, args)], cwd=root, + text=True, capture_output=True, timeout=timeout, env=env, + ) + + +def workspace(candidate): + td = tempfile.TemporaryDirectory(prefix="glm-enhanced-") + root = pathlib.Path(td.name) / "code" + shutil.copytree(pathlib.Path(candidate).resolve(), root) + return td, root + + +def lines(proc): + return [x.strip() for x in proc.stdout.splitlines() if x.strip()] + + +def exact_actions(proc, expected): + assert proc.returncode == 0, proc.stdout + proc.stderr + assert lines(proc) == expected, f"status lines {lines(proc)!r} != {expected!r}" + + +def case81(candidate): + td, root = workspace(candidate) + try: + (root / "src/deep").mkdir(parents=True, exist_ok=True) + data = { + "targets": [ + {"name": "alpha-x", "inputs": ["src/a.txt", "src/deep/b.txt"], "output": "out/deep/a.bin"}, + {"name": "beta_9", "inputs": ["src/c.txt"], "output": "out/b.txt"}, + {"name": "empty", "inputs": [], "output": "out/empty.txt"}, + ] + } + (root / "build.json").write_text(json.dumps(data), encoding="utf-8") + (root / "src/a.txt").write_bytes(b"A\nA") + (root / "src/deep/b.txt").write_bytes(b"B\x00B") + (root / "src/c.txt").write_bytes(b"C") + for p in (root / ".buildcache.json", root / "out"): + if p.is_dir(): shutil.rmtree(p) + elif p.exists(): p.unlink() + # ENHANCED_CASE_1: every declared target builds with exact ordered bytes. + p1 = run(root, "builder.py") + exact_actions(p1, ["BUILD alpha-x", "BUILD beta_9", "BUILD empty"]) + assert (root / "out/deep/a.bin").read_bytes() == b"A\nA\nB\x00B" + assert (root / "out/b.txt").read_bytes() == b"C" + assert (root / "out/empty.txt").read_bytes() == b"" + print("ENHANCED_CASE_1 PASS") + mtimes = {p: (root / p).stat().st_mtime_ns for p in ("out/deep/a.bin", "out/b.txt", "out/empty.txt")} + time.sleep(0.02) + # ENHANCED_CASE_2: unchanged inputs and existing outputs are skipped and untouched. + p2 = run(root, "builder.py") + exact_actions(p2, ["SKIP alpha-x", "SKIP beta_9", "SKIP empty"]) + assert mtimes == {p: (root / p).stat().st_mtime_ns for p in mtimes} + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: one target's content mutation invalidates only that target. + (root / "src/deep/b.txt").write_bytes(b"changed") + p3 = run(root, "builder.py") + exact_actions(p3, ["BUILD alpha-x", "SKIP beta_9", "SKIP empty"]) + assert (root / "out/deep/a.bin").read_bytes() == b"A\nA\nchanged" + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def manifest_oracle(dist): + return {p.relative_to(dist).as_posix(): {"sha256": hashlib.sha256(p.read_bytes()).hexdigest(), "size": p.stat().st_size} + for p in sorted(dist.rglob("*")) if p.is_file()} + + +def case82(candidate): + td, root = workspace(candidate) + try: + dist = root / "payload"; (dist / "a/b").mkdir(parents=True, exist_ok=True) + (dist / "zero").write_bytes(b""); (dist / "a/b/data.bin").write_bytes(b"\x00\xffx"); (dist / "sp ace.txt").write_bytes(b"hello") + mf = root / "custom-manifest.json" + # ENHANCED_CASE_1: recursive POSIX keys, SHA256 and byte sizes exactly match. + g = run(root, "manifest.py", "generate", dist, mf); assert g.returncode == 0, g.stdout + g.stderr + assert json.loads(mf.read_text()) == manifest_oracle(dist) + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: clean passes; changed, missing, and extra files fail and identify paths. + assert run(root, "manifest.py", "verify", dist, mf).returncode == 0 + target = dist / "a/b/data.bin"; original = target.read_bytes() + for mode, name in (("changed", "a/b/data.bin"), ("missing", "a/b/data.bin"), ("extra", "surprise.new")): + if mode == "changed": target.write_bytes(b"different") + elif mode == "missing": target.unlink() + else: (dist / name).write_bytes(b"extra") + p = run(root, "manifest.py", "verify", dist, mf) + assert p.returncode != 0 and name in p.stdout + p.stderr, (mode, p.stdout, p.stderr) + if mode in ("changed", "missing"): target.write_bytes(original) + else: (dist / name).unlink() + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: newly added nested files appear after regeneration. + (dist / "a/new/deeper").mkdir(parents=True); (dist / "a/new/deeper/z").write_bytes(b"z") + assert run(root, "manifest.py", "generate", dist, mf).returncode == 0 + assert json.loads(mf.read_text()) == manifest_oracle(dist) + assert run(root, "manifest.py", "verify", dist, mf).returncode == 0 + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def case83(candidate): + td, root = workspace(candidate) + try: + template = root / "custom.example" + template.write_text("# ignored\n\n BAD LINE\n FIRST = ignored\nSECOND=template-value\nTHIRD=\n", encoding="utf-8") + env = root / "candidate.env" + # ENHANCED_CASE_1: only valid left-hand template keys are requirements. + env.write_text("FIRST=one\nSECOND=two\nTHIRD=three\n", encoding="utf-8") + p = run(root, "validate_env.py", env, template); assert p.returncode == 0, p.stdout + p.stderr + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: missing and empty keys are both named on failure. + env.write_text("SECOND=\nTHIRD=ok\n", encoding="utf-8") + p = run(root, "validate_env.py", env, template) + assert p.returncode != 0 and "FIRST" in p.stdout and "SECOND" in p.stdout + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: a runtime-added template key is dynamically required. + env.write_text("FIRST=1\nSECOND=2\nTHIRD=3\n", encoding="utf-8") + assert run(root, "validate_env.py", env, template).returncode == 0 + template.write_text(template.read_text() + "RUNTIME_NEW=ignored\n", encoding="utf-8") + p = run(root, "validate_env.py", env, template) + assert p.returncode != 0 and "RUNTIME_NEW" in p.stdout + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def stage_logs(root, numbers): + d = root / "fixture-logs" + if d.exists(): shutil.rmtree(d) + d.mkdir() + originals = {} + for n in numbers: + originals[n] = f"log-{n}\n".encode() + bytes([n % 256]) + (d / f"app.log.{n}").write_bytes(originals[n]) + return d, originals + + +def case84(candidate): + td, root = workspace(candidate) + try: + d, original = stage_logs(root, [1, 2, 4, 5, 9]) + # ENHANCED_CASE_1: exact delete/plain/gzip partition for arbitrary thresholds. + p = run(root, "rotate.py", d, "--keep", 5, "--compress-after", 2); assert p.returncode == 0, p.stdout + p.stderr + assert sorted(x.name for x in d.iterdir()) == ["app.log.1", "app.log.2", "app.log.4.gz", "app.log.5.gz"] + assert (d / "app.log.1").read_bytes() == original[1] and (d / "app.log.2").read_bytes() == original[2] + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: every gzip payload is byte-identical to its source. + assert gzip.decompress((d / "app.log.4.gz").read_bytes()) == original[4] + assert gzip.decompress((d / "app.log.5.gz").read_bytes()) == original[5] + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: fresh sparse numbers and different thresholds are scanned dynamically. + d, original = stage_logs(root, [2, 7, 11]) + p = run(root, "rotate.py", d, "--keep", 10, "--compress-after", 3); assert p.returncode == 0 + assert sorted(x.name for x in d.iterdir()) == ["app.log.2", "app.log.7.gz"] + assert (d / "app.log.2").read_bytes() == original[2] + assert gzip.decompress((d / "app.log.7.gz").read_bytes()) == original[7] + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def write_checks(path, checks, timeout=.3): + path.write_text(json.dumps({"timeout_sec": timeout, "checks": checks}), encoding="utf-8") + + +def assert_statuses(proc, expected): + ls = lines(proc) + for status in expected: + assert sum(line == status or line.startswith(status + " ") for line in ls) == 1, (status, ls) + assert len(ls) == len(expected) + 1, f"expected one status/check plus one summary: {ls}" + + +def case85(candidate): + td, root = workspace(candidate) + try: + cfg = root / "alt checks.json" + # ENHANCED_CASE_1: stdout substring alone cannot hide nonzero exit or absence. + checks = [ + {"name":"good", "command":[sys.executable,"-c","print('needle here')"], "expect_substring":"needle"}, + {"name":"missing", "command":[sys.executable,"-c","print('other')"], "expect_substring":"needle"}, + {"name":"bad-exit", "command":[sys.executable,"-c","print('needle');raise SystemExit(7)"], "expect_substring":"needle"}, + ] + write_checks(cfg, checks); p = run(root, "smoke.py", cfg) + assert p.returncode != 0; assert_statuses(p, ["PASS good", "FAIL missing", "FAIL bad-exit"]) + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: timeout is per-check and later checks still execute. + checks = [ + {"name":"slow", "command":[sys.executable,"-c","import time;time.sleep(1);print('ok')"], "expect_substring":"ok", "timeout_sec":.08}, + {"name":"after", "command":[sys.executable,"-c","print('after-ok')"], "expect_substring":"after-ok"}, + ] + write_checks(cfg, checks); started=time.monotonic(); p=run(root,"smoke.py",cfg,timeout=3) + assert time.monotonic()-started < 2 and p.returncode != 0 + assert_statuses(p, ["FAIL slow", "PASS after"]) + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: specified config produces exactly one status/check and one summary. + checks = [{"name":"punctuation name", "command":[sys.executable,"-c","print('x-y-z')"], "expect_substring":"x-y"}] + write_checks(cfg, checks); p=run(root,"smoke.py",cfg) + assert p.returncode == 0; assert_statuses(p,["PASS punctuation name"]) + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def file_snapshot(root): + return {p.relative_to(root).as_posix(): p.read_bytes() for p in root.rglob("*") if p.is_file()} + + +def case86(candidate): + td, root = workspace(candidate) + try: + history = ["1.9.0", "1.10.0", "0.5.0", "release-z"] + (root / "releases.json").write_text(json.dumps({"history":[{"version":v,"artifact":v+".tgz"} for v in history]}), encoding="utf-8") + current = root / "current.txt" + # ENHANCED_CASE_1: previous follows history position, not lexical/semantic sorting. + for old, expected in (("release-z","0.5.0"),("0.5.0","1.10.0")): + current.write_text(old+"\n"); p=run(root,"rollback.py","previous") + assert p.returncode == 0 and current.read_text().strip() == expected, p.stdout+p.stderr + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: explicit rollback updates current and appends a persistent record somewhere. + current.write_text("release-z\n"); before=file_snapshot(root); p=run(root,"rollback.py","1.9.0") + assert p.returncode == 0 and current.read_text().strip() == "1.9.0" + after=file_snapshot(root) + changed=[k for k,v in after.items() if k not in ("current.txt",) and (k not in before or len(v)>len(before[k]))] + records=[after[k][len(before.get(k,b"")):] for k in changed] + assert any(b"release-z" in data and b"1.9.0" in data for data in records), \ + "successful rollback record must identify old and target versions" + entry=json.loads((root/"rollback_log.jsonl").read_text().splitlines()[-1]) + assert entry["from"]=="release-z" and entry["to"]=="1.9.0" and entry["mode"]=="explicit" + assert datetime.datetime.fromisoformat(entry["at"]).utcoffset()==datetime.timedelta(0) + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: all stated invalid targets fail and preserve current bytes. + for old,arg in ((history[0],"previous"),("release-z","9.9.9"),("0.5.0","0.5.0")): + raw=(old+"\n").encode(); current.write_bytes(raw); log_before=(root/"rollback_log.jsonl").read_bytes(); p=run(root,"rollback.py",arg) + assert p.returncode != 0 and current.read_bytes() == raw and (root/"rollback_log.jsonl").read_bytes()==log_before + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def expected_asset(rel, content): + p=pathlib.PurePosixPath(rel); return str(p.with_name(f"{p.stem}.{hashlib.sha256(content).hexdigest()[:8]}{p.suffix}")) + + +def case87(candidate): + td, root = workspace(candidate) + try: + src=root/"src"; (src/"assets").mkdir(parents=True,exist_ok=True) + assets={"assets/app.js":b"console.log('edge');\n", "assets/style.css":b"body{color:#123456}\n"} + for rel,data in assets.items(): (src/rel).write_bytes(data) + (src/"index.html").write_text('',encoding="utf-8") + if (root/"dist").exists(): shutil.rmtree(root/"dist") + p=run(root,"build.py"); assert p.returncode==0,p.stdout+p.stderr + manifest=json.loads((root/"dist/manifest.json").read_text()) + expected={rel:expected_asset(rel,data) for rel,data in assets.items()} + # ENHANCED_CASE_1: independently hashed names and copied bytes match. + assert manifest == expected + for rel,hrel in expected.items(): assert (root/"dist"/hrel).read_bytes()==assets[rel] + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: HTML uses every manifest target and no original reference. + html=(root/"dist/index.html").read_text() + assert all(h in html and rel not in html for rel,h in expected.items()) + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: mutating one asset changes only its independently calculated mapping. + assets["assets/app.js"] += b"// mutation\n"; (src/"assets/app.js").write_bytes(assets["assets/app.js"]) + assert run(root,"build.py").returncode==0 + newer=json.loads((root/"dist/manifest.json").read_text()) + assert newer["assets/app.js"]==expected_asset("assets/app.js",assets["assets/app.js"]) + assert newer["assets/app.js"]!=expected["assets/app.js"] and newer["assets/style.css"]==expected["assets/style.css"] + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def record_digest(data): + return "sha256="+base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode() + + +def inspect_wheel(root,name,version): + wheels=list((root/"dist").glob("*.whl")); assert len(wheels)==1,wheels + wheel=wheels[0]; assert wheel.name==f"{name}-{version}-py3-none-any.whl" and zipfile.is_zipfile(wheel) + with zipfile.ZipFile(wheel) as z: + names=z.namelist(); required={f"{name}/__init__.py",f"{name}/ops.py",f"{name}-{version}.dist-info/METADATA",f"{name}-{version}.dist-info/WHEEL",f"{name}-{version}.dist-info/RECORD"} + assert required <= set(names) + meta=z.read(f"{name}-{version}.dist-info/METADATA").decode(); assert re.search(rf"(?m)^Name:\s*{re.escape(name)}\s*$",meta) and re.search(rf"(?m)^Version:\s*{re.escape(version)}\s*$",meta) + rows={line.split(",",2)[0]:line.split(",",2)[1:] for line in z.read(f"{name}-{version}.dist-info/RECORD").decode().splitlines()} + assert set(names) <= set(rows) + for member in names: + if member.endswith("/RECORD"): continue + assert rows[member]==[record_digest(z.read(member)),str(len(z.read(member)))] + return wheel + + +def case88(candidate): + td, root = workspace(candidate) + try: + (root/"mathkit").mkdir(exist_ok=True); (root/"mathkit/__init__.py").write_text("VALUE=1\n"); (root/"mathkit/ops.py").write_text("def add(a,b): return a+b\n") + (root/"pyproject.toml").write_text('[project]\nname="mathkit"\nversion="0.2.0"\n') + if (root/"dist").exists(): shutil.rmtree(root/"dist") + # ENHANCED_CASE_1: metadata-derived name/version and exactly one valid wheel. + assert run(root,"build_wheel.py").returncode==0; wheel=inspect_wheel(root,"mathkit","0.2.0") + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: required members and PEP 427 RECORD hashes/sizes are valid. + assert wheel.exists() + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: version mutation controls filename, dist-info, and METADATA. + (root/"pyproject.toml").write_text('[project]\nname="mathkit"\nversion="0.3.0"\n') + shutil.rmtree(root/"dist"); assert run(root,"build_wheel.py").returncode==0; inspect_wheel(root,"mathkit","0.3.0") + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +CASES={81:case81,82:case82,83:case83,84:case84,85:case85,86:case86,87:case87,88:case88} + + +def main(argv): + if len(argv)!=3 or argv[1] not in {str(x) for x in CASES}: + raise SystemExit("usage: enhanced_suite.py TASK_ID CANDIDATE_DIR") + CASES[int(argv[1])](argv[2]) + + +if __name__ == "__main__": main(sys.argv) diff --git a/task_053/tests/validate_outputs.py b/task_053/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..c18ceff1dde5d02b416573b32213b62d4ebcc248 --- /dev/null +++ b/task_053/tests/validate_outputs.py @@ -0,0 +1,85 @@ +import json +import pathlib +import subprocess +import sys + +root = pathlib.Path.cwd() + +def _py_sources(): + _skip = {"tests", "logs", "output", "__pycache__", "node_modules", ".git"} + return [p for p in root.rglob("*.py") + if not (set(p.relative_to(root).parts) & _skip) + and p.name != "validate_outputs.py"] + + +# locate the rollback tool +candidates = [p for p in _py_sources() if "rollback" in p.name.lower()] +if not candidates: + candidates = [ + p for p in _py_sources() + if "current.txt" in p.read_text(encoding="utf-8", errors="ignore") + ] +assert candidates, "missing rollback tool (e.g. rollback.py)" +runner = candidates[0] + + +releases_path = root / "releases.json" +current_path = root / "current.txt" + +history = [e["version"] for e in + json.loads(releases_path.read_text(encoding="utf-8"))["history"]] +assert len(history) >= 3, "fixture history too short" + + +def stage(current_version): + """Reset current.txt to a known version for a deterministic run.""" + current_path.write_text(current_version + "\n", encoding="utf-8") + + +def read_current(): + return current_path.read_text(encoding="utf-8").strip() + + +def run(arg): + return subprocess.run( + [sys.executable, str(runner), arg], + cwd=root, capture_output=True, text=True, timeout=30, + ) + + +newest = history[-1] +second_newest = history[-2] +an_older = history[0] + +# --- 1) rollback previous: current(newest) -> second-newest --- +stage(newest) +r1 = run("previous") +assert r1.returncode == 0, f"`previous` should succeed:\n{r1.stdout}\n{r1.stderr}" +assert read_current() == second_newest, \ + f"`previous` from {newest} should set {second_newest}, got {read_current()}" + +# --- 2) rollback to a specific older version --- +stage(newest) +r2 = run(an_older) +assert r2.returncode == 0, f"rollback to {an_older} should succeed:\n{r2.stdout}\n{r2.stderr}" +assert read_current() == an_older, \ + f"explicit rollback should set {an_older}, got {read_current()}" + +# --- 3) unknown version: nonzero exit, current.txt unchanged --- +stage(newest) +before = read_current() +r3 = run("9.9.9") +assert r3.returncode != 0, "rollback to a nonexistent version must exit nonzero" +assert read_current() == before, \ + f"current.txt must be unchanged on unknown version (was {before}, now {read_current()})" + +# --- 4) rolling back to the already-current version is rejected, unchanged --- +stage(newest) +r4 = run(newest) +assert r4.returncode != 0, "rolling back to the already-current version must exit nonzero" +assert read_current() == newest, "current.txt must be unchanged when target == current" + +# re-stage to the shipped default so the workspace is left clean/deterministic +stage(newest) + +print("validate_outputs OK: task_086 rollback selects previous/explicit and rejects unknown") diff --git a/task_054/acceptance_checklist.json b/task_054/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..c183382348d757f9bc6bcff0555a8a793f02e01b --- /dev/null +++ b/task_054/acceptance_checklist.json @@ -0,0 +1,28 @@ +{ + "task_id": 88, + "category": "build_deployment", + "language": "python", + "acceptance_items": [ + "Exactly one dist/*.whl is produced and it is a valid zip.", + "Wheel filename version and METADATA Version match the pyproject version.", + "The zip contains mathkit/__init__.py, mathkit/ops.py and a *.dist-info/RECORD.", + "Bumping pyproject version to 0.3.0 updates the wheel filename and METADATA.", + "Stdlib only (no pip/build); runs without internet; Python files compile.", + "Original package bytes, secure CSV RECORD, WHEEL metadata, rebuilt version and old-wheel cleanup." + ], + "input_assets": [ + "pyproject.toml", + "mathkit/__init__.py", + "mathkit/ops.py" + ], + "expected_outputs": [ + "build_wheel.py", + "dist/mathkit-0.2.0-py3-none-any.whl" + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "risk_notes": [ + "Verifier bumps pyproject version to 0.3.0 at runtime to defeat hardcoded versions/filenames." + ], + "repair_revision": "2026-09-29", + "review_revision": "2026-10-07" +} diff --git a/task_054/environment/Dockerfile b/task_054/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2bd34b80ad954f5177a9066cedb797e932ed68ae --- /dev/null +++ b/task_054/environment/Dockerfile @@ -0,0 +1,4 @@ +# syntax=docker/dockerfile:1.7-labs +FROM python:3.12-slim@sha256:090ba77e2958f6af52a5341f788b50b032dd4ca28377d2893dcf1ecbdfdfe203 +WORKDIR /app +COPY ./code /app diff --git a/task_054/environment/code/README.md b/task_054/environment/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cff87711806db1a708ed1be35869a9e4c99c9be4 --- /dev/null +++ b/task_054/environment/code/README.md @@ -0,0 +1,19 @@ +# Wheel packaging starter + +The project: + +- `pyproject.toml` with a `[project]` table: `name = "mathkit"`, `version = "0.2.0"`. +- `mathkit/__init__.py` (exposes `__version__`), `mathkit/ops.py` (a few functions). + +Implement `build_wheel.py` so that running `python build_wheel.py`: + +- Reads `name` and `version` from `pyproject.toml` (use stdlib `tomllib`). +- Builds a PEP 427 wheel at `dist/mathkit--py3-none-any.whl` (a zip) + containing: + - the package files (`mathkit/__init__.py`, `mathkit/ops.py`), + - `mathkit-.dist-info/METADATA` with `Name:` and `Version:` fields, + - `mathkit-.dist-info/WHEEL`, + - `mathkit-.dist-info/RECORD`. + +Use only the Python standard library (`tomllib`, `zipfile`, `hashlib`). Do not +use `pip` or the `build` package, and no network access is required. diff --git a/task_054/environment/code/mathkit/__init__.py b/task_054/environment/code/mathkit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..082cf5fcf8e4ae0d0be5494464344a6498303932 --- /dev/null +++ b/task_054/environment/code/mathkit/__init__.py @@ -0,0 +1,6 @@ +"""mathkit — a tiny math utility package.""" +from .ops import add, multiply, factorial + +__version__ = "0.2.0" + +__all__ = ["add", "multiply", "factorial", "__version__"] diff --git a/task_054/environment/code/mathkit/ops.py b/task_054/environment/code/mathkit/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..764b98542803d3925a895e47c136dabf511c4211 --- /dev/null +++ b/task_054/environment/code/mathkit/ops.py @@ -0,0 +1,21 @@ +"""Core math operations for mathkit.""" + + +def add(a, b): + """Return the sum of a and b.""" + return a + b + + +def multiply(a, b): + """Return the product of a and b.""" + return a * b + + +def factorial(n): + """Return n! for a non-negative integer n.""" + if n < 0: + raise ValueError("factorial is undefined for negative integers") + result = 1 + for i in range(2, n + 1): + result *= i + return result diff --git a/task_054/environment/code/pyproject.toml b/task_054/environment/code/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..e57e016687162b3fd2783710305796f04b06eed3 --- /dev/null +++ b/task_054/environment/code/pyproject.toml @@ -0,0 +1,9 @@ +[project] +name = "mathkit" +version = "0.2.0" +description = "A tiny math utility package" +requires-python = ">=3.8" + +[build-system] +requires = [] +build-backend = "build_wheel" diff --git a/task_054/environment/docker-compose.yaml b/task_054/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_054/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_054/instruction.md b/task_054/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..47f4f321da61438467fffd7ce5539d5e0b634811 --- /dev/null +++ b/task_054/instruction.md @@ -0,0 +1,17 @@ +# Build a pure-Python wheel without a packaging tool + +Implement `python3 build_wheel.py` for the supplied `mathkit` package. Use the standard library, including `tomllib`, `zipfile` and `hashlib`, without invoking pip, build or a network service. + +## Inputs and output + +Read distribution name and version from `[project]` in `pyproject.toml`. Build a pure-Python PEP 427 wheel at `dist/--py3-none-any.whl`. For the supplied package, include `mathkit/__init__.py` and `mathkit/ops.py` unchanged, and include the following in `-.dist-info/`: + +- `METADATA`: fields `Name` and `Version` from the project. +- `WHEEL`: `Wheel-Version: 1.0`, `Root-Is-Purelib: true`, `Tag: py3-none-any`. +- `RECORD`: CSV rows containing archive path, digest and byte count. For every file other than `RECORD`, the digest is `algorithm=encoded_digest`, with SHA-256 or a stronger secure hash and URL-safe Base64 without padding. The row for `RECORD` itself has empty digest and byte-count fields. + +## Acceptance Checklist + +- Produce one readable, importable wheel for the current project, without duplicate members. Preserve the actual package source bytes; do not substitute a generated implementation. +- Derive archive name, metadata and dist-info paths from project settings. On rebuilding, including after a version change, remove the project's stale wheels. +- Record correct digests and exact byte lengths for every archived file. Use one record per path, with no references to nonexistent members. ZIP directory entries are allowed and need not be recorded; metadata ordering, valid CSV quoting, supported compression and eligible hash algorithm are not fixed. diff --git a/task_054/quality_notes.md b/task_054/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..5633cc2c3ddcf83fd046bc61ef53fa478cc7bb26 --- /dev/null +++ b/task_054/quality_notes.md @@ -0,0 +1,20 @@ +# Quality notes — task_088 + +- 2026-10-07 audit: previous RECORD check incorrectly allowed only SHA-256; + PyPA permits SHA-256 or stronger. Accept equivalent secure algorithms and CSV + quoting; check actual WHEEL metadata and package bytes. Preserve the existing + enhanced version-change cleanup test and also exercise it in the primary check. + Primary specification: https://packaging.python.org/en/latest/specifications/binary-distribution-format/ +- Follow-up controls exposed a gap: dynamic fixtures did not contain multiply, + so changing only its archived implementation escaped the enhanced check. + Compare all original package bytes captured before execution, not only synthetic + package fixtures. Archive actual versioned wheels for semantic inspection. + +- Closed/self-contained: pure Python stdlib (`tomllib`, `zipfile`, `hashlib`, + `base64`), no pip/build, no network. +- Discrimination: a builder that hardcodes `mathkit-0.2.0-...whl` or a constant + METADATA version fails the bump-to-0.3.0 rebuild, which recomputes the + expected name/version by reading pyproject. A builder that omits package files + or RECORD fails the zip-contents check. +- Verifier inspects the actual zip (filename, validity, member list, METADATA + fields) rather than grepping source, and restores pyproject.toml afterward. diff --git a/task_054/solution/README.md b/task_054/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..75e17b55142bcc1991de40238cb6b66332b32acf --- /dev/null +++ b/task_054/solution/README.md @@ -0,0 +1,9 @@ +# Reference solution — task_088 + +`build_wheel.py` reads `name`/`version` from `pyproject.toml` via stdlib +`tomllib`, then assembles a PEP 427 wheel +`dist/mathkit--py3-none-any.whl` with `zipfile`: the package files +plus a `mathkit-.dist-info/` containing METADATA (`Name:`/`Version:`), +WHEEL (tag `py3-none-any`), and a RECORD listing each entry with its +`sha256=` hash and size. No pip / build — stdlib only +(`tomllib`, `zipfile`, `hashlib`, `base64`). diff --git a/task_054/solution/code/build_wheel.py b/task_054/solution/code/build_wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..de56e8c8bf033c100a1111090e820802af1b3ab7 --- /dev/null +++ b/task_054/solution/code/build_wheel.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Build a PEP 427 wheel for the `mathkit` package using only the stdlib. + +Reads name + version from `pyproject.toml` ([project] table) and produces +`dist/--py3-none-any.whl` (a zip) containing the package files +plus a `-.dist-info/` directory with METADATA, WHEEL and RECORD. + +No pip, no build backend — just `tomllib`, `zipfile`, `hashlib`, `base64`. +""" +import base64 +import csv +import hashlib +import io +import pathlib +import tomllib +import zipfile + +ROOT = pathlib.Path(".") +DIST = ROOT / "dist" + + +def read_project(): + data = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8")) + project = data["project"] + return project["name"], project["version"] + + +def package_files(name): + """All files under the importable package directory.""" + pkg_dir = ROOT / name + return sorted(p for p in pkg_dir.rglob("*") if p.is_file() and '__pycache__' not in p.parts) + + +def record_hash(content: bytes) -> str: + digest = hashlib.sha256(content).digest() + b64 = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii") + return f"sha256={b64}" + + +def build(): + name, version = read_project() + DIST.mkdir(parents=True, exist_ok=True) + for old_wheel in DIST.glob(f"{name}-*-py3-none-any.whl"): + old_wheel.unlink() + dist_info = f"{name}-{version}.dist-info" + wheel_name = f"{name}-{version}-py3-none-any.whl" + wheel_path = DIST / wheel_name + + metadata = ( + "Metadata-Version: 2.1\n" + f"Name: {name}\n" + f"Version: {version}\n" + ).encode("utf-8") + wheel_meta = ( + "Wheel-Version: 1.0\n" + "Generator: build_wheel (stdlib)\n" + "Root-Is-Purelib: true\n" + "Tag: py3-none-any\n" + ).encode("utf-8") + + # collect (arcname, bytes) entries + entries = [] + for path in package_files(name): + arcname = path.relative_to(ROOT).as_posix() + entries.append((arcname, path.read_bytes())) + entries.append((f"{dist_info}/METADATA", metadata)) + entries.append((f"{dist_info}/WHEEL", wheel_meta)) + + # build RECORD (RECORD itself listed with empty hash/size) + record_stream = io.StringIO(newline='') + record_writer = csv.writer(record_stream) + for arcname, content in entries: + record_writer.writerow([arcname, record_hash(content), len(content)]) + record_writer.writerow([f'{dist_info}/RECORD', '', '']) + record = record_stream.getvalue().encode('utf-8') + entries.append((f"{dist_info}/RECORD", record)) + + with zipfile.ZipFile(wheel_path, "w", zipfile.ZIP_DEFLATED) as zf: + for arcname, content in entries: + zf.writestr(arcname, content) + + print(f"built {wheel_path}") + return wheel_path + + +if __name__ == "__main__": + build() diff --git a/task_054/solution/code/mathkit/__init__.py b/task_054/solution/code/mathkit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..082cf5fcf8e4ae0d0be5494464344a6498303932 --- /dev/null +++ b/task_054/solution/code/mathkit/__init__.py @@ -0,0 +1,6 @@ +"""mathkit — a tiny math utility package.""" +from .ops import add, multiply, factorial + +__version__ = "0.2.0" + +__all__ = ["add", "multiply", "factorial", "__version__"] diff --git a/task_054/solution/code/mathkit/ops.py b/task_054/solution/code/mathkit/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..764b98542803d3925a895e47c136dabf511c4211 --- /dev/null +++ b/task_054/solution/code/mathkit/ops.py @@ -0,0 +1,21 @@ +"""Core math operations for mathkit.""" + + +def add(a, b): + """Return the sum of a and b.""" + return a + b + + +def multiply(a, b): + """Return the product of a and b.""" + return a * b + + +def factorial(n): + """Return n! for a non-negative integer n.""" + if n < 0: + raise ValueError("factorial is undefined for negative integers") + result = 1 + for i in range(2, n + 1): + result *= i + return result diff --git a/task_054/solution/code/pyproject.toml b/task_054/solution/code/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..e57e016687162b3fd2783710305796f04b06eed3 --- /dev/null +++ b/task_054/solution/code/pyproject.toml @@ -0,0 +1,9 @@ +[project] +name = "mathkit" +version = "0.2.0" +description = "A tiny math utility package" +requires-python = ">=3.8" + +[build-system] +requires = [] +build-backend = "build_wheel" diff --git a/task_054/solution/solve.sh b/task_054/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_054/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_054/task.toml b/task_054/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_054/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_054/task_meta.json b/task_054/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..d4de6f13855b3855c1b661710039386cf6698cb8 --- /dev/null +++ b/task_054/task_meta.json @@ -0,0 +1,20 @@ +{ + "task_id": 88, + "task_category": "build_deployment", + "origin_model": "authored", + "sample_count": 0, + "user_turns": 0, + "language": "python", + "input_assets": [ + "pyproject.toml", + "mathkit/__init__.py", + "mathkit/ops.py" + ], + "expected_outputs": [ + "build_wheel.py", + "dist/mathkit-0.2.0-py3-none-any.whl" + ], + "source_row_id": null, + "repair_revision": "2026-09-29", + "instruction_sha256": "cd904353e2e557006a0e8014e3196c48f9be71f9f853644b37bf4cf27e767a78" +} diff --git a/task_054/tests/_shared/contract_checker.js b/task_054/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_054/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_054/tests/_shared/static_enhancer.sh b/task_054/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_054/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_054/tests/enhancement_cases.json b/task_054/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..066b0f808a88d0cfd74006589c4a0a8815d477f5 --- /dev/null +++ b/task_054/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +{ + "task_id": "task_088", + "cases": [ + { + "id": "ENHANCED_CASE_1", + "instruction_evidence": "从pyproject读取name/version;恰好一个合法wheel", + "assertion": "fresh build produces one correctly named valid zip from parsed metadata" + }, + { + "id": "ENHANCED_CASE_2", + "instruction_evidence": "包含包文件、METADATA、WHEEL、RECORD", + "assertion": "all required members exist; metadata fields match; RECORD covers archive members with valid hashes/sizes where present" + }, + { + "id": "ENHANCED_CASE_3", + "instruction_evidence": "版本改0.3.0后文件名与METADATA反映新版本", + "assertion": "runtime version mutation rebuilds a sole 0.3.0 wheel and updates dist-info consistently" + } + ] +} diff --git a/task_054/tests/test.sh b/task_054/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d87338f4589feb0422fa68866e63479c62706fb5 --- /dev/null +++ b/task_054/tests/test.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +set -euo pipefail +set +e +TASK_ID='88' +source "$(cd "$(dirname "$0")" && pwd)/_shared/static_enhancer.sh" +LOG_DIR="/logs/verifier" +if ! mkdir -p "$LOG_DIR" 2>/dev/null; then LOG_DIR="logs/verifier"; mkdir -p "$LOG_DIR"; fi +REWARD_FILE="$LOG_DIR/reward.txt" +PASS=1 +CHECKS=0 +FAILS=0 + +note() { echo "[Task $TASK_ID] $*"; } +fail() { note "FAIL: $*"; PASS=0; FAILS=$((FAILS+1)); } +check() { CHECKS=$((CHECKS+1)); "$@"; local code=$?; if [ $code -ne 0 ]; then fail "$*"; fi; } +have_any() { local pattern="$1"; compgen -G "$pattern" >/dev/null 2>&1; } +grep_any() { local pattern="$1"; shift; grep -REiq -- "$pattern" "$@" 2>/dev/null; } +source_files() { find . -type f \( -name '*.html' -o -name '*.js' -o -name '*.jsx' -o -name '*.ts' -o -name '*.tsx' -o -name '*.css' -o -name '*.py' -o -name '*.go' -o -name '*.swift' -o -name '*.svg' \) ! -path './tests/*' ! -path './logs/*'; } + +note "enhanced deterministic verifier start" +static_enhance_check "${TASK_ID}" "$(pwd)" +mapfile -t py_files < <(find . -type f -name '*.py' ! -path './tests/*') +if [ ${#py_files[@]} -eq 0 ]; then fail "no Python source found"; fi +if command -v python3 >/dev/null 2>&1; then + for f in "${py_files[@]}"; do python3 -m py_compile "$f" >/tmp/harbor_py_compile.log 2>&1 || fail "python compile failed: $f"; done +fi + +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +if command -v python3 >/dev/null 2>&1; then + check python3 "$TEST_DIR/validate_outputs.py" +else + fail "python3 unavailable for output validation" +fi +# BEGIN ENHANCED_CASES_081_088 +if command -v python3 >/dev/null 2>&1; then + check python3 "$TEST_DIR/validate_enhanced.py" 88 "$(pwd)" +else + fail "python3 unavailable for enhanced validation" +fi +# END ENHANCED_CASES_081_088 +# BEGIN AAAV_DYNAMIC_TEST +if [ -f "$TEST_DIR/validate_aaav_dynamic.js" ]; then + if command -v node >/dev/null 2>&1; then + check node "$TEST_DIR/validate_aaav_dynamic.js" + else + note "AAAV dynamic validation skipped (node unavailable in this runtime)" + fi +fi +# END AAAV_DYNAMIC_TEST +note "checks=$CHECKS fails=$FAILS" +if [ "$PASS" -eq 1 ]; then + echo 1 > "$REWARD_FILE" + note "PASS" + exit 0 +fi +echo 0 > "$REWARD_FILE" +note "FAIL" +exit 0 diff --git a/task_054/tests/validate_aaav_dynamic.js b/task_054/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..cc08a31dc1b72163782e906b1a94cac12b1e22f2 --- /dev/null +++ b/task_054/tests/validate_aaav_dynamic.js @@ -0,0 +1,27 @@ +const fs = require('fs'); +const path = require('path'); +const child_process = require('child_process'); +const TASK_ID = 88; +const LANGUAGE = "python"; +const EXPECTED = []; +const SKIP_DIRS = new Set(["tests","logs","node_modules",".git"]); +function assert(condition, message) { if (!condition) throw new Error(message); } +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} +const files = walk(process.cwd()); +assert(files.length > 0, 'candidate workspace should contain files'); +const source = files.filter(f => /\.(js|jsx|ts|tsx|css|html|py|go|md|svg)$/i.test(f)); +assert(source.length > 0, 'candidate should contain source or report files'); +const pyFiles = files.filter(f => f.endsWith('.py')); +for (const f of pyFiles.slice(0, 20)) { + child_process.execFileSync('python3', ['-m', 'py_compile', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); +} +console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); diff --git a/task_054/tests/validate_enhanced.py b/task_054/tests/validate_enhanced.py new file mode 100644 index 0000000000000000000000000000000000000000..381e71336e985ae55b63da193077030f30401d8a --- /dev/null +++ b/task_054/tests/validate_enhanced.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +import base64 +import csv +import io +import gzip +import hashlib +import json +import os +import pathlib +import re +import shutil +import subprocess +import sys +import tempfile +import time +import zipfile +from email.parser import Parser + +TIMEOUT = 8 + + +def run(root, script, *args, timeout=TIMEOUT): + env = os.environ.copy() + for key in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"): + env.pop(key, None) + env["PYTHONHASHSEED"] = "0" + return subprocess.run( + [sys.executable, str(root / script), *map(str, args)], cwd=root, + text=True, capture_output=True, timeout=timeout, env=env, + ) + + +def workspace(candidate): + td = tempfile.TemporaryDirectory(prefix="glm-enhanced-") + root = pathlib.Path(td.name) / "code" + shutil.copytree(pathlib.Path(candidate).resolve(), root) + return td, root + + +def lines(proc): + return [x.strip() for x in proc.stdout.splitlines() if x.strip()] + + +def exact_actions(proc, expected): + assert proc.returncode == 0, proc.stdout + proc.stderr + assert lines(proc) == expected, f"status lines {lines(proc)!r} != {expected!r}" + + +def case81(candidate): + td, root = workspace(candidate) + try: + (root / "src/deep").mkdir(parents=True, exist_ok=True) + data = { + "targets": [ + {"name": "alpha-x", "inputs": ["src/a.txt", "src/deep/b.txt"], "output": "out/deep/a.bin"}, + {"name": "beta_9", "inputs": ["src/c.txt"], "output": "out/b.txt"}, + {"name": "empty", "inputs": [], "output": "out/empty.txt"}, + ] + } + (root / "build.json").write_text(json.dumps(data), encoding="utf-8") + (root / "src/a.txt").write_bytes(b"A\nA") + (root / "src/deep/b.txt").write_bytes(b"B\x00B") + (root / "src/c.txt").write_bytes(b"C") + for p in (root / ".buildcache.json", root / "out"): + if p.is_dir(): shutil.rmtree(p) + elif p.exists(): p.unlink() + # ENHANCED_CASE_1: every declared target builds with exact ordered bytes. + p1 = run(root, "builder.py") + exact_actions(p1, ["BUILD alpha-x", "BUILD beta_9", "BUILD empty"]) + assert (root / "out/deep/a.bin").read_bytes() == b"A\nA\nB\x00B" + assert (root / "out/b.txt").read_bytes() == b"C" + assert (root / "out/empty.txt").read_bytes() == b"" + print("ENHANCED_CASE_1 PASS") + mtimes = {p: (root / p).stat().st_mtime_ns for p in ("out/deep/a.bin", "out/b.txt", "out/empty.txt")} + time.sleep(0.02) + # ENHANCED_CASE_2: unchanged inputs and existing outputs are skipped and untouched. + p2 = run(root, "builder.py") + exact_actions(p2, ["SKIP alpha-x", "SKIP beta_9", "SKIP empty"]) + assert mtimes == {p: (root / p).stat().st_mtime_ns for p in mtimes} + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: one target's content mutation invalidates only that target. + (root / "src/deep/b.txt").write_bytes(b"changed") + p3 = run(root, "builder.py") + exact_actions(p3, ["BUILD alpha-x", "SKIP beta_9", "SKIP empty"]) + assert (root / "out/deep/a.bin").read_bytes() == b"A\nA\nchanged" + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def manifest_oracle(dist): + return {p.relative_to(dist).as_posix(): {"sha256": hashlib.sha256(p.read_bytes()).hexdigest(), "size": p.stat().st_size} + for p in sorted(dist.rglob("*")) if p.is_file()} + + +def case82(candidate): + td, root = workspace(candidate) + try: + dist = root / "payload"; (dist / "a/b").mkdir(parents=True, exist_ok=True) + (dist / "zero").write_bytes(b""); (dist / "a/b/data.bin").write_bytes(b"\x00\xffx"); (dist / "sp ace.txt").write_bytes(b"hello") + mf = root / "custom-manifest.json" + # ENHANCED_CASE_1: recursive POSIX keys, SHA256 and byte sizes exactly match. + g = run(root, "manifest.py", "generate", dist, mf); assert g.returncode == 0, g.stdout + g.stderr + assert json.loads(mf.read_text()) == manifest_oracle(dist) + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: clean passes; changed, missing, and extra files fail and identify paths. + assert run(root, "manifest.py", "verify", dist, mf).returncode == 0 + target = dist / "a/b/data.bin"; original = target.read_bytes() + for mode, name in (("changed", "a/b/data.bin"), ("missing", "a/b/data.bin"), ("extra", "surprise.new")): + if mode == "changed": target.write_bytes(b"different") + elif mode == "missing": target.unlink() + else: (dist / name).write_bytes(b"extra") + p = run(root, "manifest.py", "verify", dist, mf) + assert p.returncode != 0 and name in p.stdout + p.stderr, (mode, p.stdout, p.stderr) + if mode in ("changed", "missing"): target.write_bytes(original) + else: (dist / name).unlink() + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: newly added nested files appear after regeneration. + (dist / "a/new/deeper").mkdir(parents=True); (dist / "a/new/deeper/z").write_bytes(b"z") + assert run(root, "manifest.py", "generate", dist, mf).returncode == 0 + assert json.loads(mf.read_text()) == manifest_oracle(dist) + assert run(root, "manifest.py", "verify", dist, mf).returncode == 0 + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def case83(candidate): + td, root = workspace(candidate) + try: + template = root / "custom.example" + template.write_text("# ignored\n\n BAD LINE\n FIRST = ignored\nSECOND=template-value\nTHIRD=\n", encoding="utf-8") + env = root / "candidate.env" + # ENHANCED_CASE_1: only valid left-hand template keys are requirements. + env.write_text("FIRST=one\nSECOND=two\nTHIRD=three\n", encoding="utf-8") + p = run(root, "validate_env.py", env, template); assert p.returncode == 0, p.stdout + p.stderr + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: missing and empty keys are both named on failure. + env.write_text("SECOND=\nTHIRD=ok\n", encoding="utf-8") + p = run(root, "validate_env.py", env, template) + assert p.returncode != 0 and "FIRST" in p.stdout and "SECOND" in p.stdout + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: a runtime-added template key is dynamically required. + env.write_text("FIRST=1\nSECOND=2\nTHIRD=3\n", encoding="utf-8") + assert run(root, "validate_env.py", env, template).returncode == 0 + template.write_text(template.read_text() + "RUNTIME_NEW=ignored\n", encoding="utf-8") + p = run(root, "validate_env.py", env, template) + assert p.returncode != 0 and "RUNTIME_NEW" in p.stdout + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def stage_logs(root, numbers): + d = root / "fixture-logs" + if d.exists(): shutil.rmtree(d) + d.mkdir() + originals = {} + for n in numbers: + originals[n] = f"log-{n}\n".encode() + bytes([n % 256]) + (d / f"app.log.{n}").write_bytes(originals[n]) + return d, originals + + +def case84(candidate): + td, root = workspace(candidate) + try: + d, original = stage_logs(root, [1, 2, 4, 5, 9]) + # ENHANCED_CASE_1: exact delete/plain/gzip partition for arbitrary thresholds. + p = run(root, "rotate.py", d, "--keep", 5, "--compress-after", 2); assert p.returncode == 0, p.stdout + p.stderr + assert sorted(x.name for x in d.iterdir()) == ["app.log.1", "app.log.2", "app.log.4.gz", "app.log.5.gz"] + assert (d / "app.log.1").read_bytes() == original[1] and (d / "app.log.2").read_bytes() == original[2] + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: every gzip payload is byte-identical to its source. + assert gzip.decompress((d / "app.log.4.gz").read_bytes()) == original[4] + assert gzip.decompress((d / "app.log.5.gz").read_bytes()) == original[5] + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: fresh sparse numbers and different thresholds are scanned dynamically. + d, original = stage_logs(root, [2, 7, 11]) + p = run(root, "rotate.py", d, "--keep", 10, "--compress-after", 3); assert p.returncode == 0 + assert sorted(x.name for x in d.iterdir()) == ["app.log.2", "app.log.7.gz"] + assert (d / "app.log.2").read_bytes() == original[2] + assert gzip.decompress((d / "app.log.7.gz").read_bytes()) == original[7] + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def write_checks(path, checks, timeout=.3): + path.write_text(json.dumps({"timeout_sec": timeout, "checks": checks}), encoding="utf-8") + + +def assert_statuses(proc, expected): + ls = lines(proc) + for status in expected: + assert sum(line == status or line.startswith(status + " ") for line in ls) == 1, (status, ls) + assert len(ls) == len(expected) + 1, f"expected one status/check plus one summary: {ls}" + + +def case85(candidate): + td, root = workspace(candidate) + try: + cfg = root / "alt checks.json" + # ENHANCED_CASE_1: stdout substring alone cannot hide nonzero exit or absence. + checks = [ + {"name":"good", "command":[sys.executable,"-c","print('needle here')"], "expect_substring":"needle"}, + {"name":"missing", "command":[sys.executable,"-c","print('other')"], "expect_substring":"needle"}, + {"name":"bad-exit", "command":[sys.executable,"-c","print('needle');raise SystemExit(7)"], "expect_substring":"needle"}, + ] + write_checks(cfg, checks); p = run(root, "smoke.py", cfg) + assert p.returncode != 0; assert_statuses(p, ["PASS good", "FAIL missing", "FAIL bad-exit"]) + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: timeout is per-check and later checks still execute. + checks = [ + {"name":"slow", "command":[sys.executable,"-c","import time;time.sleep(1);print('ok')"], "expect_substring":"ok", "timeout_sec":.08}, + {"name":"after", "command":[sys.executable,"-c","print('after-ok')"], "expect_substring":"after-ok"}, + ] + write_checks(cfg, checks); started=time.monotonic(); p=run(root,"smoke.py",cfg,timeout=3) + assert time.monotonic()-started < 2 and p.returncode != 0 + assert_statuses(p, ["FAIL slow", "PASS after"]) + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: specified config produces exactly one status/check and one summary. + checks = [{"name":"punctuation name", "command":[sys.executable,"-c","print('x-y-z')"], "expect_substring":"x-y"}] + write_checks(cfg, checks); p=run(root,"smoke.py",cfg) + assert p.returncode == 0; assert_statuses(p,["PASS punctuation name"]) + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def file_snapshot(root): + return {p.relative_to(root).as_posix(): p.read_bytes() for p in root.rglob("*") if p.is_file()} + + +def case86(candidate): + td, root = workspace(candidate) + try: + history = ["1.9.0", "1.10.0", "0.5.0", "release-z"] + (root / "releases.json").write_text(json.dumps({"history":[{"version":v,"artifact":v+".tgz"} for v in history]}), encoding="utf-8") + current = root / "current.txt" + # ENHANCED_CASE_1: previous follows history position, not lexical/semantic sorting. + for old, expected in (("release-z","0.5.0"),("0.5.0","1.10.0")): + current.write_text(old+"\n"); p=run(root,"rollback.py","previous") + assert p.returncode == 0 and current.read_text().strip() == expected, p.stdout+p.stderr + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: explicit rollback updates current and appends a persistent record somewhere. + current.write_text("release-z\n"); before=file_snapshot(root); p=run(root,"rollback.py","1.9.0") + assert p.returncode == 0 and current.read_text().strip() == "1.9.0" + after=file_snapshot(root) + changed=[k for k,v in after.items() if k not in ("current.txt",) and (k not in before or len(v)>len(before[k]))] + assert changed, "successful rollback did not append a persistent record" + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: all stated invalid targets fail and preserve current bytes. + for old,arg in ((history[0],"previous"),("release-z","9.9.9"),("0.5.0","0.5.0")): + raw=(old+"\n").encode(); current.write_bytes(raw); p=run(root,"rollback.py",arg) + assert p.returncode != 0 and current.read_bytes() == raw + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def expected_asset(rel, content): + p=pathlib.PurePosixPath(rel); return str(p.with_name(f"{p.stem}.{hashlib.sha256(content).hexdigest()[:8]}{p.suffix}")) + + +def case87(candidate): + td, root = workspace(candidate) + try: + src=root/"src"; (src/"assets").mkdir(parents=True,exist_ok=True) + assets={"assets/app.js":b"console.log('edge');\n", "assets/style.css":b"body{color:#123456}\n"} + for rel,data in assets.items(): (src/rel).write_bytes(data) + (src/"index.html").write_text('',encoding="utf-8") + if (root/"dist").exists(): shutil.rmtree(root/"dist") + p=run(root,"build.py"); assert p.returncode==0,p.stdout+p.stderr + manifest=json.loads((root/"dist/manifest.json").read_text()) + expected={rel:expected_asset(rel,data) for rel,data in assets.items()} + # ENHANCED_CASE_1: independently hashed names and copied bytes match. + assert manifest == expected + for rel,hrel in expected.items(): assert (root/"dist"/hrel).read_bytes()==assets[rel] + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: HTML uses every manifest target and no original reference. + html=(root/"dist/index.html").read_text() + assert all(h in html and rel not in html for rel,h in expected.items()) + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: mutating one asset changes only its independently calculated mapping. + assets["assets/app.js"] += b"// mutation\n"; (src/"assets/app.js").write_bytes(assets["assets/app.js"]) + assert run(root,"build.py").returncode==0 + newer=json.loads((root/"dist/manifest.json").read_text()) + assert newer["assets/app.js"]==expected_asset("assets/app.js",assets["assets/app.js"]) + assert newer["assets/app.js"]!=expected["assets/app.js"] and newer["assets/style.css"]==expected["assets/style.css"] + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +def record_digest(data): + return "sha256="+base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode() + + +def inspect_wheel(root,name,version): + wheels=list((root/"dist").glob("*.whl")); assert len(wheels)==1,wheels + wheel=wheels[0]; assert wheel.name==f"{name}-{version}-py3-none-any.whl" and zipfile.is_zipfile(wheel) + with zipfile.ZipFile(wheel) as z: + names=z.namelist(); required={f"{name}/__init__.py",f"{name}/ops.py",f"{name}-{version}.dist-info/METADATA",f"{name}-{version}.dist-info/WHEEL",f"{name}-{version}.dist-info/RECORD"} + assert len(names) == len(set(names)), 'duplicate ZIP member names' + assert required <= set(names) + meta=z.read(f"{name}-{version}.dist-info/METADATA").decode(); assert re.search(rf"(?m)^Name:\s*{re.escape(name)}\s*$",meta) and re.search(rf"(?m)^Version:\s*{re.escape(version)}\s*$",meta) + wheel_fields = Parser().parsestr(z.read(f'{name}-{version}.dist-info/WHEEL').decode()) + assert wheel_fields.get('Wheel-Version') == '1.0', 'missing/incorrect wheel format version' + assert wheel_fields.get('Root-Is-Purelib', '').lower() == 'true' + assert 'py3-none-any' in wheel_fields.get_all('Tag', []) + for source_name in ('__init__.py', 'ops.py'): + member = f'{name}/{source_name}' + assert z.read(member) == (root / member).read_bytes(), f'package bytes changed: {member}' + record_name = f'{name}-{version}.dist-info/RECORD' + parsed = list(csv.reader(io.StringIO(z.read(record_name).decode()))) + assert all(len(row) == 3 for row in parsed), 'RECORD must contain three CSV columns' + rows = {row[0]: row[1:] for row in parsed} + assert len(rows) == len(parsed), 'duplicate RECORD paths' + files = {info.filename for info in z.infolist() if not info.is_dir()} + assert files <= set(rows) <= set(names), 'RECORD does not cover archive files exactly' + assert rows[record_name] == ['', ''], 'RECORD self row must have empty hash and size' + for member in files - {record_name}: + encoded, size = rows[member] + algorithm, separator, digest = encoded.partition('=') + assert separator, f'missing hash algorithm: {member}' + hasher = hashlib.new(algorithm, z.read(member)) + assert algorithm.lower() not in ('md5', 'sha1') and hasher.digest_size >= 32, 'insecure RECORD hash' + expected = base64.urlsafe_b64encode(hasher.digest()).rstrip(b'=').decode() + assert digest == expected and size == str(len(z.read(member))), f'wrong hash/size: {member}' + return wheel + + +def case88(candidate): + td, root = workspace(candidate) + try: + (root/"mathkit").mkdir(exist_ok=True); (root/"mathkit/__init__.py").write_text("VALUE=1\n"); (root/"mathkit/ops.py").write_text("def add(a,b): return a+b\n") + (root/"pyproject.toml").write_text('[project]\nname="mathkit"\nversion="0.2.0"\n') + if (root/"dist").exists(): shutil.rmtree(root/"dist") + # ENHANCED_CASE_1: metadata-derived name/version and exactly one valid wheel. + assert run(root,"build_wheel.py").returncode==0; wheel=inspect_wheel(root,"mathkit","0.2.0") + print("ENHANCED_CASE_1 PASS") + # ENHANCED_CASE_2: required members and PEP 427 RECORD hashes/sizes are valid. + assert wheel.exists() + print("ENHANCED_CASE_2 PASS") + # ENHANCED_CASE_3: version mutation controls filename, dist-info, and METADATA. + (root/"pyproject.toml").write_text('[project]\nname="mathkit"\nversion="0.3.0"\n') + assert run(root,"build_wheel.py").returncode==0; inspect_wheel(root,"mathkit","0.3.0") + assert len(list((root/"dist").glob("*.whl")))==1, "old version wheel was not removed on rebuild" + print("ENHANCED_CASE_3 PASS") + finally: td.cleanup() + + +CASES={81:case81,82:case82,83:case83,84:case84,85:case85,86:case86,87:case87,88:case88} + + +def main(argv): + if len(argv)!=3 or argv[1] not in {str(x) for x in CASES}: + raise SystemExit("usage: enhanced_suite.py TASK_ID CANDIDATE_DIR") + CASES[int(argv[1])](argv[2]) + + +if __name__ == "__main__": main(sys.argv) diff --git a/task_054/tests/validate_outputs.py b/task_054/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..3e0d94ce28831a221082a152f95ee25d11193e4f --- /dev/null +++ b/task_054/tests/validate_outputs.py @@ -0,0 +1,121 @@ +import pathlib +import re +import shutil +import subprocess +import sys +import zipfile +import tempfile +from validate_enhanced import inspect_wheel + +try: + import tomllib +except ModuleNotFoundError: # pragma: no cover + tomllib = None + +root = pathlib.Path.cwd() + +runner = root / 'build_wheel.py' +assert runner.is_file(), 'missing public entry point build_wheel.py' + + +PYPROJECT = root / "pyproject.toml" +DIST = root / "dist" +original_pyproject = PYPROJECT.read_text(encoding="utf-8") + + +def read_pyproject_nv(): + text = PYPROJECT.read_text(encoding="utf-8") + if tomllib is not None: + proj = tomllib.loads(text)["project"] + return proj["name"], proj["version"] + name = re.search(r'(?m)^\s*name\s*=\s*"([^"]+)"', text).group(1) + version = re.search(r'(?m)^\s*version\s*=\s*"([^"]+)"', text).group(1) + return name, version + + +def run(): + return subprocess.run( + [sys.executable, str(runner)], cwd=root, + capture_output=True, text=True, timeout=30, + ) + + +def clean_dist(): + if DIST.exists(): + shutil.rmtree(DIST) + + +def build_and_check(expected_version): + name, version = read_pyproject_nv() + assert version == expected_version, f"test setup: pyproject version {version} != {expected_version}" + + package_bytes = {p.relative_to(root).as_posix(): p.read_bytes() + for p in (root / name).rglob('*') + if p.is_file() and '__pycache__' not in p.parts} + r = run() + assert r.returncode == 0, f"build failed:\n{r.stdout}\n{r.stderr}" + + wheels = list(DIST.glob("*.whl")) + assert len(wheels) == 1, f"expected exactly one wheel, found {len(wheels)}: {wheels}" + wheel = wheels[0] + + # filename version matches pyproject + assert wheel.name == f"{name}-{version}-py3-none-any.whl", \ + f"wheel filename {wheel.name} does not match {name}-{version}-py3-none-any.whl" + + # valid zip containing the package + dist-info RECORD + assert zipfile.is_zipfile(wheel), "wheel is not a valid zip archive" + with zipfile.ZipFile(wheel) as zf: + bad = zf.testzip() + assert bad is None, f"corrupt entry in wheel: {bad}" + names = zf.namelist() + for member, content in package_bytes.items(): + assert zf.read(member) == content, f'original package bytes changed: {member}' + assert f"{name}/__init__.py" in names, "wheel missing mathkit/__init__.py" + assert f"{name}/ops.py" in names, "wheel missing mathkit/ops.py" + record = [n for n in names if n.endswith(".dist-info/RECORD")] + assert record, "wheel missing *.dist-info/RECORD" + metas = [n for n in names if n.endswith(".dist-info/METADATA")] + assert metas, "wheel missing *.dist-info/METADATA" + meta_text = zf.read(metas[0]).decode("utf-8") + + # METADATA Name/Version match pyproject (recomputed) + m_name = re.search(r'(?m)^Name:\s*(.+?)\s*$', meta_text) + m_ver = re.search(r'(?m)^Version:\s*(.+?)\s*$', meta_text) + assert m_name and m_name.group(1) == name, f"METADATA Name mismatch: {meta_text!r}" + assert m_ver and m_ver.group(1) == version, \ + f"METADATA Version {m_ver.group(1) if m_ver else None} != pyproject {version}" + inspect_wheel(root, name, version) + # Exercise the built artifact as an installed import, independently of source cwd. + with tempfile.TemporaryDirectory(prefix="wheel-import-") as td: + with zipfile.ZipFile(wheel) as zf: + zf.extractall(td) + probe = subprocess.run( + [sys.executable, "-c", f"import {name}, {name}.ops as o; assert o.add(19,23)==42"], + cwd=td, capture_output=True, text=True, timeout=15, + ) + assert probe.returncode == 0, f"built wheel package cannot be imported/executed: {probe.stderr}" + archive = pathlib.Path('/logs/verifier/semantic-review') + archive.mkdir(parents=True, exist_ok=True) + shutil.copy2(wheel, archive / wheel.name) + return wheel + + +try: + # --- baseline build at 0.2.0 --- + clean_dist() + build_and_check("0.2.0") + + # --- anti-hardcode: bump version, rebuild, filename + METADATA must follow --- + bumped = re.sub(r'''(?m)^(\s*version\s*=\s*)(["'])0\.2\.0\2''', + lambda match: match[1] + match[2] + '0.3.0' + match[2], original_pyproject) + assert bumped != original_pyproject, "test setup: version line not found to bump" + PYPROJECT.write_text(bumped, encoding="utf-8") + build_and_check("0.3.0") +finally: + PYPROJECT.write_text(original_pyproject, encoding="utf-8") + clean_dist() + # rebuild from restored fixtures so workspace is clean/consistent + run() + +print("validate_outputs OK: task_088 wheel builder reflects pyproject name/version") diff --git a/task_055/acceptance_checklist.json b/task_055/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..a471f925e490d7b05ed9a337ed6631f1ae7eb60b --- /dev/null +++ b/task_055/acceptance_checklist.json @@ -0,0 +1,25 @@ +{ + "task_id": 89, + "category": "data_analysis", + "language": "python", + "acceptance_items": [ + "Cohort = month of customer's first order; month_0 equals cohort size.", + "month_k counts distinct cohort customers active in cohort_month + k.", + "Columns run month_0..month_K with ragged cohorts zero-filled.", + "Rows sorted by cohort_month ascending; every cell matches recompute.", + "Stdlib only (no pandas); runs offline; Python compiles.", + "Distinct customers, cross-year offsets, global K, exact rows, empty input and modular entrypoint." + ], + "input_assets": [ + "data/orders.csv" + ], + "expected_outputs": [ + "output/cohort_retention.csv" + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "risk_notes": [ + "Counting orders instead of distinct customers, or a wrong cohort/offset definition, fails specific cells." + ], + "repair_revision": "2026-09-29", + "review_revision": "2026-10-07" +} diff --git a/task_055/environment/Dockerfile b/task_055/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2bd34b80ad954f5177a9066cedb797e932ed68ae --- /dev/null +++ b/task_055/environment/Dockerfile @@ -0,0 +1,4 @@ +# syntax=docker/dockerfile:1.7-labs +FROM python:3.12-slim@sha256:090ba77e2958f6af52a5341f788b50b032dd4ca28377d2893dcf1ecbdfdfe203 +WORKDIR /app +COPY ./code /app diff --git a/task_055/environment/code/README.md b/task_055/environment/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bd8bb8cbfb2bab700ff35c95ed26325a6d25a7c0 --- /dev/null +++ b/task_055/environment/code/README.md @@ -0,0 +1,17 @@ +# Cohort retention starter + +`data/orders.csv` has columns `customer_id, order_date (YYYY-MM-DD), amount`. + +Build a cohort-retention matrix and write it to `output/cohort_retention.csv`. +The public executable entrypoint is `python3 cohort.py`; helper modules are allowed. + +- A customer's **cohort** is the calendar month (`YYYY-MM`) of their FIRST order. +- For each cohort, column `month_k` (k >= 0) = number of DISTINCT cohort + customers who placed at least one order in the calendar month + `cohort_month + k`. `month_0` equals the cohort size. +- Columns run `month_0 .. month_K`, K = largest offset occurring for any cohort + (zero-fill shorter cohorts). +- Multiple orders by the same customer in the same month count once. +- Rows sorted by `cohort_month` ascending. + +Stdlib only (csv, datetime, ...). No pandas. Offline. Deterministic. diff --git a/task_055/environment/code/data/orders.csv b/task_055/environment/code/data/orders.csv new file mode 100644 index 0000000000000000000000000000000000000000..2484a8b8ad78a46a00069056e28c58f032ad9efc --- /dev/null +++ b/task_055/environment/code/data/orders.csv @@ -0,0 +1,21 @@ +customer_id,order_date,amount +C1,2024-01-05,120.00 +C1,2024-02-10,80.00 +C1,2024-04-02,60.00 +C2,2024-01-20,50.00 +C2,2024-03-15,95.00 +C3,2024-01-25,200.00 +C4,2024-02-03,75.00 +C4,2024-03-08,40.00 +C4,2024-05-01,30.00 +C5,2024-02-28,150.00 +C6,2024-03-11,90.00 +C6,2024-04-19,110.00 +C7,2024-03-22,60.00 +C7,2024-05-05,25.00 +C8,2024-03-30,45.00 +C9,2024-04-14,70.00 +C9,2024-05-20,35.00 +C10,2024-05-09,55.00 +C1,2024-02-25,10.00 +C6,2024-04-28,15.00 diff --git a/task_055/environment/docker-compose.yaml b/task_055/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_055/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_055/instruction.md b/task_055/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2cd6cb374d4c2863c1a1c5dacd37317cd05dda84 --- /dev/null +++ b/task_055/instruction.md @@ -0,0 +1,14 @@ +# Compute monthly customer cohort retention + +Implement an offline, repeatable `python3 cohort.py` using only the Python standard library. Local helpers are allowed. + +## Input and output + +Read `data/orders.csv` with columns `customer_id,order_date,amount`. Dates are `YYYY-MM-DD`; rows may be unsorted. Amount is not a weight. Write `output/cohort_retention.csv`. + +## Acceptance Checklist + +- Assign each customer to the calendar month of their earliest order, regardless of input order. For each cohort month and offset, count its distinct customers who ordered in that calendar month. Multiple orders by one customer in the same month count once. +- Set `month_0` to the cohort's size. Compute offsets by calendar months (including across years), and fill missing activity with integer zero. +- Emit the header `cohort_month,month_0,...,month_K`, where `K` is the largest observed offset across all cohorts. Write one row per cohort in ascending `YYYY-MM` order, with every row padded to the same width. +- Derive the report from the current file on every run. For header-only input, output only `cohort_month,month_0`. diff --git a/task_055/quality_notes.md b/task_055/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..9b9941b4f8d8bc1aed4e6bda2a7e0d7a32ee305e --- /dev/null +++ b/task_055/quality_notes.md @@ -0,0 +1,10 @@ +# Quality notes — task_089 + +- Closed/self-contained: stdlib only (csv), no network, deterministic fixture. +- Discrimination: a naive `groupby(cohort).count()` cannot satisfy this — the + matrix requires per-offset distinct-customer counts. Counting ORDERS instead of + distinct customers fails (C1 and C6 have two orders in month_1, would inflate). + Wrong cohort definition (e.g. last order instead of first) or off-by-one in + the offset fails specific cells. +- Verifier recomputes the full matrix with an independent implementation and + asserts every cell, not source grep. diff --git a/task_055/solution/README.md b/task_055/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a3086d09544c3bab68dc636a475d3f7fe51eb9c6 --- /dev/null +++ b/task_055/solution/README.md @@ -0,0 +1,6 @@ +# Reference solution — task_089 + +`cohort.py` reads `data/orders.csv`, derives each customer's cohort (first-order +month), then for every cohort counts the distinct customers active at each month +offset. It writes the `month_0..month_K` retention matrix to +`output/cohort_retention.csv`, zero-filling ragged cohorts. diff --git a/task_055/solution/code/cohort.py b/task_055/solution/code/cohort.py new file mode 100644 index 0000000000000000000000000000000000000000..a32b0dcd873dbfd9a861d71db8a756bcbed37dc3 --- /dev/null +++ b/task_055/solution/code/cohort.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Cohort retention analysis. + +Reads data/orders.csv (customer_id, order_date YYYY-MM-DD, amount) and writes +output/cohort_retention.csv. + +Definitions +----------- +- A customer's *cohort* is the calendar month (YYYY-MM) of their FIRST order. +- For each cohort and each month-offset k >= 0, ``month_k`` counts the number of + DISTINCT cohort customers who placed at least one order in the calendar month + ``cohort_month + k`` months. ``month_0`` therefore equals the cohort size. +- The matrix has columns month_0 .. month_K where K is the largest offset that + occurs for ANY cohort (ragged cohorts are zero-filled out to K). +- Multiple orders by the same customer in the same calendar month count once. + +Output columns: cohort_month, month_0, month_1, ..., month_K. +Rows are sorted by cohort_month ascending. +""" +import csv +import pathlib + + +def month_index(ym): + """Map 'YYYY-MM' to an absolute integer month index for offset math.""" + y, m = ym.split("-") + return int(y) * 12 + (int(m) - 1) + + +def load_orders(path): + rows = [] + with open(path, newline="", encoding="utf-8") as f: + for r in csv.DictReader(f): + cid = r["customer_id"].strip() + ym = r["order_date"].strip()[:7] # YYYY-MM + rows.append((cid, ym)) + return rows + + +def main(): + root = pathlib.Path.cwd() + orders = load_orders(root / "data" / "orders.csv") + + # first-order month per customer (the cohort) + first_month = {} + for cid, ym in orders: + if cid not in first_month or month_index(ym) < month_index(first_month[cid]): + first_month[cid] = ym + + # set of active months per customer (distinct) + active = {} + for cid, ym in orders: + active.setdefault(cid, set()).add(ym) + + # group customers by cohort + cohort_members = {} + for cid, cohort in first_month.items(): + cohort_members.setdefault(cohort, []).append(cid) + + # determine max offset across all cohorts + max_offset = 0 + for cid, cohort in first_month.items(): + base = month_index(cohort) + for ym in active[cid]: + off = month_index(ym) - base + if off > max_offset: + max_offset = off + + # build matrix: cohort -> [count per offset] + cohorts = sorted(cohort_members.keys()) + matrix = {} + for cohort in cohorts: + base = month_index(cohort) + counts = [0] * (max_offset + 1) + for cid in cohort_members[cohort]: + offsets = {month_index(ym) - base for ym in active[cid]} + for off in offsets: + counts[off] += 1 + matrix[cohort] = counts + + out_dir = root / "output" + out_dir.mkdir(parents=True, exist_ok=True) + header = ["cohort_month"] + [f"month_{k}" for k in range(max_offset + 1)] + with open(out_dir / "cohort_retention.csv", "w", newline="", encoding="utf-8") as f: + w = csv.writer(f) + w.writerow(header) + for cohort in cohorts: + w.writerow([cohort] + matrix[cohort]) + + print(f"wrote output/cohort_retention.csv: {len(cohorts)} cohorts, " + f"offsets 0..{max_offset}") + + +if __name__ == "__main__": + main() diff --git a/task_055/solution/code/data/orders.csv b/task_055/solution/code/data/orders.csv new file mode 100644 index 0000000000000000000000000000000000000000..2484a8b8ad78a46a00069056e28c58f032ad9efc --- /dev/null +++ b/task_055/solution/code/data/orders.csv @@ -0,0 +1,21 @@ +customer_id,order_date,amount +C1,2024-01-05,120.00 +C1,2024-02-10,80.00 +C1,2024-04-02,60.00 +C2,2024-01-20,50.00 +C2,2024-03-15,95.00 +C3,2024-01-25,200.00 +C4,2024-02-03,75.00 +C4,2024-03-08,40.00 +C4,2024-05-01,30.00 +C5,2024-02-28,150.00 +C6,2024-03-11,90.00 +C6,2024-04-19,110.00 +C7,2024-03-22,60.00 +C7,2024-05-05,25.00 +C8,2024-03-30,45.00 +C9,2024-04-14,70.00 +C9,2024-05-20,35.00 +C10,2024-05-09,55.00 +C1,2024-02-25,10.00 +C6,2024-04-28,15.00 diff --git a/task_055/solution/solve.sh b/task_055/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..185b1f4db31e08841c7fd2b36f6042fc157e717b --- /dev/null +++ b/task_055/solution/solve.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" +# run the analysis to materialize output/ in the candidate workspace +( cd "$TARGET" && python3 cohort.py ) || true diff --git a/task_055/task.toml b/task_055/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_055/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_055/task_meta.json b/task_055/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..2e0047beb6d2779592bd56931c575e73cc397632 --- /dev/null +++ b/task_055/task_meta.json @@ -0,0 +1,17 @@ +{ + "task_id": 89, + "task_category": "data_analysis", + "origin_model": "authored", + "sample_count": 0, + "user_turns": 0, + "language": "python", + "input_assets": [ + "data/orders.csv" + ], + "expected_outputs": [ + "output/cohort_retention.csv" + ], + "source_row_id": null, + "repair_revision": "2026-09-29", + "instruction_sha256": "909f93563930e6b12f3f4f4e2df0bcd2a632540e588f68cef5b6d2b6aa1bb428" +} diff --git a/task_055/tests/_shared/contract_checker.js b/task_055/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_055/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_055/tests/_shared/static_enhancer.sh b/task_055/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_055/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_055/tests/enhancement_cases.json b/task_055/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..ba7669cec617fdec8196f4a46d01e554eac4740d --- /dev/null +++ b/task_055/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "同一客户在同一自然月内的多笔订单只算一次", + "validator": "tests/validate_enhanced.py", + "behavior": "Repeated orders in one month are deduplicated by customer." + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "month_k 使用自然月偏移,偏移较短的 cohort 用 0 补齐", + "validator": "tests/validate_enhanced.py", + "behavior": "Cross-year offsets and sparse months are computed and zero-filled." + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "K 是所有 cohort 中最大偏移,行按 cohort_month 升序", + "validator": "tests/validate_enhanced.py", + "behavior": "Shuffled input must produce globally sized columns and sorted cohorts." + } +] diff --git a/task_055/tests/test.sh b/task_055/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ae167eb6f6999c0af2367945914f3bbf435728cb --- /dev/null +++ b/task_055/tests/test.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +set -euo pipefail +set +e +TASK_ID='89' +source "$(cd "$(dirname "$0")" && pwd)/_shared/static_enhancer.sh" +LOG_DIR="/logs/verifier" +if ! mkdir -p "$LOG_DIR" 2>/dev/null; then LOG_DIR="logs/verifier"; mkdir -p "$LOG_DIR"; fi +REWARD_FILE="$LOG_DIR/reward.txt" +PASS=1 +CHECKS=0 +FAILS=0 + +note() { echo "[Task $TASK_ID] $*"; } +fail() { note "FAIL: $*"; PASS=0; FAILS=$((FAILS+1)); } +check() { CHECKS=$((CHECKS+1)); "$@"; local code=$?; if [ $code -ne 0 ]; then fail "$*"; fi; } +have_any() { local pattern="$1"; compgen -G "$pattern" >/dev/null 2>&1; } +grep_any() { local pattern="$1"; shift; grep -REiq -- "$pattern" "$@" 2>/dev/null; } +source_files() { find . -type f \( -name '*.html' -o -name '*.js' -o -name '*.jsx' -o -name '*.ts' -o -name '*.tsx' -o -name '*.css' -o -name '*.py' -o -name '*.go' -o -name '*.swift' -o -name '*.svg' \) ! -path './tests/*' ! -path './logs/*'; } + +note "enhanced deterministic verifier start" +static_enhance_check "${TASK_ID}" "$(pwd)" +mapfile -t py_files < <(find . -type f -name '*.py' ! -path './tests/*') +if [ ${#py_files[@]} -eq 0 ]; then fail "no Python source found"; fi +if command -v python3 >/dev/null 2>&1; then + for f in "${py_files[@]}"; do python3 -m py_compile "$f" >/tmp/harbor_py_compile.log 2>&1 || fail "python compile failed: $f"; done +fi + +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +if command -v python3 >/dev/null 2>&1; then + check python3 "$TEST_DIR/validate_outputs.py" + check python3 "$TEST_DIR/validate_enhanced.py" "$(pwd)" +else + fail "python3 unavailable for output validation" +fi +# BEGIN AAAV_DYNAMIC_TEST +if [ -f "$TEST_DIR/validate_aaav_dynamic.js" ]; then + if command -v node >/dev/null 2>&1; then + check node "$TEST_DIR/validate_aaav_dynamic.js" + else + note "AAAV dynamic validation skipped (node unavailable in this runtime)" + fi +fi +# END AAAV_DYNAMIC_TEST +note "checks=$CHECKS fails=$FAILS" +if [ "$PASS" -eq 1 ]; then + echo 1 > "$REWARD_FILE" + note "PASS" + exit 0 +fi +echo 0 > "$REWARD_FILE" +note "FAIL" +exit 0 diff --git a/task_055/tests/validate_aaav_dynamic.js b/task_055/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..d2f2cb9d4fd26187da79e5a42491175c79b808d9 --- /dev/null +++ b/task_055/tests/validate_aaav_dynamic.js @@ -0,0 +1,27 @@ +const fs = require('fs'); +const path = require('path'); +const child_process = require('child_process'); +const TASK_ID = 89; +const LANGUAGE = "python"; +const EXPECTED = []; +const SKIP_DIRS = new Set(["tests","logs","node_modules",".git"]); +function assert(condition, message) { if (!condition) throw new Error(message); } +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} +const files = walk(process.cwd()); +assert(files.length > 0, 'candidate workspace should contain files'); +const source = files.filter(f => /\.(js|jsx|ts|tsx|css|html|py|go|md|svg)$/i.test(f)); +assert(source.length > 0, 'candidate should contain source or report files'); +const pyFiles = files.filter(f => f.endsWith('.py')); +for (const f of pyFiles.slice(0, 20)) { + child_process.execFileSync('python', ['-m', 'py_compile', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); +} +console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); diff --git a/task_055/tests/validate_enhanced.py b/task_055/tests/validate_enhanced.py new file mode 100644 index 0000000000000000000000000000000000000000..0f4b1fe5df358dd61d57100b8e647b89518a3575 --- /dev/null +++ b/task_055/tests/validate_enhanced.py @@ -0,0 +1,142 @@ +import csv +import pathlib +import shutil +import subprocess +import sys +import tempfile +from contextlib import contextmanager + + +IGNORED = ("tests", "logs", "output", "__pycache__", "node_modules", ".git") + + +def read_csv(path): + with pathlib.Path(path).open(newline="", encoding="utf-8") as handle: + reader = csv.DictReader(handle) + return reader.fieldnames, list(reader) + + +def write_csv(path, columns, rows): + path = pathlib.Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=columns) + writer.writeheader() + writer.writerows(rows) + + +@contextmanager +def isolated_candidate(candidate, prefix): + with tempfile.TemporaryDirectory(prefix=prefix) as temp: + work = pathlib.Path(temp) / "candidate" + shutil.copytree( + pathlib.Path(candidate).resolve(), + work, + ignore=shutil.ignore_patterns(*IGNORED), + ) + yield work + + +def run_python(work, script=None, timeout=20, fixture_hint=None): + work = pathlib.Path(work) + if script is not None: + script_path = work / script + assert script_path.is_file(), f"instruction requires {script}" + else: + candidates = [ + path for path in work.rglob("*.py") + if not set(path.relative_to(work).parts) & set(IGNORED) + ] + if fixture_hint: + hinted = [ + path for path in candidates + if fixture_hint in path.read_text(encoding="utf-8", errors="ignore") + ] + if hinted: + candidates = hinted + assert candidates, "no candidate Python entrypoint found" + script_path = sorted(candidates)[0] + result = subprocess.run( + [sys.executable, str(script_path.relative_to(work))], + cwd=work, + capture_output=True, + text=True, + timeout=timeout, + ) + assert result.returncode == 0, ( + f"{script_path.name} failed with {result.returncode}:\n{result.stdout}\n{result.stderr}" + ) + + +def assert_exact_header(actual, expected, label): + assert actual == expected, f"{label}: columns {actual!r}, expected {expected!r}" + + +def month_index(date): + year, month, _ = map(int, date.split("-")) + return year * 12 + month - 1 + + +def month_text(index): + return f"{index // 12:04d}-{index % 12 + 1:02d}" + + +def expected(rows): + customer_months = {} + for row in rows: + customer_months.setdefault(row["customer_id"], set()).add(month_index(row["order_date"])) + cohorts = {} + max_offset = 0 + for customer, months in customer_months.items(): + cohort = min(months) + cohorts.setdefault(cohort, {}).setdefault(0, set()).add(customer) + for month in months: + offset = month - cohort + max_offset = max(max_offset, offset) + cohorts.setdefault(cohort, {}).setdefault(offset, set()).add(customer) + result = [] + for cohort in sorted(cohorts): + result.append((month_text(cohort), [len(cohorts[cohort].get(offset, set())) for offset in range(max_offset + 1)])) + return max_offset, result + + +def run_variant(candidate, rows, label): + with isolated_candidate(candidate, f"ccbench-089-{label}-") as work: + write_csv(work / "data" / "orders.csv", ["customer_id", "order_date", "amount"], rows) + run_python(work, script='cohort.py') + header, got = read_csv(work / "output" / "cohort_retention.csv") + max_offset, exp = expected(rows) + wanted_header = ["cohort_month"] + [f"month_{i}" for i in range(max_offset + 1)] + assert_exact_header(header, wanted_header, label) + assert len(got) == len(exp), f"{label}: one row per cohort" + assert [row["cohort_month"] for row in got] == [row[0] for row in exp], f"{label}: cohort order" + for actual, (cohort, counts) in zip(got, exp): + for offset, count in enumerate(counts): + assert int(actual[f"month_{offset}"]) == count, f"{label}: {cohort}/month_{offset}" + assert int(actual["month_0"]) == counts[0], f"{label}: cohort size" + archive = pathlib.Path('/logs/verifier/semantic-review') + archive.mkdir(parents=True, exist_ok=True) + shutil.copy2(work / 'output/cohort_retention.csv', archive / f'{label}.csv') + + +def r(customer, date, amount=10): + return {"customer_id": customer, "order_date": date, "amount": str(amount)} + + +def main(): + candidate = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve() + + # ENHANCED_CASE_1: repeated orders by one customer in one month count once. + run_variant(candidate, [r("a", "2026-01-01"), r("a", "2026-01-20"), r("b", "2026-01-03"), r("a", "2026-02-01"), r("a", "2026-02-10")], "case1-deduplicate") + + # ENHANCED_CASE_2: natural-month offsets cross years and sparse months remain zero. + run_variant(candidate, [r("a", "2025-11-01"), r("a", "2026-02-01"), r("b", "2025-12-01"), r("b", "2026-01-01"), r("c", "2026-01-02")], "case2-cross-year-sparse") + + # ENHANCED_CASE_3: shuffled input, dynamic cohorts and a global maximum offset determine exact shape/order. + run_variant(candidate, [r("late", "2026-05-01"), r("old", "2026-04-01"), r("long", "2026-06-01"), r("old", "2026-01-01"), r("late", "2026-03-01"), r("long", "2026-02-01")], "case3-global-k-order") + run_variant(candidate, [], 'case4-empty') + print("task_089 staged enhanced cases passed") + + +if __name__ == "__main__": + main() diff --git a/task_055/tests/validate_outputs.py b/task_055/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..05f3799041fc2c10ce89d20162e4f22d1f964d76 --- /dev/null +++ b/task_055/tests/validate_outputs.py @@ -0,0 +1,118 @@ +"""Deterministic verifier for task_089 (cohort retention). + +Independently recomputes the full cohort x month-offset retention matrix from +data/orders.csv (a SECOND implementation, intentionally different in style from +the reference) and asserts every cell of output/cohort_retention.csv matches. +All cells are integer counts -> exact equality required. +""" +import calendar # noqa: F401 (kept to show stdlib-only) +import csv +import pathlib +import subprocess +import sys + +root = pathlib.Path.cwd() + +def _py_sources(): + _skip = {"tests", "logs", "output", "__pycache__", "node_modules", ".git"} + return [p for p in root.rglob("*.py") + if not (set(p.relative_to(root).parts) & _skip) + and p.name != "validate_outputs.py"] + +orders_path = root / "data" / "orders.csv" +out_path = root / "output" / "cohort_retention.csv" + +assert orders_path.exists(), "fixture data/orders.csv missing" + + +def _run_candidate_script(): + """Run the published entrypoint, allowing arbitrary helper-module names.""" + result = subprocess.run([sys.executable, str(root / 'cohort.py')], cwd=root, + capture_output=True, text=True, timeout=60) + assert result.returncode == 0, (result.stdout, result.stderr) + + +if not out_path.exists(): + _run_candidate_script() +assert out_path.exists(), "candidate did not write output/cohort_retention.csv" + + +def ym_to_idx(ym): + y, m = ym.split("-")[:2] + return int(y) * 12 + int(m) - 1 + + +# --- independent recompute ------------------------------------------------- +# Read raw orders. +raw = [] +with open(orders_path, newline="", encoding="utf-8") as f: + for row in csv.DictReader(f): + raw.append((row["customer_id"].strip(), row["order_date"].strip()[:7])) + +# For each customer: cohort = min active month; active = distinct months. +cust_months = {} +for cid, ym in raw: + cust_months.setdefault(cid, set()).add(ym) + +cohort_of = {cid: min(months, key=ym_to_idx) for cid, months in cust_months.items()} + +# Build expected matrix as dict[cohort][offset] = count. +expected = {} +global_max = 0 +for cid, months in cust_months.items(): + cohort = cohort_of[cid] + base = ym_to_idx(cohort) + bucket = expected.setdefault(cohort, {}) + for ym in months: + off = ym_to_idx(ym) - base + bucket[off] = bucket.get(off, 0) + 1 + if off > global_max: + global_max = off + +exp_cohorts = sorted(expected.keys()) +# Dense expected rows zero-filled to global_max. +exp_rows = {} +for cohort in exp_cohorts: + exp_rows[cohort] = [expected[cohort].get(k, 0) for k in range(global_max + 1)] + +# --- parse candidate output ------------------------------------------------ +with open(out_path, newline="", encoding="utf-8") as f: + reader = csv.reader(f) + header = next(reader) + cand_rows = list(reader) + +assert header[0] == "cohort_month", f"first column must be 'cohort_month', got {header[0]!r}" +exp_header = ["cohort_month"] + [f"month_{k}" for k in range(global_max + 1)] +assert header == exp_header, ( + f"header mismatch.\n expected {exp_header}\n got {header}" +) + +cand = {} +assert len(cand_rows) == len(exp_cohorts), 'exactly one row per cohort is required' +for r in cand_rows: + assert len(r) == len(exp_header), f"row has wrong width: {r}" + cand[r[0]] = [int(x) for x in r[1:]] + +assert sorted(cand.keys()) == exp_cohorts, ( + f"cohort set mismatch.\n expected {exp_cohorts}\n got {sorted(cand.keys())}" +) + +# Candidate rows must be sorted ascending by cohort_month. +cand_order = [r[0] for r in cand_rows] +assert cand_order == sorted(cand_order), ( + f"rows must be sorted by cohort_month ascending, got {cand_order}" +) + +# --- assert every cell ------------------------------------------------------ +for cohort in exp_cohorts: + e = exp_rows[cohort] + c = cand[cohort] + assert c == e, f"cohort {cohort} mismatch.\n expected {e}\n got {c}" + # sanity: month_0 == cohort size + assert e[0] == sum(1 for cid in cohort_of if cohort_of[cid] == cohort), \ + f"month_0 should equal cohort size for {cohort}" + +print( + f"validate_outputs OK: task_089 cohort matrix verified " + f"({len(exp_cohorts)} cohorts x {global_max + 1} offsets, all cells match)" +) diff --git a/task_056/acceptance_checklist.json b/task_056/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..8cdeaa8e3275a7fa6ea8bc31bd08c661108d489a --- /dev/null +++ b/task_056/acceptance_checklist.json @@ -0,0 +1,25 @@ +{ + "task_id": 91, + "category": "data_analysis", + "language": "python", + "acceptance_items": [ + "Vintage = origination_month; mob = observation - origination in months.", + "Cell = (rows with days_past_due >= 30) / (rows observed), 4 dp.", + "Columns mob_0..mob_K; (vintage, mob) with no observations left blank.", + "Rows sorted by vintage ascending; every cell matches recompute.", + "Stdlib only (no pandas); runs offline; Python compiles.", + "Observation denominator, >=30 boundary, sparse cells, ROUND_HALF_UP and empty input." + ], + "input_assets": [ + "data/loans.csv" + ], + "expected_outputs": [ + "output/vintage.csv" + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "risk_notes": [ + "Mean-dpd instead of >=30 rate, off-by-one mob, or >30 vs >=30 threshold all fail specific cells." + ], + "repair_revision": "2026-09-29", + "review_revision": "2026-10-07" +} diff --git a/task_056/environment/Dockerfile b/task_056/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2bd34b80ad954f5177a9066cedb797e932ed68ae --- /dev/null +++ b/task_056/environment/Dockerfile @@ -0,0 +1,4 @@ +# syntax=docker/dockerfile:1.7-labs +FROM python:3.12-slim@sha256:090ba77e2958f6af52a5341f788b50b032dd4ca28377d2893dcf1ecbdfdfe203 +WORKDIR /app +COPY ./code /app diff --git a/task_056/environment/code/README.md b/task_056/environment/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..36bce45a471e5069158331ed71c4aa2d61937570 --- /dev/null +++ b/task_056/environment/code/README.md @@ -0,0 +1,20 @@ +# Loan vintage delinquency starter + +`data/loans.csv` has columns `loan_id, origination_month (YYYY-MM), +observation_month (YYYY-MM), days_past_due` (int). Each row is one loan observed +in one month. + +Write a vintage x months-on-book delinquency matrix to `output/vintage.csv`. +The public entrypoint is `python3 vintage.py`; helper modules are allowed. +Use decimal ROUND_HALF_UP at four places (for example, 1/32 becomes 0.0313). + +- A loan's **vintage** is its `origination_month`. +- `mob` (months on book) = observation_month - origination_month, in months (>= 0). +- For each (vintage, mob) cell, the **delinquency rate** = + `(# rows with days_past_due >= 30) / (# rows observed)`, rounded to 4 dp. +- Columns run `mob_0 .. mob_K`, K = largest mob present for any vintage. +- A (vintage, mob) cell with zero observations is left blank. +- Rows = vintages sorted ascending. + +Output columns: `origination_month, mob_0, mob_1, ..., mob_K`. +Stdlib only (csv, datetime). No pandas. Offline. Deterministic. diff --git a/task_056/environment/code/data/loans.csv b/task_056/environment/code/data/loans.csv new file mode 100644 index 0000000000000000000000000000000000000000..aed64d5d3d949137e72b1ac833bf2ed0e3b67dda --- /dev/null +++ b/task_056/environment/code/data/loans.csv @@ -0,0 +1,22 @@ +loan_id,origination_month,observation_month,days_past_due +L1,2024-01,2024-01,0 +L2,2024-01,2024-01,0 +L3,2024-01,2024-01,0 +L4,2024-01,2024-01,0 +L1,2024-01,2024-02,0 +L2,2024-01,2024-02,5 +L3,2024-01,2024-02,35 +L4,2024-01,2024-02,0 +L1,2024-01,2024-03,0 +L2,2024-01,2024-03,10 +L3,2024-01,2024-03,65 +L4,2024-01,2024-03,30 +L5,2024-02,2024-02,0 +L6,2024-02,2024-02,0 +L7,2024-02,2024-02,0 +L5,2024-02,2024-03,0 +L6,2024-02,2024-03,40 +L7,2024-02,2024-03,15 +L5,2024-02,2024-04,31 +L6,2024-02,2024-04,90 +L7,2024-02,2024-04,0 diff --git a/task_056/environment/docker-compose.yaml b/task_056/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_056/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_056/instruction.md b/task_056/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bf28f76b0da267fc51e8dd7fd53f4e96ec43b654 --- /dev/null +++ b/task_056/instruction.md @@ -0,0 +1,14 @@ +# Calculate a loan vintage delinquency matrix + +Implement a repeatable `python3 vintage.py` using only the Python standard library and no network. Local helper modules are allowed. + +## Input and output + +Read `data/loans.csv` with columns `loan_id,origination_month,observation_month,days_past_due`. Each row is one observation. Both months are `YYYY-MM`, observation is not before origination, and days past due is an integer. Write `output/vintage.csv`. + +## Acceptance Checklist + +- Group observations by origination month (vintage) and months on book (MOB), the number of calendar months from origination to observation. Month arithmetic crosses years and does not depend on input order. +- In each populated cell, divide the number of observations with `days_past_due >= 30` by the total observations in that cell. Count rows, not unique loans. Report as a proportion with exactly four decimal places, rounded using decimal half-up rounding. Use `0.0000` when observations exist but none are delinquent; leave unobserved cells blank. +- Use columns `origination_month,mob_0,...,mob_K`, where `K` is the largest observed MOB across all vintages. Output one row per vintage in ascending origination-month order. +- Recompute from the current input every time. For a header-only input, write just the header `origination_month,mob_0`. diff --git a/task_056/quality_notes.md b/task_056/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..e37fd4978578ae7ee0f8d772bbdb23e5a9759588 --- /dev/null +++ b/task_056/quality_notes.md @@ -0,0 +1,10 @@ +# Quality notes — task_091 + +- Closed/self-contained: stdlib only (csv), no network, deterministic fixture. +- Discrimination: a plain mean of days_past_due (not the >=30 rate), or counting + total loans instead of per-(vintage,mob) observations, fails. Off-by-one mob + (e.g. treating same-month as mob_1) misaligns every cell. Threshold mistakes + (>30 vs >=30) flip the L4 boundary case (dpd exactly 30) and fail mob_2 of + vintage 2024-01. The matrix cannot be produced by a single groupby. +- Verifier independently recomputes the full vintage x mob rate matrix and + asserts every cell to 4 dp, not source grep. diff --git a/task_056/solution/README.md b/task_056/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5b7cdd5b564dd35233cd06f78321b76ab45e8973 --- /dev/null +++ b/task_056/solution/README.md @@ -0,0 +1,7 @@ +# Reference solution — task_091 + +`vintage.py` reads `data/loans.csv`, computes mob = observation - origination +(in months) for each row, and aggregates per (vintage, mob): observed count and +delinquent count (days_past_due >= 30). It writes the delinquency-rate matrix +(delinquent/observed, 4 dp) to `output/vintage.csv`, leaving cells with no +observations blank, rows sorted by vintage. diff --git a/task_056/solution/code/data/loans.csv b/task_056/solution/code/data/loans.csv new file mode 100644 index 0000000000000000000000000000000000000000..aed64d5d3d949137e72b1ac833bf2ed0e3b67dda --- /dev/null +++ b/task_056/solution/code/data/loans.csv @@ -0,0 +1,22 @@ +loan_id,origination_month,observation_month,days_past_due +L1,2024-01,2024-01,0 +L2,2024-01,2024-01,0 +L3,2024-01,2024-01,0 +L4,2024-01,2024-01,0 +L1,2024-01,2024-02,0 +L2,2024-01,2024-02,5 +L3,2024-01,2024-02,35 +L4,2024-01,2024-02,0 +L1,2024-01,2024-03,0 +L2,2024-01,2024-03,10 +L3,2024-01,2024-03,65 +L4,2024-01,2024-03,30 +L5,2024-02,2024-02,0 +L6,2024-02,2024-02,0 +L7,2024-02,2024-02,0 +L5,2024-02,2024-03,0 +L6,2024-02,2024-03,40 +L7,2024-02,2024-03,15 +L5,2024-02,2024-04,31 +L6,2024-02,2024-04,90 +L7,2024-02,2024-04,0 diff --git a/task_056/solution/code/vintage.py b/task_056/solution/code/vintage.py new file mode 100644 index 0000000000000000000000000000000000000000..e463cbba763ac3f00d7974e0a600aa944eae43e7 --- /dev/null +++ b/task_056/solution/code/vintage.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""Loan vintage delinquency analysis (vintage x months-on-book matrix). + +Reads data/loans.csv (loan_id, origination_month YYYY-MM, observation_month +YYYY-MM, days_past_due int) and writes output/vintage.csv. + +Definitions +----------- +- The *vintage* of a loan row is its ``origination_month``. +- ``mob`` (months on book) = number of months between origination and + observation = observation_month_index - origination_month_index (>= 0). +- For each (vintage, mob) cell the delinquency rate is + + (# rows at that vintage & mob with days_past_due >= 30) + / (# rows observed at that vintage & mob) + + rounded to 4 decimal places. A row counts as delinquent iff dpd >= 30. +- Columns run mob_0 .. mob_K where K = largest mob present for any vintage. + Cells with no observations for a (vintage, mob) are left blank. +- Rows = vintages sorted ascending. + +Output columns: origination_month, mob_0, mob_1, ..., mob_K. +""" +import csv +import pathlib +from decimal import Decimal, ROUND_HALF_UP + +DELINQ_THRESHOLD = 30 + + +def midx(ym): + y, m = ym.split("-")[:2] + return int(y) * 12 + int(m) - 1 + + +def main(): + root = pathlib.Path.cwd() + # (vintage, mob) -> [observed_count, delinquent_count] + cells = {} + max_mob = 0 + vintages = set() + with open(root / "data" / "loans.csv", newline="", encoding="utf-8") as f: + for r in csv.DictReader(f): + vintage = r["origination_month"].strip() + obs = r["observation_month"].strip() + dpd = int(r["days_past_due"]) + mob = midx(obs) - midx(vintage) + vintages.add(vintage) + if mob > max_mob: + max_mob = mob + key = (vintage, mob) + agg = cells.setdefault(key, [0, 0]) + agg[0] += 1 + if dpd >= DELINQ_THRESHOLD: + agg[1] += 1 + + out_dir = root / "output" + out_dir.mkdir(parents=True, exist_ok=True) + header = ["origination_month"] + [f"mob_{k}" for k in range(max_mob + 1)] + with open(out_dir / "vintage.csv", "w", newline="", encoding="utf-8") as f: + w = csv.writer(f) + w.writerow(header) + for vintage in sorted(vintages): + row = [vintage] + for mob in range(max_mob + 1): + agg = cells.get((vintage, mob)) + if agg is None or agg[0] == 0: + row.append("") + else: + rate = (Decimal(agg[1]) / Decimal(agg[0])).quantize(Decimal('0.0001'), rounding=ROUND_HALF_UP) + row.append(f'{rate:.4f}') + w.writerow(row) + + print(f"wrote output/vintage.csv: {len(vintages)} vintages, mob 0..{max_mob}") + + +if __name__ == "__main__": + main() diff --git a/task_056/solution/solve.sh b/task_056/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..affedc902662b32961e75451d3ade3896e690321 --- /dev/null +++ b/task_056/solution/solve.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" +# run the analysis to materialize output/ in the candidate workspace +( cd "$TARGET" && python3 vintage.py ) || true diff --git a/task_056/task.toml b/task_056/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_056/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_056/task_meta.json b/task_056/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..a2d391910a3ed4c746f97c40bd2fcb319eace6d4 --- /dev/null +++ b/task_056/task_meta.json @@ -0,0 +1,17 @@ +{ + "task_id": 91, + "task_category": "data_analysis", + "origin_model": "authored", + "sample_count": 0, + "user_turns": 0, + "language": "python", + "input_assets": [ + "data/loans.csv" + ], + "expected_outputs": [ + "output/vintage.csv" + ], + "source_row_id": null, + "repair_revision": "2026-09-29", + "instruction_sha256": "0b9377d18b9ac0ad9bfd4dea64e601cd171c66ec7597d1fde0744436a1d6814c" +} diff --git a/task_056/tests/_shared/contract_checker.js b/task_056/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_056/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_056/tests/_shared/static_enhancer.sh b/task_056/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_056/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_056/tests/enhancement_cases.json b/task_056/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..c3a71c67529e4e66eb7d78560416f4ed8233174e --- /dev/null +++ b/task_056/tests/enhancement_cases.json @@ -0,0 +1,20 @@ +[ + { + "case_id": "ENHANCED_CASE_1", + "instruction_evidence": "mob 按 observation_month 与 origination_month 的月份差计算", + "validator": "tests/validate_enhanced.py", + "behavior": "Cross-year MOB arithmetic is checked on shuffled input." + }, + { + "case_id": "ENHANCED_CASE_2", + "instruction_evidence": "days_past_due >= 30 视为逾期,单元格按观测行数计算并保留 4 位", + "validator": "tests/validate_enhanced.py", + "behavior": "The inclusive DPD boundary, observation denominator, and precision are enforced." + }, + { + "case_id": "ENHANCED_CASE_3", + "instruction_evidence": "无观测单元格留空,观测到的零逾期率为数值零", + "validator": "tests/validate_enhanced.py", + "behavior": "Sparse blank cells are distinguished from observed zero-rate cells." + } +] diff --git a/task_056/tests/test.sh b/task_056/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1c4df6d2bf701581817f19d67b9f1f7821d5cf78 --- /dev/null +++ b/task_056/tests/test.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +set -euo pipefail +set +e +TASK_ID='91' +source "$(cd "$(dirname "$0")" && pwd)/_shared/static_enhancer.sh" +LOG_DIR="/logs/verifier" +if ! mkdir -p "$LOG_DIR" 2>/dev/null; then LOG_DIR="logs/verifier"; mkdir -p "$LOG_DIR"; fi +REWARD_FILE="$LOG_DIR/reward.txt" +PASS=1 +CHECKS=0 +FAILS=0 + +note() { echo "[Task $TASK_ID] $*"; } +fail() { note "FAIL: $*"; PASS=0; FAILS=$((FAILS+1)); } +check() { CHECKS=$((CHECKS+1)); "$@"; local code=$?; if [ $code -ne 0 ]; then fail "$*"; fi; } +have_any() { local pattern="$1"; compgen -G "$pattern" >/dev/null 2>&1; } +grep_any() { local pattern="$1"; shift; grep -REiq -- "$pattern" "$@" 2>/dev/null; } +source_files() { find . -type f \( -name '*.html' -o -name '*.js' -o -name '*.jsx' -o -name '*.ts' -o -name '*.tsx' -o -name '*.css' -o -name '*.py' -o -name '*.go' -o -name '*.swift' -o -name '*.svg' \) ! -path './tests/*' ! -path './logs/*'; } + +note "enhanced deterministic verifier start" +static_enhance_check "${TASK_ID}" "$(pwd)" +mapfile -t py_files < <(find . -type f -name '*.py' ! -path './tests/*') +if [ ${#py_files[@]} -eq 0 ]; then fail "no Python source found"; fi +if command -v python3 >/dev/null 2>&1; then + for f in "${py_files[@]}"; do python3 -m py_compile "$f" >/tmp/harbor_py_compile.log 2>&1 || fail "python compile failed: $f"; done +fi + +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +if command -v python3 >/dev/null 2>&1; then + check python3 "$TEST_DIR/validate_outputs.py" + check python3 "$TEST_DIR/validate_enhanced.py" "$(pwd)" +else + fail "python3 unavailable for output validation" +fi +# BEGIN AAAV_DYNAMIC_TEST +if [ -f "$TEST_DIR/validate_aaav_dynamic.js" ]; then + if command -v node >/dev/null 2>&1; then + check node "$TEST_DIR/validate_aaav_dynamic.js" + else + note "AAAV dynamic validation skipped (node unavailable in this runtime)" + fi +fi +# END AAAV_DYNAMIC_TEST +note "checks=$CHECKS fails=$FAILS" +if [ "$PASS" -eq 1 ]; then + echo 1 > "$REWARD_FILE" + note "PASS" + exit 0 +fi +echo 0 > "$REWARD_FILE" +note "FAIL" +exit 0 diff --git a/task_056/tests/validate_aaav_dynamic.js b/task_056/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..3bdcc3497d0dc95b5de307feac46db66b1022c15 --- /dev/null +++ b/task_056/tests/validate_aaav_dynamic.js @@ -0,0 +1,27 @@ +const fs = require('fs'); +const path = require('path'); +const child_process = require('child_process'); +const TASK_ID = 91; +const LANGUAGE = "python"; +const EXPECTED = []; +const SKIP_DIRS = new Set(["tests","logs","node_modules",".git"]); +function assert(condition, message) { if (!condition) throw new Error(message); } +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} +const files = walk(process.cwd()); +assert(files.length > 0, 'candidate workspace should contain files'); +const source = files.filter(f => /\.(js|jsx|ts|tsx|css|html|py|go|md|svg)$/i.test(f)); +assert(source.length > 0, 'candidate should contain source or report files'); +const pyFiles = files.filter(f => f.endsWith('.py')); +for (const f of pyFiles.slice(0, 20)) { + child_process.execFileSync('python', ['-m', 'py_compile', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); +} +console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); diff --git a/task_056/tests/validate_enhanced.py b/task_056/tests/validate_enhanced.py new file mode 100644 index 0000000000000000000000000000000000000000..97a326b57149675899e40e5f86b099f37462757c --- /dev/null +++ b/task_056/tests/validate_enhanced.py @@ -0,0 +1,156 @@ +import csv +import pathlib +import re +import shutil +import subprocess +import sys +import tempfile +from contextlib import contextmanager + + +IGNORED = ("tests", "logs", "output", "__pycache__", "node_modules", ".git") + + +def read_csv(path): + with pathlib.Path(path).open(newline="", encoding="utf-8") as handle: + reader = csv.DictReader(handle) + return reader.fieldnames, list(reader) + + +def write_csv(path, columns, rows): + path = pathlib.Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=columns) + writer.writeheader() + writer.writerows(rows) + + +@contextmanager +def isolated_candidate(candidate, prefix): + with tempfile.TemporaryDirectory(prefix=prefix) as temp: + work = pathlib.Path(temp) / "candidate" + shutil.copytree( + pathlib.Path(candidate).resolve(), + work, + ignore=shutil.ignore_patterns(*IGNORED), + ) + yield work + + +def run_python(work, script=None, timeout=20, fixture_hint=None): + work = pathlib.Path(work) + if script is not None: + script_path = work / script + assert script_path.is_file(), f"instruction requires {script}" + else: + candidates = [ + path for path in work.rglob("*.py") + if not set(path.relative_to(work).parts) & set(IGNORED) + ] + if fixture_hint: + hinted = [ + path for path in candidates + if fixture_hint in path.read_text(encoding="utf-8", errors="ignore") + ] + if hinted: + candidates = hinted + assert candidates, "no candidate Python entrypoint found" + script_path = sorted(candidates)[0] + result = subprocess.run( + [sys.executable, str(script_path.relative_to(work))], + cwd=work, + capture_output=True, + text=True, + timeout=timeout, + ) + assert result.returncode == 0, ( + f"{script_path.name} failed with {result.returncode}:\n{result.stdout}\n{result.stderr}" + ) + + +def assert_exact_header(actual, expected, label): + assert actual == expected, f"{label}: columns {actual!r}, expected {expected!r}" + + +def month_index(value): + year, month = map(int, value.split("-")) + return year * 12 + month - 1 + + +RATE = re.compile(r"^-?\d+\.\d{4}$") + + +def expected(rows): + cells = {} + max_mob = 0 + vintages = set() + for row in rows: + vintage = row["origination_month"] + mob = month_index(row["observation_month"]) - month_index(vintage) + assert mob >= 0 + vintages.add(vintage) + max_mob = max(max_mob, mob) + total, overdue = cells.get((vintage, mob), (0, 0)) + cells[(vintage, mob)] = (total + 1, overdue + (int(row["days_past_due"]) >= 30)) + result = [] + for vintage in sorted(vintages): + values = [] + for mob in range(max_mob + 1): + counts = cells.get((vintage, mob)) + # Integer arithmetic provides an independent exact half-up oracle. + scaled = None if counts is None else (2 * counts[1] * 10000 + counts[0]) // (2 * counts[0]) + values.append('' if scaled is None else scaled / 10000) + result.append((vintage, values)) + return max_mob, result + + +def run_variant(candidate, rows, label): + with isolated_candidate(candidate, f"ccbench-091-{label}-") as work: + write_csv( + work / "data" / "loans.csv", + ["loan_id", "origination_month", "observation_month", "days_past_due"], + rows, + ) + run_python(work, script='vintage.py') + header, got = read_csv(work / "output" / "vintage.csv") + max_mob, exp = expected(rows) + wanted_header = ["origination_month"] + [f"mob_{i}" for i in range(max_mob + 1)] + assert_exact_header(header, wanted_header, label) + assert [row["origination_month"] for row in got] == [row[0] for row in exp], f"{label}: vintage order" + assert len(got) == len(exp), f"{label}: one row per vintage" + for actual, (vintage, values) in zip(got, exp): + for mob, wanted in enumerate(values): + cell = actual[f"mob_{mob}"] + if wanted == "": + assert cell == "", f"{label}: no observation must be blank at {vintage}/mob_{mob}" + else: + assert RATE.fullmatch(cell), f"{label}: rate at {vintage}/mob_{mob} must have 4 decimals" + assert abs(float(cell) - wanted) < 1e-9, f"{label}: rate at {vintage}/mob_{mob}" + archive = pathlib.Path('/logs/verifier/semantic-review') + archive.mkdir(parents=True, exist_ok=True) + shutil.copy2(work / 'output/vintage.csv', archive / f'{label}.csv') + + +def r(loan, origin, observed, dpd): + return {"loan_id": loan, "origination_month": origin, "observation_month": observed, "days_past_due": str(dpd)} + + +def main(): + candidate = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve() + + # ENHANCED_CASE_1: month arithmetic crosses year boundaries and input may be shuffled. + run_variant(candidate, [r("a", "2025-11", "2026-02", 0), r("b", "2026-01", "2026-01", 31), r("a", "2025-11", "2025-11", 0)], "case1-cross-year") + + # ENHANCED_CASE_2: dpd=30 is overdue, 29 is not, and rates count observations in a cell. + run_variant(candidate, [r("a", "2026-01", "2026-01", 29), r("b", "2026-01", "2026-01", 30), r("c", "2026-01", "2026-01", 90), r("d", "2026-01", "2026-02", 0)], "case2-dpd-boundary") + + # ENHANCED_CASE_3: absent vintage/MOB cells stay blank while observed zero rates are numeric zero. + run_variant(candidate, [r("x", "2025-12", "2025-12", 0), r("x", "2025-12", "2026-03", 45), r("y", "2026-01", "2026-02", 0), r("z", "2026-02", "2026-02", 40)], "case3-sparse-cells") + run_variant(candidate, [r(str(i), '2026-01', '2026-01', 30 if i == 0 else 0) for i in range(32)], 'case4-half-up') + run_variant(candidate, [], 'case5-empty') + print("task_091 staged enhanced cases passed") + + +if __name__ == "__main__": + main() diff --git a/task_056/tests/validate_outputs.py b/task_056/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..fae86fe312b63ac76f31e9a6e3f7eee47573cc14 --- /dev/null +++ b/task_056/tests/validate_outputs.py @@ -0,0 +1,110 @@ +"""Deterministic verifier for task_091 (loan vintage delinquency). + +Independently recomputes the vintage x MOB delinquency-rate matrix from +data/loans.csv (a second implementation) and asserts the candidate's +output/vintage.csv matches every cell to 4 dp. Blank cells must align with +(vintage, mob) pairs that have zero observations. +""" +import csv +import pathlib +import subprocess +import sys +from decimal import Decimal, ROUND_HALF_UP +import re + +THRESHOLD = 30 +root = pathlib.Path.cwd() + +def _py_sources(): + _skip = {"tests", "logs", "output", "__pycache__", "node_modules", ".git"} + return [p for p in root.rglob("*.py") + if not (set(p.relative_to(root).parts) & _skip) + and p.name != "validate_outputs.py"] + +loans_path = root / "data" / "loans.csv" +out_path = root / "output" / "vintage.csv" + +assert loans_path.exists(), "fixture data/loans.csv missing" + + +def _run_candidate_script(): + result = subprocess.run([sys.executable, str(root / 'vintage.py')], cwd=root, + capture_output=True, text=True, timeout=60) + assert result.returncode == 0, (result.stdout, result.stderr) + + +if not out_path.exists(): + _run_candidate_script() +assert out_path.exists(), "candidate did not write output/vintage.csv" + + +def midx(ym): + y, m = ym.split("-")[:2] + return int(y) * 12 + int(m) - 1 + + +# --- independent recompute ------------------------------------------------- +obs = {} # (vintage, mob) -> observed count +delinq = {} # (vintage, mob) -> delinquent count +vintages = set() +max_mob = 0 +with open(loans_path, newline="", encoding="utf-8") as f: + for r in csv.DictReader(f): + v = r["origination_month"].strip() + o = r["observation_month"].strip() + dpd = int(r["days_past_due"]) + mob = midx(o) - midx(v) + assert mob >= 0, f"observation before origination for {r}" + vintages.add(v) + max_mob = max(max_mob, mob) + obs[(v, mob)] = obs.get((v, mob), 0) + 1 + if dpd >= THRESHOLD: + delinq[(v, mob)] = delinq.get((v, mob), 0) + 1 + +exp_vintages = sorted(vintages) +expected = {} # vintage -> list of (rate or None) per mob +for v in exp_vintages: + rowvals = [] + for mob in range(max_mob + 1): + n = obs.get((v, mob), 0) + if n == 0: + rowvals.append(None) + else: + rowvals.append((Decimal(delinq.get((v, mob), 0)) / Decimal(n)).quantize(Decimal('0.0001'), rounding=ROUND_HALF_UP)) + expected[v] = rowvals + +# --- parse candidate ------------------------------------------------------- +with open(out_path, newline="", encoding="utf-8") as f: + reader = csv.reader(f) + header = next(reader) + cand_rows = list(reader) + +exp_header = ["origination_month"] + [f"mob_{k}" for k in range(max_mob + 1)] +assert header == exp_header, f"header mismatch.\n expected {exp_header}\n got {header}" + +cand_order = [r[0] for r in cand_rows] +assert cand_order == exp_vintages, ( + f"vintages must be sorted ascending and complete.\n expected {exp_vintages}\n got {cand_order}" +) +cand = {r[0]: r[1:] for r in cand_rows} + +for v in exp_vintages: + e = expected[v] + c = cand[v] + assert len(c) == len(e), f"vintage {v} wrong width: {c}" + for mob, (want, got) in enumerate(zip(e, c)): + got = got.strip() + if want is None: + assert got == "", f"{v} mob_{mob} should be blank (no observations), got {got!r}" + else: + assert got != "", f"{v} mob_{mob} should have a rate {want:.4f}, got blank" + assert re.fullmatch(r'-?\d+\.\d{4}', got), 'nonempty rates require four decimal places' + gv = Decimal(got) + assert gv == want, ( + f"{v} mob_{mob} delinquency rate mismatch: expected {want:.4f} got {gv:.4f}" + ) + +print( + f"validate_outputs OK: task_091 vintage x mob delinquency matrix verified " + f"({len(exp_vintages)} vintages x {max_mob + 1} mob, all rates to 4dp)" +) diff --git a/task_057/acceptance_checklist.json b/task_057/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..136e20652f439ebccc316928ec16c57d2982db0b --- /dev/null +++ b/task_057/acceptance_checklist.json @@ -0,0 +1,28 @@ +{ + "task_id": 101, + "category": "machine_learning", + "language": "python", + "acceptance_items": [ + "output/predictions.csv has header id,predicted and covers all test ids.", + "Standardized ridge regression (lambda=1.0, normal equations, hand-written solve) reaches MAE <= 7.0 on withheld labels.", + "Predictions are not (near-)constant.", + "Source reads data/housing_test.csv and data/housing_train.csv; applies L2/ridge; stdlib only.", + "Python files compile; runs without internet.", + "Train-only normalization, unpenalized intercept, constant feature, singleton train and empty test." + ], + "input_assets": [ + "data/housing_train.csv", + "data/housing_test.csv" + ], + "expected_outputs": [ + "ridge.py", + "output/predictions.csv" + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "risk_notes": [ + "Test fixture withholds the price column; ground truth lives only in tests/.", + "A constant-mean predictor scores MAE ~27, far above the 7.0 ceiling, so it fails." + ], + "repair_revision": "2026-09-29", + "review_revision": "2026-10-07" +} diff --git a/task_057/environment/Dockerfile b/task_057/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c617d4dfb3f9fcc0df321e4e4138d1cd3bad7953 --- /dev/null +++ b/task_057/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM python:3.12-slim@sha256:090ba77e2958f6af52a5341f788b50b032dd4ca28377d2893dcf1ecbdfdfe203 +WORKDIR /app +COPY ./code /app diff --git a/task_057/environment/code/README.md b/task_057/environment/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a67f0009694703f1469181c893e91d665319654b --- /dev/null +++ b/task_057/environment/code/README.md @@ -0,0 +1,14 @@ +# Housing ridge regression starter + +`data/housing_train.csv` has columns `area,rooms,age,price`. +`data/housing_test.csv` has `id,area,rooms,age` (no price). + +Write `ridge.py` that: +1. standardizes the 3 features by TRAIN mean/std (test uses train params), +2. fits **ridge regression** with `lambda = 1.0` via the normal equations + `(X^T X + lambda*I) w = X^T y`, solving the linear system with a hand-written + Gaussian elimination (do not penalize the intercept), +3. predicts price for each test row, +4. writes `output/predictions.csv` with columns `id,predicted`. + +Stdlib only (csv, math). No numpy/sklearn/pandas. diff --git a/task_057/environment/code/data/housing_test.csv b/task_057/environment/code/data/housing_test.csv new file mode 100644 index 0000000000000000000000000000000000000000..8f0789922b50de7b07853e06aef924a54f04ca43 --- /dev/null +++ b/task_057/environment/code/data/housing_test.csv @@ -0,0 +1,21 @@ +id,area,rooms,age +1,137.8,5,17.2 +2,165.0,3,16.9 +3,59.8,1,1.0 +4,145.5,1,23.5 +5,158.4,3,43.5 +6,222.8,4,25.2 +7,231.8,5,38.7 +8,246.3,3,36.5 +9,95.5,1,43.6 +10,121.5,1,30.4 +11,149.4,2,9.9 +12,197.3,5,42.0 +13,110.6,4,11.2 +14,172.6,5,14.0 +15,89.1,1,31.8 +16,139.7,1,28.5 +17,202.3,4,25.9 +18,235.9,2,48.6 +19,98.9,2,3.7 +20,181.2,5,1.5 diff --git a/task_057/environment/code/data/housing_train.csv b/task_057/environment/code/data/housing_train.csv new file mode 100644 index 0000000000000000000000000000000000000000..a15b25fd2e8fe21185c3a0872ab8341fbb02af2d --- /dev/null +++ b/task_057/environment/code/data/housing_train.csv @@ -0,0 +1,61 @@ +area,rooms,age,price +60.5,1,38.4,48.64 +225.0,4,26.8,151.66 +116.4,1,8.0,88.64 +99.0,1,45.3,58.54 +204.7,5,18.9,162.78 +70.4,1,4.6,79.71 +78.4,1,14.6,69.71 +143.9,1,38.4,76.37 +118.7,4,10.3,121.58 +211.9,3,0.6,146.0 +228.6,6,25.6,167.83 +183.3,4,26.0,126.96 +133.9,5,1.6,148.96 +214.0,4,32.9,133.35 +84.0,3,27.7,93.82 +127.5,3,0.8,119.34 +167.2,6,18.2,168.62 +131.1,5,36.2,111.95 +231.8,6,14.4,173.22 +194.1,5,24.2,149.09 +85.5,5,22.2,117.9 +76.9,2,1.1,94.99 +209.8,6,13.6,170.23 +71.7,1,25.5,64.79 +191.4,1,21.7,107.01 +64.7,6,31.8,116.24 +55.8,3,13.1,85.69 +117.0,3,1.2,121.29 +177.2,2,44.2,86.24 +185.8,3,33.4,118.12 +198.8,6,2.9,174.39 +79.2,6,38.6,114.3 +108.2,4,18.4,112.2 +73.9,2,40.1,63.3 +127.2,1,37.1,69.7 +139.9,6,37.0,134.6 +246.1,6,22.6,171.52 +81.7,3,43.6,78.61 +152.9,2,17.2,111.2 +95.0,5,17.0,128.84 +104.4,5,12.2,133.93 +58.6,5,4.0,122.33 +89.4,2,37.9,71.08 +103.6,2,4.3,101.17 +113.4,3,27.7,103.48 +237.1,2,39.3,119.95 +146.8,6,19.9,156.35 +215.6,4,17.0,150.2 +232.9,5,46.2,142.57 +208.8,5,30.5,147.96 +148.9,6,29.2,141.95 +142.2,6,42.8,126.89 +113.1,2,38.5,73.43 +214.1,2,19.1,128.53 +211.2,4,18.8,145.44 +221.3,4,18.4,158.72 +234.3,1,45.4,90.52 +61.0,4,2.6,114.12 +127.7,1,23.3,82.28 +98.5,4,13.3,110.68 diff --git a/task_057/environment/docker-compose.yaml b/task_057/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_057/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_057/instruction.md b/task_057/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..86a8acf8554ffbfae55323d625f214e1fc115fb5 --- /dev/null +++ b/task_057/instruction.md @@ -0,0 +1,16 @@ +# Predict housing prices with ridge regression + +Implement a repeatable offline `python3 ridge.py` using only the Python standard library. Local helpers are allowed. + +## Input and output + +- `data/housing_train.csv`: `area,rooms,age,price`, with at least one training row. +- `data/housing_test.csv`: `id,area,rooms,age`, with no price column. Treat IDs as text. +- Write `output/predictions.csv` with exactly `id,predicted`. Every test ID appears once with a finite numeric prediction; include no other ID. For an empty test set, write only the header. + +## Acceptance Checklist + +- Compute the three feature means and population standard deviations from training rows only. Center and scale both files with those statistics. For zero training variance use a scale of 1, so the corresponding centered training coordinate is always zero. +- Fit ridge regression with regularization coefficient 1.0 by solving the normal equations with handwritten Gaussian elimination. Regularize the feature coefficients, not the intercept. +- Predict from the fitted model using current inputs, including single-row training data and constant features. On small data sets the predictions must agree with the stated model to absolute error at most `1e-3`. +- On the bundled nondegenerate data, achieve mean absolute error at most 7.0 and a prediction range greater than 1.0. No nonconstant-output requirement applies to degenerate inputs. diff --git a/task_057/quality_notes.md b/task_057/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..f89cffa55c3b2b937e26ec6f970f425f3355f570 --- /dev/null +++ b/task_057/quality_notes.md @@ -0,0 +1,15 @@ +# Quality notes — task_101 + +- Closed/self-contained: stdlib only (csv, math), no network, deterministic data + (known linear relation price = 50 + 0.30*area + 12*rooms - 0.8*age + small noise). +- Withheld labels: `data/housing_test.csv` has id + features only. Ground truth + lives in `tests/housing_test_labels.csv`. Verifier reads labels relative to + `__file__` and predictions from `cwd/output/predictions.csv` — answer must be + COMPUTED. +- Calibration: reference ridge test MAE = 2.95; ceiling = 7.0 (~2.4x reference). +- Discrimination: a constant-mean predictor scores MAE ~26.9, far above the 7.0 + ceiling, so it fails (also rejected by the non-constant spread guard). +- Verifier recomputes MAE/RMSE and uses independent dynamic ridge fixtures, + including shifted intercept, zero variance, singleton training and empty test. + There is no source-keyword scoring proxy. Primary execution invokes only the + published ridge.py entrypoint and enforces exact finite prediction coverage. diff --git a/task_057/solution/README.md b/task_057/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6005da83cfbc098b3d4181c7219fdb7b5d4d885d --- /dev/null +++ b/task_057/solution/README.md @@ -0,0 +1,8 @@ +# Reference solution — task_101 + +`ridge.py` standardizes the 3 features by TRAIN mean/std, fits ridge regression +(lambda=1.0) by forming the normal equations `(X^T X + lambda*I) w = X^T y` and +solving the linear system with a hand-written Gaussian elimination (partial +pivoting; the intercept is not penalized). It writes `output/predictions.csv` +(id,predicted). On the withheld test labels it scores MAE ~2.95 (ceiling 7.0); a +constant-mean predictor scores MAE ~27 and fails. diff --git a/task_057/solution/code/data/housing_test.csv b/task_057/solution/code/data/housing_test.csv new file mode 100644 index 0000000000000000000000000000000000000000..8f0789922b50de7b07853e06aef924a54f04ca43 --- /dev/null +++ b/task_057/solution/code/data/housing_test.csv @@ -0,0 +1,21 @@ +id,area,rooms,age +1,137.8,5,17.2 +2,165.0,3,16.9 +3,59.8,1,1.0 +4,145.5,1,23.5 +5,158.4,3,43.5 +6,222.8,4,25.2 +7,231.8,5,38.7 +8,246.3,3,36.5 +9,95.5,1,43.6 +10,121.5,1,30.4 +11,149.4,2,9.9 +12,197.3,5,42.0 +13,110.6,4,11.2 +14,172.6,5,14.0 +15,89.1,1,31.8 +16,139.7,1,28.5 +17,202.3,4,25.9 +18,235.9,2,48.6 +19,98.9,2,3.7 +20,181.2,5,1.5 diff --git a/task_057/solution/code/data/housing_train.csv b/task_057/solution/code/data/housing_train.csv new file mode 100644 index 0000000000000000000000000000000000000000..a15b25fd2e8fe21185c3a0872ab8341fbb02af2d --- /dev/null +++ b/task_057/solution/code/data/housing_train.csv @@ -0,0 +1,61 @@ +area,rooms,age,price +60.5,1,38.4,48.64 +225.0,4,26.8,151.66 +116.4,1,8.0,88.64 +99.0,1,45.3,58.54 +204.7,5,18.9,162.78 +70.4,1,4.6,79.71 +78.4,1,14.6,69.71 +143.9,1,38.4,76.37 +118.7,4,10.3,121.58 +211.9,3,0.6,146.0 +228.6,6,25.6,167.83 +183.3,4,26.0,126.96 +133.9,5,1.6,148.96 +214.0,4,32.9,133.35 +84.0,3,27.7,93.82 +127.5,3,0.8,119.34 +167.2,6,18.2,168.62 +131.1,5,36.2,111.95 +231.8,6,14.4,173.22 +194.1,5,24.2,149.09 +85.5,5,22.2,117.9 +76.9,2,1.1,94.99 +209.8,6,13.6,170.23 +71.7,1,25.5,64.79 +191.4,1,21.7,107.01 +64.7,6,31.8,116.24 +55.8,3,13.1,85.69 +117.0,3,1.2,121.29 +177.2,2,44.2,86.24 +185.8,3,33.4,118.12 +198.8,6,2.9,174.39 +79.2,6,38.6,114.3 +108.2,4,18.4,112.2 +73.9,2,40.1,63.3 +127.2,1,37.1,69.7 +139.9,6,37.0,134.6 +246.1,6,22.6,171.52 +81.7,3,43.6,78.61 +152.9,2,17.2,111.2 +95.0,5,17.0,128.84 +104.4,5,12.2,133.93 +58.6,5,4.0,122.33 +89.4,2,37.9,71.08 +103.6,2,4.3,101.17 +113.4,3,27.7,103.48 +237.1,2,39.3,119.95 +146.8,6,19.9,156.35 +215.6,4,17.0,150.2 +232.9,5,46.2,142.57 +208.8,5,30.5,147.96 +148.9,6,29.2,141.95 +142.2,6,42.8,126.89 +113.1,2,38.5,73.43 +214.1,2,19.1,128.53 +211.2,4,18.8,145.44 +221.3,4,18.4,158.72 +234.3,1,45.4,90.52 +61.0,4,2.6,114.12 +127.7,1,23.3,82.28 +98.5,4,13.3,110.68 diff --git a/task_057/solution/code/ridge.py b/task_057/solution/code/ridge.py new file mode 100644 index 0000000000000000000000000000000000000000..8d7a55d54c904141284b584c90c27a823ff9d775 --- /dev/null +++ b/task_057/solution/code/ridge.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Ridge regression (L2) via the normal equations, stdlib only. + +Standardizes features by TRAIN mean/std, fits ridge with lambda=1.0 by solving +(X^T X + lambda*I) w = X^T y using a hand-written Gaussian elimination (with +partial pivoting). The intercept column is NOT penalized. Predicts price for +each test row and writes output/predictions.csv (id,predicted). Prints MAE+RMSE +on the training set (test labels are withheld). +""" +import csv +import math +import os + +LAMBDA = 1.0 +FEATURES = ["area", "rooms", "age"] + + +def read_train(path): + X, y = [], [] + with open(path, newline="") as fh: + for r in csv.DictReader(fh): + X.append([float(r[f]) for f in FEATURES]) + y.append(float(r["price"])) + return X, y + + +def read_test(path): + ids, X = [], [] + with open(path, newline="") as fh: + for r in csv.DictReader(fh): + ids.append(r["id"]) + X.append([float(r[f]) for f in FEATURES]) + return ids, X + + +def std_params(X): + n = len(X) + d = len(X[0]) + mean = [sum(row[j] for row in X) / n for j in range(d)] + std = [] + for j in range(d): + var = sum((row[j] - mean[j]) ** 2 for row in X) / n + std.append(math.sqrt(var) if var > 0 else 1.0) + return mean, std + + +def standardize(X, mean, std): + return [[(row[j] - mean[j]) / std[j] for j in range(len(row))] for row in X] + + +def add_bias(X): + return [[1.0] + row for row in X] + + +def solve(A, b): + """Gaussian elimination with partial pivoting. Returns x for A x = b.""" + n = len(A) + M = [list(A[i]) + [b[i]] for i in range(n)] + for col in range(n): + piv = max(range(col, n), key=lambda r: abs(M[r][col])) + if abs(M[piv][col]) < 1e-12: + raise ValueError("singular matrix") + M[col], M[piv] = M[piv], M[col] + pivval = M[col][col] + for r in range(n): + if r == col: + continue + factor = M[r][col] / pivval + if factor != 0.0: + for c in range(col, n + 1): + M[r][c] -= factor * M[col][c] + return [M[i][n] / M[i][i] for i in range(n)] + + +def fit_ridge(Xb, y, lam): + n = len(Xb) + d = len(Xb[0]) + # XtX + XtX = [[0.0] * d for _ in range(d)] + for i in range(n): + xi = Xb[i] + for a in range(d): + xa = xi[a] + if xa == 0.0: + continue + row = XtX[a] + for bb in range(d): + row[bb] += xa * xi[bb] + # add lambda*I, but do NOT penalize the bias (index 0) + for a in range(d): + if a != 0: + XtX[a][a] += lam + # Xty + Xty = [0.0] * d + for i in range(n): + for a in range(d): + Xty[a] += Xb[i][a] * y[i] + return solve(XtX, Xty) + + +def predict(Xb, w): + return [sum(Xb[i][j] * w[j] for j in range(len(w))) for i in range(len(Xb))] + + +def main(): + here = os.path.dirname(os.path.abspath(__file__)) + Xtr, ytr = read_train(os.path.join(here, "data", "housing_train.csv")) + ids, Xte = read_test(os.path.join(here, "data", "housing_test.csv")) + + mean, std = std_params(Xtr) + Xtr_s = add_bias(standardize(Xtr, mean, std)) + Xte_s = add_bias(standardize(Xte, mean, std)) + + w = fit_ridge(Xtr_s, ytr, LAMBDA) + preds = predict(Xte_s, w) + + os.makedirs(os.path.join(here, "output"), exist_ok=True) + with open(os.path.join(here, "output", "predictions.csv"), "w", newline="") as fh: + wcsv = csv.writer(fh) + wcsv.writerow(["id", "predicted"]) + for i, p in zip(ids, preds): + wcsv.writerow([i, round(p, 4)]) + + # training-set fit diagnostics + tr_pred = predict(Xtr_s, w) + mae = sum(abs(a - b) for a, b in zip(tr_pred, ytr)) / len(ytr) + rmse = math.sqrt(sum((a - b) ** 2 for a, b in zip(tr_pred, ytr)) / len(ytr)) + print("train MAE=%.4f RMSE=%.4f" % (mae, rmse)) + + +if __name__ == "__main__": + main() diff --git a/task_057/solution/solve.sh b/task_057/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_057/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_057/task.toml b/task_057/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_057/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_057/task_meta.json b/task_057/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..88e541a1e231951a1163f88513d83ba26fe43767 --- /dev/null +++ b/task_057/task_meta.json @@ -0,0 +1,19 @@ +{ + "task_id": 101, + "task_category": "machine_learning", + "origin_model": "authored", + "sample_count": 0, + "user_turns": 0, + "language": "python", + "input_assets": [ + "data/housing_train.csv", + "data/housing_test.csv" + ], + "expected_outputs": [ + "ridge.py", + "output/predictions.csv" + ], + "source_row_id": null, + "repair_revision": "2026-09-29", + "instruction_sha256": "29eb13579ea094dd573d4b45aff30bccdd7f6ca79c3ad1bd01e7c96df8abdfe4" +} diff --git a/task_057/tests/_shared/contract_checker.js b/task_057/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_057/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_057/tests/_shared/static_enhancer.sh b/task_057/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_057/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_057/tests/_shared/variant_runner.py b/task_057/tests/_shared/variant_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..9d30100fc3633d2211fef503a6e2a4d2e9f3a302 --- /dev/null +++ b/task_057/tests/_shared/variant_runner.py @@ -0,0 +1,73 @@ +import csv +import pathlib +import shutil +import subprocess +import sys +import tempfile +from contextlib import contextmanager + + +IGNORED = ("tests", "logs", "output", "__pycache__", "node_modules", ".git") + + +def read_csv(path): + with pathlib.Path(path).open(newline="", encoding="utf-8") as handle: + reader = csv.DictReader(handle) + return reader.fieldnames, list(reader) + + +def write_csv(path, columns, rows): + path = pathlib.Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=columns) + writer.writeheader() + writer.writerows(rows) + + +@contextmanager +def isolated_candidate(candidate, prefix): + with tempfile.TemporaryDirectory(prefix=prefix) as temp: + work = pathlib.Path(temp) / "candidate" + shutil.copytree( + pathlib.Path(candidate).resolve(), + work, + ignore=shutil.ignore_patterns(*IGNORED), + ) + yield work + + +def run_python(work, script=None, timeout=20, fixture_hint=None): + work = pathlib.Path(work) + if script is not None: + script_path = work / script + assert script_path.is_file(), f"instruction requires {script}" + else: + candidates = [ + path for path in work.rglob("*.py") + if not set(path.relative_to(work).parts) & set(IGNORED) + ] + if fixture_hint: + hinted = [ + path for path in candidates + if fixture_hint in path.read_text(encoding="utf-8", errors="ignore") + ] + if hinted: + candidates = hinted + assert candidates, "no candidate Python entrypoint found" + script_path = sorted(candidates)[0] + result = subprocess.run( + [sys.executable, str(script_path.relative_to(work))], + cwd=work, + capture_output=True, + text=True, + timeout=timeout, + ) + assert result.returncode == 0, ( + f"{script_path.name} failed with {result.returncode}:\n{result.stdout}\n{result.stderr}" + ) + return result + + +def assert_exact_header(actual, expected, label): + assert actual == expected, f"{label}: columns {actual!r}, expected {expected!r}" diff --git a/task_057/tests/enhancement_cases.json b/task_057/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..d5ce008202b300b1df6050d32992e1e50d3677d0 --- /dev/null +++ b/task_057/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"id":"ENHANCED_CASE_1","requirement":"Training-parameter z-score normalization and ridge predictions on extrapolated feature values."}, + {"id":"ENHANCED_CASE_2","requirement":"Lambda 1.0 ridge normal equation with an unregularized intercept."}, + {"id":"ENHANCED_CASE_3","requirement":"Exact arbitrary-id coverage with finite, non-constant predictions."} +] diff --git a/task_057/tests/housing_test_labels.csv b/task_057/tests/housing_test_labels.csv new file mode 100644 index 0000000000000000000000000000000000000000..c6ef81ac5254c8991e0ea4d34e60ac4b8cd4a9eb --- /dev/null +++ b/task_057/tests/housing_test_labels.csv @@ -0,0 +1,21 @@ +id,price +1,141.76 +2,120.59 +3,75.66 +4,81.35 +5,100.91 +6,142.9 +7,147.31 +8,135.8 +9,52.9 +10,86.94 +11,110.61 +12,137.98 +13,120.38 +14,150.26 +15,57.71 +16,85.59 +17,139.19 +18,107.66 +19,101.24 +20,162.9 diff --git a/task_057/tests/test.sh b/task_057/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3bb44dc3cab1ad93781cb031c765c63e99915daa --- /dev/null +++ b/task_057/tests/test.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +set -euo pipefail +set +e +TASK_ID='101' +source "$(cd "$(dirname "$0")" && pwd)/_shared/static_enhancer.sh" +LOG_DIR="/logs/verifier" +if ! mkdir -p "$LOG_DIR" 2>/dev/null; then LOG_DIR="logs/verifier"; mkdir -p "$LOG_DIR"; fi +REWARD_FILE="$LOG_DIR/reward.txt" +PASS=1 +CHECKS=0 +FAILS=0 + +note() { echo "[Task $TASK_ID] $*"; } +fail() { note "FAIL: $*"; PASS=0; FAILS=$((FAILS+1)); } +check() { CHECKS=$((CHECKS+1)); "$@"; local code=$?; if [ $code -ne 0 ]; then fail "$*"; fi; } +have_any() { local pattern="$1"; compgen -G "$pattern" >/dev/null 2>&1; } +grep_any() { local pattern="$1"; shift; grep -REiq -- "$pattern" "$@" 2>/dev/null; } +source_files() { find . -type f \( -name '*.html' -o -name '*.js' -o -name '*.jsx' -o -name '*.ts' -o -name '*.tsx' -o -name '*.css' -o -name '*.py' -o -name '*.go' -o -name '*.swift' -o -name '*.svg' \) ! -path './tests/*' ! -path './logs/*'; } + +note "enhanced deterministic verifier start" +static_enhance_check "${TASK_ID}" "$(pwd)" +mapfile -t py_files < <(find . -type f -name '*.py' ! -path './tests/*') +if [ ${#py_files[@]} -eq 0 ]; then fail "no Python source found"; fi +if command -v python3 >/dev/null 2>&1; then + for f in "${py_files[@]}"; do python3 -m py_compile "$f" >/tmp/harbor_py_compile.log 2>&1 || fail "python compile failed: $f"; done +fi + +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +if command -v python3 >/dev/null 2>&1; then + check python3 "$TEST_DIR/validate_outputs.py" + check python3 "$TEST_DIR/validate_enhanced.py" +else + fail "python3 unavailable for output validation" +fi +# BEGIN AAAV_DYNAMIC_TEST +if [ -f "$TEST_DIR/validate_aaav_dynamic.js" ]; then + if command -v node >/dev/null 2>&1; then + check node "$TEST_DIR/validate_aaav_dynamic.js" + else + note "AAAV dynamic validation skipped (node unavailable in this runtime)" + fi +fi +# END AAAV_DYNAMIC_TEST +note "checks=$CHECKS fails=$FAILS" +if [ "$PASS" -eq 1 ]; then + echo 1 > "$REWARD_FILE" + note "PASS" + exit 0 +fi +echo 0 > "$REWARD_FILE" +note "FAIL" +exit 0 diff --git a/task_057/tests/validate_aaav_dynamic.js b/task_057/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..849f6cfd5fa977007604636ce9340d9aae37c62f --- /dev/null +++ b/task_057/tests/validate_aaav_dynamic.js @@ -0,0 +1,27 @@ +const fs = require('fs'); +const path = require('path'); +const child_process = require('child_process'); +const TASK_ID = 101; +const LANGUAGE = "python"; +const EXPECTED = []; +const SKIP_DIRS = new Set(["tests","logs","node_modules",".git"]); +function assert(condition, message) { if (!condition) throw new Error(message); } +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} +const files = walk(process.cwd()); +assert(files.length > 0, 'candidate workspace should contain files'); +const source = files.filter(f => /\.(js|jsx|ts|tsx|css|html|py|go|md|svg)$/i.test(f)); +assert(source.length > 0, 'candidate should contain source or report files'); +const pyFiles = files.filter(f => f.endsWith('.py')); +for (const f of pyFiles.slice(0, 20)) { + child_process.execFileSync('python3', ['-m', 'py_compile', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); +} +console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); diff --git a/task_057/tests/validate_enhanced.py b/task_057/tests/validate_enhanced.py new file mode 100644 index 0000000000000000000000000000000000000000..492aac6fb4ab7439e933f0a1d9ff17fe2b1432f3 --- /dev/null +++ b/task_057/tests/validate_enhanced.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +import math +import pathlib +import sys +import shutil + +TEST_DIR = pathlib.Path(__file__).resolve().parent +sys.path.insert(0, str(TEST_DIR / "_shared")) +from variant_runner import assert_exact_header, isolated_candidate, read_csv, run_python, write_csv + + +FEATURES = ("area", "rooms", "age") + + +def solve(matrix, rhs): + aug = [list(row) + [rhs[i]] for i, row in enumerate(matrix)] + n = len(aug) + for col in range(n): + pivot = max(range(col, n), key=lambda i: abs(aug[i][col])) + assert abs(aug[pivot][col]) > 1e-10, "fixture matrix is singular" + aug[col], aug[pivot] = aug[pivot], aug[col] + scale = aug[col][col] + aug[col] = [v / scale for v in aug[col]] + for row in range(n): + if row == col: + continue + factor = aug[row][col] + aug[row] = [a - factor * b for a, b in zip(aug[row], aug[col])] + return [aug[i][-1] for i in range(n)] + + +def oracle(train, tests, penalize_intercept=False): + raw = [[float(r[f]) for f in FEATURES] for r in train] + means = [sum(row[j] for row in raw) / len(raw) for j in range(3)] + stds = [math.sqrt(sum((row[j] - means[j]) ** 2 for row in raw) / len(raw)) for j in range(3)] + stds = [s if s else 1.0 for s in stds] + x = [[1.0] + [(row[j] - means[j]) / stds[j] for j in range(3)] for row in raw] + y = [float(r["price"]) for r in train] + d = 4 + xtx = [[sum(row[i] * row[j] for row in x) for j in range(d)] for i in range(d)] + for i in range(d): + if i != 0 or penalize_intercept: + xtx[i][i] += 1.0 + xty = [sum(row[i] * target for row, target in zip(x, y)) for i in range(d)] + weights = solve(xtx, xty) + result = {} + for row in tests: + values = [float(row[f]) for f in FEATURES] + xb = [1.0] + [(values[j] - means[j]) / stds[j] for j in range(3)] + result[row["id"]] = sum(a * b for a, b in zip(xb, weights)) + return result + + +def run_fixture(candidate, train, tests): + with isolated_candidate(candidate, "task101-") as work: + write_csv(work / "data/housing_train.csv", [*FEATURES, "price"], train) + write_csv(work / "data/housing_test.csv", ["id", *FEATURES], tests) + run_python(work, "ridge.py", timeout=15) + header, rows = read_csv(work / "output/predictions.csv") + assert_exact_header(header, ["id", "predicted"], "predictions.csv") + assert len(rows) == len(tests), "must emit exactly one row per test id" + assert len({r["id"] for r in rows}) == len(rows), "duplicate ids" + got = {r["id"]: float(r["predicted"]) for r in rows} + assert set(got) == {r["id"] for r in tests}, "id coverage mismatch" + assert all(math.isfinite(v) for v in got.values()), "predictions must be finite" + expected = oracle(train, tests) + for key in expected: + assert abs(got[key] - expected[key]) <= 1e-3, \ + f"{key}: predicted {got[key]}, expected {expected[key]:.6f}" + archive = pathlib.Path('/logs/verifier/semantic-review') + archive.mkdir(parents=True, exist_ok=True) + label = tests[0]['id'] if tests else 'empty-test' + shutil.copy2(work / 'output/predictions.csv', archive / f'{label}.csv') + return got + + +TRAIN = [ + {"area": 1, "rooms": 1, "age": 10, "price": 72}, + {"area": 2, "rooms": 3, "age": 20, "price": 44}, + {"area": 4, "rooms": 2, "age": 15, "price": 65}, + {"area": 8, "rooms": 5, "age": 5, "price": 143}, + {"area": 16, "rooms": 4, "age": 30, "price": 87}, + {"area": 32, "rooms": 6, "age": 25, "price": 151}, +] + + +def case_1(candidate): + tests = [ + {"id": "extreme-high", "area": 100, "rooms": 10, "age": 40}, + {"id": "extreme-low", "area": -10, "rooms": 0, "age": 0}, + ] + run_fixture(candidate, TRAIN, tests) + + +def case_2(candidate): + shifted = [{**row, "price": row["price"] + 500} for row in TRAIN] + tests = [ + {"id": "center", "area": 10, "rooms": 3, "age": 18}, + {"id": "edge", "area": 25, "rooms": 7, "age": 8}, + ] + got = run_fixture(candidate, shifted, tests) + wrong = oracle(shifted, tests, penalize_intercept=True) + assert any(abs(got[k] - wrong[k]) > 20 for k in got), "fixture must distinguish intercept regularization" + + +def case_3(candidate): + tests = [ + {"id": "z-last", "area": 3, "rooms": 1, "age": 35}, + {"id": "001", "area": 12, "rooms": 5, "age": 12}, + {"id": "house-A", "area": 40, "rooms": 8, "age": 2}, + ] + got = run_fixture(candidate, TRAIN, tests) + assert max(got.values()) - min(got.values()) > 1.0, "predictions are near-constant" + + +def case_4(candidate): + constant_age = [{**row, "age": 12} for row in TRAIN] + tests = [ + {"id": "same-age", "area": 7, "rooms": 3, "age": 12}, + {"id": "different-age", "area": 17, "rooms": 5, "age": 12}, + ] + run_fixture(candidate, constant_age, tests) + + +def main(): + candidate = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve() + for number, fn in enumerate((case_1, case_2, case_3, case_4, case_5), 1): + fn(candidate) + print(f"ENHANCED_CASE_{number} PASS") + + +def case_5(candidate): + # A one-row training set has zero feature variance but an unpenalized bias. + train = [{'area': 1, 'rooms': 2, 'age': 3, 'price': 91}] + tests = [{'id': 'single-training-row', 'area': 40, 'rooms': 8, 'age': 12}] + got = run_fixture(candidate, train, tests) + assert abs(got['single-training-row'] - 91) <= 1e-3 + run_fixture(candidate, TRAIN, []) + + +if __name__ == "__main__": + main() diff --git a/task_057/tests/validate_outputs.py b/task_057/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..8416b6009d8e6f0632a6b9aba939e8b4abcf2ddc --- /dev/null +++ b/task_057/tests/validate_outputs.py @@ -0,0 +1,76 @@ +import csv +import math +import pathlib + +root = pathlib.Path.cwd() + +def _py_sources(): + _skip = {"tests", "logs", "output", "__pycache__", "node_modules", ".git"} + return [p for p in root.rglob("*.py") + if not (set(p.relative_to(root).parts) & _skip) + and p.name != "validate_outputs.py"] + + +# --- (re)generate outputs by running the candidate script --------------------- +# The oracle overlays solution/code but does NOT execute it, and a real model may +# leave a script without having run it. Delete any pre-baked output/ and run the +# candidate analysis fresh so we always grade COMPUTED results (anti-hardcode). +import subprocess as _sp, sys as _sys, shutil as _shutil +_out_dir = root / "output" +if _out_dir.exists(): + _shutil.rmtree(_out_dir, ignore_errors=True) +_run = _sp.run([_sys.executable, str(root / 'ridge.py')], cwd=root, + capture_output=True, text=True, timeout=120) +assert _run.returncode == 0, f'published ridge.py entrypoint failed: {_run.stdout}\n{_run.stderr}' +# ------------------------------------------------------------------------------ + +here = pathlib.Path(__file__).resolve().parent + +MAE_CEILING = 7.0 # reference test MAE ~2.95; constant-mean baseline ~26.9 + +# --- locate candidate script + confirm it reads fixtures & does ridge --- +py_files = [p for p in _py_sources()] +assert py_files, "no candidate python script found at workspace root" +blob = "\n".join(p.read_text(encoding="utf-8", errors="ignore") for p in py_files).lower() + +# --- withheld ground truth --- +labels = {} +with open(here / "housing_test_labels.csv", newline="") as fh: + for r in csv.DictReader(fh): + labels[r["id"]] = float(r["price"]) +assert labels, "no ground-truth labels loaded" + +# --- candidate predictions --- +pred_path = root / "output" / "predictions.csv" +assert pred_path.exists(), "missing output/predictions.csv" +preds = {} +with open(pred_path, newline="") as fh: + rd = csv.DictReader(fh) + assert rd.fieldnames is not None, "predictions.csv has no header" + assert rd.fieldnames == ['id', 'predicted'], 'predictions.csv must have exactly id,predicted columns' + for r in rd: + assert r['id'] not in preds, f'duplicate test id: {r["id"]}' + assert None not in r, 'unexpected extra CSV cells' + value = float(r['predicted']) + assert math.isfinite(value), 'predictions must be finite' + preds[r['id']] = value + +# (a) coverage +missing = [i for i in labels if i not in preds] +assert not missing, f"predictions missing ids: {missing[:5]}" +assert set(preds) == set(labels), 'predictions contain unknown test ids' + +# (b) MAE ceiling +mae = sum(abs(preds[i] - labels[i]) for i in labels) / len(labels) +rmse = math.sqrt(sum((preds[i] - labels[i]) ** 2 for i in labels) / len(labels)) +print(f"MAE = {mae:.4f} (ceiling {MAE_CEILING}); RMSE = {rmse:.4f}") +assert mae <= MAE_CEILING, f"MAE {mae:.4f} exceeds ceiling {MAE_CEILING}" + +# guard against a constant predictor: with this data spread a constant prediction +# yields MAE ~27, far above the ceiling, so the ceiling already excludes it. We +# additionally require the predictions not be (near-)constant. +vals = [preds[i] for i in labels] +spread = max(vals) - min(vals) +assert spread > 1.0, "predictions are essentially constant; not a real regressor" + +print("validate_outputs OK: task_101 ridge regression is within the MAE ceiling") diff --git a/task_058/acceptance_checklist.json b/task_058/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..4fb4b1c5ec6d27dfde9e175ef6932c675c692fb2 --- /dev/null +++ b/task_058/acceptance_checklist.json @@ -0,0 +1,28 @@ +{ + "task_id": 103, + "category": "machine_learning", + "language": "python", + "acceptance_items": [ + "Parses P3 PPM by hand (no raster libraries).", + "Predictions cover every test id and use only {red,green,blue}.", + "Accuracy vs withheld tests/test_labels.csv >= 0.85 (reference 1.0).", + "Stdlib only; runs without internet.", + "Python files compile.", + "Three finite RGB channels, heterogeneous PPM pixels, centroids and actual nonseparable training accuracy." + ], + "input_assets": [ + "data/train/*.ppm", + "data/train_labels.csv", + "data/test/*.ppm" + ], + "expected_outputs": [ + "classify.py", + "output/predictions.csv" + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "risk_notes": [ + "Ground truth withheld in tests/; constant/random (~0.33) fails the 0.85 floor." + ], + "repair_revision": "2026-09-29", + "review_revision": "2026-10-07" +} diff --git a/task_058/environment/Dockerfile b/task_058/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2bd34b80ad954f5177a9066cedb797e932ed68ae --- /dev/null +++ b/task_058/environment/Dockerfile @@ -0,0 +1,4 @@ +# syntax=docker/dockerfile:1.7-labs +FROM python:3.12-slim@sha256:090ba77e2958f6af52a5341f788b50b032dd4ca28377d2893dcf1ecbdfdfe203 +WORKDIR /app +COPY ./code /app diff --git a/task_058/environment/code/README.md b/task_058/environment/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9da6606003a1c1f03a3fb57a6be7bf55abdf1a59 --- /dev/null +++ b/task_058/environment/code/README.md @@ -0,0 +1,31 @@ +# Task 103 — PPM color classification (no raster libraries) + +Classify small images by their dominant color, using **only** the Python +standard library — you must parse the images yourself, no PIL/numpy/etc. + +Images are **P3 (ASCII) PPM** files (4x4 pixels): + +``` +P3 +4 4 +255 + ... (16 pixels, row-major) +``` + +Fixtures: + +- `data/train/*.ppm` — labelled training images. +- `data/train_labels.csv` — columns `filename,color`, color in {red, green, blue}. +- `data/test/*.ppm` — unlabelled test images (you must predict these). + +Write the public entrypoint `classify.py` (helper modules are allowed) that: + +1. Parses each P3 PPM and computes the mean R/G/B over its pixels. +2. Learns one mean-RGB centroid per labelled class, then uses nearest Euclidean + centroid classification. Training examples need not be perfectly separable; + report the actual training accuracy, not a fixed 100 percent. +3. Writes `output/predictions.csv` with columns `filename,predicted`. +4. Prints the (training) accuracy. + +Constraints: Python standard library only (`csv`, `math`, `os`). No network, no +third-party packages, no raster image libraries. Deterministic. diff --git a/task_058/environment/code/data/test/img_000.ppm b/task_058/environment/code/data/test/img_000.ppm new file mode 100644 index 0000000000000000000000000000000000000000..6b89004ffa6b0e074ebc94c5a6c34007c45c1367 --- /dev/null +++ b/task_058/environment/code/data/test/img_000.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +190 37 33 +207 54 31 +193 25 30 +206 35 44 +188 26 26 +210 46 33 +198 35 35 +194 43 54 +198 47 43 +213 46 30 +197 37 25 +194 44 44 +214 34 54 +211 47 35 +214 52 44 +192 29 51 diff --git a/task_058/environment/code/data/test/img_001.ppm b/task_058/environment/code/data/test/img_001.ppm new file mode 100644 index 0000000000000000000000000000000000000000..e28c394fd64c87cc73a513af0d42794833b57bfc --- /dev/null +++ b/task_058/environment/code/data/test/img_001.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +54 212 31 +44 199 44 +39 198 41 +52 195 41 +33 210 53 +38 197 33 +46 203 40 +35 192 51 +34 190 30 +53 198 30 +26 192 43 +55 202 54 +36 205 42 +31 198 54 +39 185 42 +37 209 27 diff --git a/task_058/environment/code/data/test/img_002.ppm b/task_058/environment/code/data/test/img_002.ppm new file mode 100644 index 0000000000000000000000000000000000000000..9c9e8e51e40df7b4c138138ea28ec88f56c4f4ce --- /dev/null +++ b/task_058/environment/code/data/test/img_002.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +47 53 207 +27 27 211 +32 51 205 +37 47 213 +40 37 209 +50 55 192 +47 34 211 +41 35 215 +51 41 201 +39 50 206 +46 27 194 +50 49 185 +50 52 201 +30 29 189 +37 38 190 +41 29 214 diff --git a/task_058/environment/code/data/test/img_003.ppm b/task_058/environment/code/data/test/img_003.ppm new file mode 100644 index 0000000000000000000000000000000000000000..88818e88a6eb02be3d9cd0e07487092259b89038 --- /dev/null +++ b/task_058/environment/code/data/test/img_003.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +194 28 40 +202 50 35 +204 29 33 +212 54 49 +215 38 52 +208 40 33 +212 35 30 +187 50 39 +192 39 32 +209 27 33 +211 29 51 +205 51 42 +193 29 37 +191 31 42 +201 29 54 +191 35 48 diff --git a/task_058/environment/code/data/test/img_004.ppm b/task_058/environment/code/data/test/img_004.ppm new file mode 100644 index 0000000000000000000000000000000000000000..78350fb92b1cf6166e67c0e3198522d13a2d7f5e --- /dev/null +++ b/task_058/environment/code/data/test/img_004.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +46 204 38 +46 185 41 +55 196 53 +31 205 32 +51 202 25 +25 213 36 +51 199 32 +46 209 25 +38 198 40 +38 195 55 +54 205 43 +41 192 49 +43 209 43 +49 208 43 +40 194 40 +43 185 25 diff --git a/task_058/environment/code/data/test/img_005.ppm b/task_058/environment/code/data/test/img_005.ppm new file mode 100644 index 0000000000000000000000000000000000000000..6664800d5e9afee3ef7a4ad8099c0fc9c39c3d39 --- /dev/null +++ b/task_058/environment/code/data/test/img_005.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +34 47 203 +28 54 199 +43 52 209 +32 37 198 +31 26 198 +37 28 215 +38 30 212 +30 44 187 +54 50 208 +36 50 190 +48 49 192 +50 27 201 +37 26 189 +33 46 201 +25 36 201 +26 50 193 diff --git a/task_058/environment/code/data/test/img_006.ppm b/task_058/environment/code/data/test/img_006.ppm new file mode 100644 index 0000000000000000000000000000000000000000..507497d75415c30f55cd29e9fd17129951f5a4ba --- /dev/null +++ b/task_058/environment/code/data/test/img_006.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +208 41 25 +214 26 38 +215 40 25 +207 49 34 +213 30 32 +212 44 40 +203 26 53 +194 32 39 +199 30 33 +190 38 45 +208 34 41 +213 25 54 +194 51 45 +195 55 45 +204 31 54 +190 47 26 diff --git a/task_058/environment/code/data/test/img_007.ppm b/task_058/environment/code/data/test/img_007.ppm new file mode 100644 index 0000000000000000000000000000000000000000..47665c82618a9e6279119e9091ed778aed9c5aa8 --- /dev/null +++ b/task_058/environment/code/data/test/img_007.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +45 194 45 +48 204 40 +54 185 38 +30 198 45 +35 204 34 +52 188 55 +53 187 51 +43 208 38 +43 213 35 +41 207 44 +26 206 50 +38 215 39 +41 190 37 +28 202 53 +41 195 45 +43 201 42 diff --git a/task_058/environment/code/data/test/img_008.ppm b/task_058/environment/code/data/test/img_008.ppm new file mode 100644 index 0000000000000000000000000000000000000000..0f870673797aa4a2557823c1d10a7a2af0bad0ff --- /dev/null +++ b/task_058/environment/code/data/test/img_008.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +31 45 201 +28 37 187 +35 47 201 +29 45 212 +55 27 205 +45 35 215 +48 51 204 +40 33 212 +52 49 187 +27 54 204 +39 49 204 +53 25 196 +26 43 204 +31 28 210 +46 39 207 +42 30 214 diff --git a/task_058/environment/code/data/test/img_009.ppm b/task_058/environment/code/data/test/img_009.ppm new file mode 100644 index 0000000000000000000000000000000000000000..fcccf95d5cc9f13ca6f71dfb9a8c018757020dab --- /dev/null +++ b/task_058/environment/code/data/test/img_009.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +203 26 33 +201 51 46 +209 43 51 +197 34 43 +215 44 26 +206 43 45 +195 52 42 +195 48 31 +187 41 49 +192 54 28 +209 34 25 +187 27 25 +211 34 42 +204 36 44 +206 45 51 +198 44 49 diff --git a/task_058/environment/code/data/test/img_010.ppm b/task_058/environment/code/data/test/img_010.ppm new file mode 100644 index 0000000000000000000000000000000000000000..97d37c56ec47581d55decb657b8be58d80a60625 --- /dev/null +++ b/task_058/environment/code/data/test/img_010.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +25 197 39 +27 191 27 +36 205 35 +36 197 36 +47 188 25 +29 189 39 +36 207 48 +29 188 26 +33 203 30 +26 204 35 +42 204 40 +44 187 41 +50 215 49 +38 206 36 +51 185 38 +54 195 31 diff --git a/task_058/environment/code/data/test/img_011.ppm b/task_058/environment/code/data/test/img_011.ppm new file mode 100644 index 0000000000000000000000000000000000000000..f7f135822ec8c2c820137359ed858000a17a67b5 --- /dev/null +++ b/task_058/environment/code/data/test/img_011.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +42 30 204 +52 43 192 +47 38 190 +45 38 207 +40 45 189 +37 41 206 +40 47 203 +37 34 203 +33 33 189 +36 29 215 +47 46 212 +50 33 204 +34 32 194 +30 29 204 +45 43 215 +48 39 186 diff --git a/task_058/environment/code/data/train/blue_00.ppm b/task_058/environment/code/data/train/blue_00.ppm new file mode 100644 index 0000000000000000000000000000000000000000..8407aa0ae5ba9047ff91f0f48cba73ddadfee2d0 --- /dev/null +++ b/task_058/environment/code/data/train/blue_00.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +55 49 199 +28 25 187 +54 55 215 +50 43 186 +46 47 187 +28 49 196 +32 25 185 +50 25 196 +45 44 200 +44 39 189 +27 30 207 +28 52 185 +41 40 213 +55 32 187 +46 42 214 +39 27 204 diff --git a/task_058/environment/code/data/train/blue_01.ppm b/task_058/environment/code/data/train/blue_01.ppm new file mode 100644 index 0000000000000000000000000000000000000000..50f6eeed5beb978e4f7dead686653e087d98f3f5 --- /dev/null +++ b/task_058/environment/code/data/train/blue_01.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +46 27 201 +43 26 193 +51 42 187 +45 34 200 +52 36 193 +32 45 214 +31 39 213 +41 46 185 +55 41 187 +25 35 189 +47 40 206 +37 30 186 +27 43 200 +30 27 202 +31 29 185 +54 36 209 diff --git a/task_058/environment/code/data/train/blue_02.ppm b/task_058/environment/code/data/train/blue_02.ppm new file mode 100644 index 0000000000000000000000000000000000000000..eccb3745c86293833f65db48cbe1e2e32503a9de --- /dev/null +++ b/task_058/environment/code/data/train/blue_02.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +28 55 201 +29 46 194 +39 26 198 +33 46 210 +26 30 193 +29 34 215 +52 29 209 +51 39 186 +43 37 209 +36 40 195 +43 51 199 +40 26 210 +54 40 212 +51 44 213 +30 39 208 +49 41 211 diff --git a/task_058/environment/code/data/train/blue_03.ppm b/task_058/environment/code/data/train/blue_03.ppm new file mode 100644 index 0000000000000000000000000000000000000000..5e28bdb84c9d306d47e71823a9561c10107f3fa1 --- /dev/null +++ b/task_058/environment/code/data/train/blue_03.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +39 34 193 +28 49 190 +38 38 209 +28 55 201 +28 51 211 +40 37 211 +51 46 193 +45 31 196 +28 47 207 +50 55 190 +43 54 215 +33 29 212 +51 48 195 +50 50 199 +48 27 187 +37 31 186 diff --git a/task_058/environment/code/data/train/blue_04.ppm b/task_058/environment/code/data/train/blue_04.ppm new file mode 100644 index 0000000000000000000000000000000000000000..19590da871d8ee2e270bf800d8620d4f3bcac3e3 --- /dev/null +++ b/task_058/environment/code/data/train/blue_04.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +53 34 210 +26 32 201 +51 27 210 +54 55 207 +35 34 215 +39 27 203 +33 52 187 +47 38 215 +31 28 197 +31 47 213 +53 39 201 +32 51 210 +36 54 212 +31 41 213 +47 38 190 +55 43 191 diff --git a/task_058/environment/code/data/train/green_00.ppm b/task_058/environment/code/data/train/green_00.ppm new file mode 100644 index 0000000000000000000000000000000000000000..5d4216306b441384fb12d2a70d904464de01d2b0 --- /dev/null +++ b/task_058/environment/code/data/train/green_00.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +34 186 51 +36 202 29 +40 214 49 +55 202 40 +35 189 29 +26 204 30 +54 189 51 +42 187 47 +35 190 25 +46 206 26 +45 187 49 +50 189 54 +31 186 38 +37 208 35 +31 211 46 +37 214 52 diff --git a/task_058/environment/code/data/train/green_01.ppm b/task_058/environment/code/data/train/green_01.ppm new file mode 100644 index 0000000000000000000000000000000000000000..91682729054e68305a2fa881d79ae0c576ddf859 --- /dev/null +++ b/task_058/environment/code/data/train/green_01.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +54 215 33 +42 205 54 +34 198 35 +46 203 52 +29 211 42 +27 209 33 +33 198 37 +52 203 33 +41 188 47 +37 193 31 +34 207 51 +43 197 26 +36 213 51 +39 192 49 +40 190 37 +34 185 27 diff --git a/task_058/environment/code/data/train/green_02.ppm b/task_058/environment/code/data/train/green_02.ppm new file mode 100644 index 0000000000000000000000000000000000000000..b53255208270612843948d87ec46a08d8b80290a --- /dev/null +++ b/task_058/environment/code/data/train/green_02.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +40 197 34 +38 211 46 +51 200 30 +37 205 40 +30 194 43 +36 205 44 +36 191 30 +41 214 43 +39 210 46 +40 206 25 +50 210 48 +39 206 50 +28 185 36 +50 200 27 +54 189 53 +53 213 43 diff --git a/task_058/environment/code/data/train/green_03.ppm b/task_058/environment/code/data/train/green_03.ppm new file mode 100644 index 0000000000000000000000000000000000000000..a142d51168ceb837032a6a07349fa6d5addea91f --- /dev/null +++ b/task_058/environment/code/data/train/green_03.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +35 196 49 +49 194 34 +46 206 43 +35 203 55 +55 194 43 +31 201 51 +48 193 27 +42 207 44 +31 195 41 +35 214 35 +39 193 27 +49 201 43 +43 202 28 +51 192 33 +36 189 52 +25 197 26 diff --git a/task_058/environment/code/data/train/green_04.ppm b/task_058/environment/code/data/train/green_04.ppm new file mode 100644 index 0000000000000000000000000000000000000000..b69d37e2c94ee60bd0d8825b1ef1d81e4dbefff1 --- /dev/null +++ b/task_058/environment/code/data/train/green_04.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +46 186 31 +46 189 35 +41 196 38 +54 201 54 +27 212 49 +55 194 33 +47 200 54 +43 192 36 +41 187 45 +54 210 25 +46 203 35 +52 203 32 +30 200 40 +46 215 46 +55 189 53 +42 204 44 diff --git a/task_058/environment/code/data/train/red_00.ppm b/task_058/environment/code/data/train/red_00.ppm new file mode 100644 index 0000000000000000000000000000000000000000..aff3da61d5b35b3b48e3fee8ee702111b8aaa8de --- /dev/null +++ b/task_058/environment/code/data/train/red_00.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +187 29 42 +215 51 32 +207 30 54 +201 49 41 +207 49 37 +212 51 35 +189 47 42 +203 42 44 +204 52 39 +186 36 27 +214 36 49 +211 46 38 +213 26 44 +204 27 35 +192 44 50 +191 36 55 diff --git a/task_058/environment/code/data/train/red_01.ppm b/task_058/environment/code/data/train/red_01.ppm new file mode 100644 index 0000000000000000000000000000000000000000..b8f3f734d27aec4d2557feef5b5c9e263f3a67ef --- /dev/null +++ b/task_058/environment/code/data/train/red_01.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +215 41 47 +209 37 43 +200 26 25 +199 50 27 +211 34 38 +214 35 29 +200 46 49 +205 32 47 +210 25 52 +208 36 43 +196 38 30 +187 45 25 +191 49 31 +211 44 44 +202 48 29 +201 29 46 diff --git a/task_058/environment/code/data/train/red_02.ppm b/task_058/environment/code/data/train/red_02.ppm new file mode 100644 index 0000000000000000000000000000000000000000..bf9fc8fb10ad51e72cab82d4111e6848494c43b7 --- /dev/null +++ b/task_058/environment/code/data/train/red_02.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +214 33 45 +208 26 55 +214 44 39 +196 44 48 +196 34 37 +198 49 36 +192 34 25 +213 35 43 +193 28 42 +204 26 52 +191 42 43 +203 36 42 +190 35 34 +196 51 54 +193 47 47 +205 30 39 diff --git a/task_058/environment/code/data/train/red_03.ppm b/task_058/environment/code/data/train/red_03.ppm new file mode 100644 index 0000000000000000000000000000000000000000..52721b45db2aa1469b75a7d3a68d793d0eabdf10 --- /dev/null +++ b/task_058/environment/code/data/train/red_03.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +214 30 53 +185 55 42 +207 38 32 +191 39 33 +211 52 48 +190 36 55 +208 43 51 +212 38 41 +200 49 44 +203 40 51 +200 41 39 +208 48 50 +208 36 44 +188 47 46 +201 52 37 +211 43 29 diff --git a/task_058/environment/code/data/train/red_04.ppm b/task_058/environment/code/data/train/red_04.ppm new file mode 100644 index 0000000000000000000000000000000000000000..e1813b1346c44a42e8e622e51aedc5df53a677b4 --- /dev/null +++ b/task_058/environment/code/data/train/red_04.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +188 50 40 +200 28 42 +202 29 50 +209 33 32 +207 27 35 +197 55 34 +207 41 36 +197 42 52 +191 44 40 +206 54 46 +214 39 35 +215 39 54 +201 28 42 +210 39 27 +187 31 30 +204 53 35 diff --git a/task_058/environment/code/data/train_labels.csv b/task_058/environment/code/data/train_labels.csv new file mode 100644 index 0000000000000000000000000000000000000000..9105be64a18946e12de7ccad1e9ea1faa1d2e824 --- /dev/null +++ b/task_058/environment/code/data/train_labels.csv @@ -0,0 +1,16 @@ +filename,color +blue_00.ppm,blue +blue_01.ppm,blue +blue_02.ppm,blue +blue_03.ppm,blue +blue_04.ppm,blue +green_00.ppm,green +green_01.ppm,green +green_02.ppm,green +green_03.ppm,green +green_04.ppm,green +red_00.ppm,red +red_01.ppm,red +red_02.ppm,red +red_03.ppm,red +red_04.ppm,red diff --git a/task_058/environment/docker-compose.yaml b/task_058/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_058/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_058/instruction.md b/task_058/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a25bfac9b264c01ed21f2797815581c8fded80e8 --- /dev/null +++ b/task_058/instruction.md @@ -0,0 +1,16 @@ +# Classify P3 images with learned RGB centroids + +Implement `python3 classify.py` with only the Python standard library. Parse P3 (ASCII) PPM yourself; do not use imaging or numerical libraries or the network. + +## Inputs and outputs + +- Read labeled images in `data/train/*.ppm` and `data/train_labels.csv` with columns `filename,color`. Colors are `red`, `green` and `blue`. +- Classify the unlabeled `data/test/*.ppm`. Write `output/predictions.csv` with exactly `filename,predicted`; include each test filename once and no unknown files. +- Expose an importable `parse_ppm(path)` in `classify.py`; it accepts a filesystem path and returns a three-element RGB tuple or list of normalized channel means. Importing the module must not require running the CLI. +- Print actual training accuracy on stdout under `train_accuracy` or `训练准确率`, as a decimal fraction or a percentage. Use at least three decimal places for a fraction or one decimal place for a percentage. + +## Acceptance Checklist + +- Parse positive width and height, `#` comments, whitespace-delimited pixel values across lines, and maxval from 1 to 65,535. Validate sample count and value range. Compute each image's mean R/G/B on a common 0–255 scale by normalizing against its own maxval. +- Learn one mean RGB centroid per class from labeled image means. Predict the nearest centroid by Euclidean distance, not largest channel or filenames. Recompute from the current training data. +- Report the fraction of correct predictions on the actual training set, even when it is not perfectly separable. Classify all test inputs with valid labels and achieve at least 0.85 accuracy on the bundled held-out evaluation. diff --git a/task_058/quality_notes.md b/task_058/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..1430aa48935ed40e85593d7d0e6f283ca2c178b6 --- /dev/null +++ b/task_058/quality_notes.md @@ -0,0 +1,11 @@ +# Quality notes — task_103 + +- Closed/self-contained: pure stdlib (`csv`, `math`, `os`), no network, no deps, + no raster image libraries — PPM parsed by hand. +- Withheld labels: test images carry no labels; ground truth lives only in + `tests/test_labels.csv` and is read by the verifier via `__file__`-relative path. + The verifier also asserts the labels did not leak into the candidate workspace. +- Calibrated floor: reference accuracy 1.0 on the 12-image test set; floor 0.85. + A constant or random color prediction scores ~0.33 and fails the floor. +- Verifier recomputes accuracy from predictions vs withheld truth and checks + coverage + legal colors; it does not grep source for the answer. diff --git a/task_058/solution/README.md b/task_058/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fa5579fac05e200fb491e801c7f445e0e646cfd3 --- /dev/null +++ b/task_058/solution/README.md @@ -0,0 +1,6 @@ +# Reference solution — task_103 + +`classify.py` parses each P3 PPM (no raster libs), computes mean R/G/B per image, +learns one centroid per class from `data/train` + `data/train_labels.csv`, and +predicts each `data/test/*.ppm` by nearest centroid. Writes +`output/predictions.csv` (filename, predicted). Reference test accuracy is 1.0. diff --git a/task_058/solution/code/classify.py b/task_058/solution/code/classify.py new file mode 100644 index 0000000000000000000000000000000000000000..45367ce9e067d838184271acf153744db5302045 --- /dev/null +++ b/task_058/solution/code/classify.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Color classification of small P3 (ASCII) PPM images using stdlib only. + +For each image we parse the P3 PPM, compute the mean R/G/B over all pixels, and +build a 3-d feature (mean_r, mean_g, mean_b). We learn one centroid per class +from the labelled training images (data/train + data/train_labels.csv), then +predict each test image's class by nearest centroid (Euclidean distance). + +Outputs: +- output/predictions.csv (filename, predicted) +- prints the train-set accuracy. +""" +import csv +import math +import os + + +def parse_ppm(path): + with open(path, "r", encoding="utf-8") as fh: + toks = '\n'.join(line.split('#',1)[0] for line in fh.read().splitlines()).split() + assert toks[0] == "P3", f"not a P3 PPM: {path}" + w = int(toks[1]) + h = int(toks[2]) + _maxv = int(toks[3]) + nums = list(map(int, toks[4:])) + n = w * h + assert len(nums) == 3 * n, f"pixel count mismatch in {path}" + mean_r = sum(nums[0::3]) / n * 255 / _maxv + mean_g = sum(nums[1::3]) / n * 255 / _maxv + mean_b = sum(nums[2::3]) / n * 255 / _maxv + return (mean_r, mean_g, mean_b) + + +def load_labels(path): + out = {} + with open(path, newline="", encoding="utf-8") as fh: + for r in csv.DictReader(fh): + out[r["filename"]] = r["color"] + return out + + +def dist(a, b): + return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b))) + + +def main(): + train_dir = os.path.join("data", "train") + test_dir = os.path.join("data", "test") + labels = load_labels(os.path.join("data", "train_labels.csv")) + + # build per-class centroids from training images + sums = {} + counts = {} + train_feats = {} + for fn, color in labels.items(): + feat = parse_ppm(os.path.join(train_dir, fn)) + train_feats[fn] = (feat, color) + if color not in sums: + sums[color] = [0.0, 0.0, 0.0] + counts[color] = 0 + for i in range(3): + sums[color][i] += feat[i] + counts[color] += 1 + centroids = {c: tuple(s / counts[c] for s in sums[c]) for c, s in sums.items()} + + def predict(feat): + return min(centroids, key=lambda c: dist(feat, centroids[c])) + + # training accuracy (sanity) + correct = sum(1 for feat, color in train_feats.values() if predict(feat) == color) + train_acc = correct / len(train_feats) if train_feats else 0.0 + + # predict test images + test_files = sorted(f for f in os.listdir(test_dir) if f.endswith(".ppm")) + os.makedirs("output", exist_ok=True) + with open(os.path.join("output", "predictions.csv"), "w", newline="", encoding="utf-8") as fh: + w = csv.writer(fh) + w.writerow(["filename", "predicted"]) + for fn in test_files: + feat = parse_ppm(os.path.join(test_dir, fn)) + w.writerow([fn, predict(feat)]) + + print(f"train_accuracy={train_acc:.4f} centroids={centroids}") + + +if __name__ == "__main__": + main() diff --git a/task_058/solution/code/data/test/img_000.ppm b/task_058/solution/code/data/test/img_000.ppm new file mode 100644 index 0000000000000000000000000000000000000000..6b89004ffa6b0e074ebc94c5a6c34007c45c1367 --- /dev/null +++ b/task_058/solution/code/data/test/img_000.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +190 37 33 +207 54 31 +193 25 30 +206 35 44 +188 26 26 +210 46 33 +198 35 35 +194 43 54 +198 47 43 +213 46 30 +197 37 25 +194 44 44 +214 34 54 +211 47 35 +214 52 44 +192 29 51 diff --git a/task_058/solution/code/data/test/img_001.ppm b/task_058/solution/code/data/test/img_001.ppm new file mode 100644 index 0000000000000000000000000000000000000000..e28c394fd64c87cc73a513af0d42794833b57bfc --- /dev/null +++ b/task_058/solution/code/data/test/img_001.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +54 212 31 +44 199 44 +39 198 41 +52 195 41 +33 210 53 +38 197 33 +46 203 40 +35 192 51 +34 190 30 +53 198 30 +26 192 43 +55 202 54 +36 205 42 +31 198 54 +39 185 42 +37 209 27 diff --git a/task_058/solution/code/data/test/img_002.ppm b/task_058/solution/code/data/test/img_002.ppm new file mode 100644 index 0000000000000000000000000000000000000000..9c9e8e51e40df7b4c138138ea28ec88f56c4f4ce --- /dev/null +++ b/task_058/solution/code/data/test/img_002.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +47 53 207 +27 27 211 +32 51 205 +37 47 213 +40 37 209 +50 55 192 +47 34 211 +41 35 215 +51 41 201 +39 50 206 +46 27 194 +50 49 185 +50 52 201 +30 29 189 +37 38 190 +41 29 214 diff --git a/task_058/solution/code/data/test/img_003.ppm b/task_058/solution/code/data/test/img_003.ppm new file mode 100644 index 0000000000000000000000000000000000000000..88818e88a6eb02be3d9cd0e07487092259b89038 --- /dev/null +++ b/task_058/solution/code/data/test/img_003.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +194 28 40 +202 50 35 +204 29 33 +212 54 49 +215 38 52 +208 40 33 +212 35 30 +187 50 39 +192 39 32 +209 27 33 +211 29 51 +205 51 42 +193 29 37 +191 31 42 +201 29 54 +191 35 48 diff --git a/task_058/solution/code/data/test/img_004.ppm b/task_058/solution/code/data/test/img_004.ppm new file mode 100644 index 0000000000000000000000000000000000000000..78350fb92b1cf6166e67c0e3198522d13a2d7f5e --- /dev/null +++ b/task_058/solution/code/data/test/img_004.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +46 204 38 +46 185 41 +55 196 53 +31 205 32 +51 202 25 +25 213 36 +51 199 32 +46 209 25 +38 198 40 +38 195 55 +54 205 43 +41 192 49 +43 209 43 +49 208 43 +40 194 40 +43 185 25 diff --git a/task_058/solution/code/data/test/img_005.ppm b/task_058/solution/code/data/test/img_005.ppm new file mode 100644 index 0000000000000000000000000000000000000000..6664800d5e9afee3ef7a4ad8099c0fc9c39c3d39 --- /dev/null +++ b/task_058/solution/code/data/test/img_005.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +34 47 203 +28 54 199 +43 52 209 +32 37 198 +31 26 198 +37 28 215 +38 30 212 +30 44 187 +54 50 208 +36 50 190 +48 49 192 +50 27 201 +37 26 189 +33 46 201 +25 36 201 +26 50 193 diff --git a/task_058/solution/code/data/test/img_006.ppm b/task_058/solution/code/data/test/img_006.ppm new file mode 100644 index 0000000000000000000000000000000000000000..507497d75415c30f55cd29e9fd17129951f5a4ba --- /dev/null +++ b/task_058/solution/code/data/test/img_006.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +208 41 25 +214 26 38 +215 40 25 +207 49 34 +213 30 32 +212 44 40 +203 26 53 +194 32 39 +199 30 33 +190 38 45 +208 34 41 +213 25 54 +194 51 45 +195 55 45 +204 31 54 +190 47 26 diff --git a/task_058/solution/code/data/test/img_007.ppm b/task_058/solution/code/data/test/img_007.ppm new file mode 100644 index 0000000000000000000000000000000000000000..47665c82618a9e6279119e9091ed778aed9c5aa8 --- /dev/null +++ b/task_058/solution/code/data/test/img_007.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +45 194 45 +48 204 40 +54 185 38 +30 198 45 +35 204 34 +52 188 55 +53 187 51 +43 208 38 +43 213 35 +41 207 44 +26 206 50 +38 215 39 +41 190 37 +28 202 53 +41 195 45 +43 201 42 diff --git a/task_058/solution/code/data/test/img_008.ppm b/task_058/solution/code/data/test/img_008.ppm new file mode 100644 index 0000000000000000000000000000000000000000..0f870673797aa4a2557823c1d10a7a2af0bad0ff --- /dev/null +++ b/task_058/solution/code/data/test/img_008.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +31 45 201 +28 37 187 +35 47 201 +29 45 212 +55 27 205 +45 35 215 +48 51 204 +40 33 212 +52 49 187 +27 54 204 +39 49 204 +53 25 196 +26 43 204 +31 28 210 +46 39 207 +42 30 214 diff --git a/task_058/solution/code/data/test/img_009.ppm b/task_058/solution/code/data/test/img_009.ppm new file mode 100644 index 0000000000000000000000000000000000000000..fcccf95d5cc9f13ca6f71dfb9a8c018757020dab --- /dev/null +++ b/task_058/solution/code/data/test/img_009.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +203 26 33 +201 51 46 +209 43 51 +197 34 43 +215 44 26 +206 43 45 +195 52 42 +195 48 31 +187 41 49 +192 54 28 +209 34 25 +187 27 25 +211 34 42 +204 36 44 +206 45 51 +198 44 49 diff --git a/task_058/solution/code/data/test/img_010.ppm b/task_058/solution/code/data/test/img_010.ppm new file mode 100644 index 0000000000000000000000000000000000000000..97d37c56ec47581d55decb657b8be58d80a60625 --- /dev/null +++ b/task_058/solution/code/data/test/img_010.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +25 197 39 +27 191 27 +36 205 35 +36 197 36 +47 188 25 +29 189 39 +36 207 48 +29 188 26 +33 203 30 +26 204 35 +42 204 40 +44 187 41 +50 215 49 +38 206 36 +51 185 38 +54 195 31 diff --git a/task_058/solution/code/data/test/img_011.ppm b/task_058/solution/code/data/test/img_011.ppm new file mode 100644 index 0000000000000000000000000000000000000000..f7f135822ec8c2c820137359ed858000a17a67b5 --- /dev/null +++ b/task_058/solution/code/data/test/img_011.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +42 30 204 +52 43 192 +47 38 190 +45 38 207 +40 45 189 +37 41 206 +40 47 203 +37 34 203 +33 33 189 +36 29 215 +47 46 212 +50 33 204 +34 32 194 +30 29 204 +45 43 215 +48 39 186 diff --git a/task_058/solution/code/data/train/blue_00.ppm b/task_058/solution/code/data/train/blue_00.ppm new file mode 100644 index 0000000000000000000000000000000000000000..8407aa0ae5ba9047ff91f0f48cba73ddadfee2d0 --- /dev/null +++ b/task_058/solution/code/data/train/blue_00.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +55 49 199 +28 25 187 +54 55 215 +50 43 186 +46 47 187 +28 49 196 +32 25 185 +50 25 196 +45 44 200 +44 39 189 +27 30 207 +28 52 185 +41 40 213 +55 32 187 +46 42 214 +39 27 204 diff --git a/task_058/solution/code/data/train/blue_01.ppm b/task_058/solution/code/data/train/blue_01.ppm new file mode 100644 index 0000000000000000000000000000000000000000..50f6eeed5beb978e4f7dead686653e087d98f3f5 --- /dev/null +++ b/task_058/solution/code/data/train/blue_01.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +46 27 201 +43 26 193 +51 42 187 +45 34 200 +52 36 193 +32 45 214 +31 39 213 +41 46 185 +55 41 187 +25 35 189 +47 40 206 +37 30 186 +27 43 200 +30 27 202 +31 29 185 +54 36 209 diff --git a/task_058/solution/code/data/train/blue_02.ppm b/task_058/solution/code/data/train/blue_02.ppm new file mode 100644 index 0000000000000000000000000000000000000000..eccb3745c86293833f65db48cbe1e2e32503a9de --- /dev/null +++ b/task_058/solution/code/data/train/blue_02.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +28 55 201 +29 46 194 +39 26 198 +33 46 210 +26 30 193 +29 34 215 +52 29 209 +51 39 186 +43 37 209 +36 40 195 +43 51 199 +40 26 210 +54 40 212 +51 44 213 +30 39 208 +49 41 211 diff --git a/task_058/solution/code/data/train/blue_03.ppm b/task_058/solution/code/data/train/blue_03.ppm new file mode 100644 index 0000000000000000000000000000000000000000..5e28bdb84c9d306d47e71823a9561c10107f3fa1 --- /dev/null +++ b/task_058/solution/code/data/train/blue_03.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +39 34 193 +28 49 190 +38 38 209 +28 55 201 +28 51 211 +40 37 211 +51 46 193 +45 31 196 +28 47 207 +50 55 190 +43 54 215 +33 29 212 +51 48 195 +50 50 199 +48 27 187 +37 31 186 diff --git a/task_058/solution/code/data/train/blue_04.ppm b/task_058/solution/code/data/train/blue_04.ppm new file mode 100644 index 0000000000000000000000000000000000000000..19590da871d8ee2e270bf800d8620d4f3bcac3e3 --- /dev/null +++ b/task_058/solution/code/data/train/blue_04.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +53 34 210 +26 32 201 +51 27 210 +54 55 207 +35 34 215 +39 27 203 +33 52 187 +47 38 215 +31 28 197 +31 47 213 +53 39 201 +32 51 210 +36 54 212 +31 41 213 +47 38 190 +55 43 191 diff --git a/task_058/solution/code/data/train/green_00.ppm b/task_058/solution/code/data/train/green_00.ppm new file mode 100644 index 0000000000000000000000000000000000000000..5d4216306b441384fb12d2a70d904464de01d2b0 --- /dev/null +++ b/task_058/solution/code/data/train/green_00.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +34 186 51 +36 202 29 +40 214 49 +55 202 40 +35 189 29 +26 204 30 +54 189 51 +42 187 47 +35 190 25 +46 206 26 +45 187 49 +50 189 54 +31 186 38 +37 208 35 +31 211 46 +37 214 52 diff --git a/task_058/solution/code/data/train/green_01.ppm b/task_058/solution/code/data/train/green_01.ppm new file mode 100644 index 0000000000000000000000000000000000000000..91682729054e68305a2fa881d79ae0c576ddf859 --- /dev/null +++ b/task_058/solution/code/data/train/green_01.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +54 215 33 +42 205 54 +34 198 35 +46 203 52 +29 211 42 +27 209 33 +33 198 37 +52 203 33 +41 188 47 +37 193 31 +34 207 51 +43 197 26 +36 213 51 +39 192 49 +40 190 37 +34 185 27 diff --git a/task_058/solution/code/data/train/green_02.ppm b/task_058/solution/code/data/train/green_02.ppm new file mode 100644 index 0000000000000000000000000000000000000000..b53255208270612843948d87ec46a08d8b80290a --- /dev/null +++ b/task_058/solution/code/data/train/green_02.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +40 197 34 +38 211 46 +51 200 30 +37 205 40 +30 194 43 +36 205 44 +36 191 30 +41 214 43 +39 210 46 +40 206 25 +50 210 48 +39 206 50 +28 185 36 +50 200 27 +54 189 53 +53 213 43 diff --git a/task_058/solution/code/data/train/green_03.ppm b/task_058/solution/code/data/train/green_03.ppm new file mode 100644 index 0000000000000000000000000000000000000000..a142d51168ceb837032a6a07349fa6d5addea91f --- /dev/null +++ b/task_058/solution/code/data/train/green_03.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +35 196 49 +49 194 34 +46 206 43 +35 203 55 +55 194 43 +31 201 51 +48 193 27 +42 207 44 +31 195 41 +35 214 35 +39 193 27 +49 201 43 +43 202 28 +51 192 33 +36 189 52 +25 197 26 diff --git a/task_058/solution/code/data/train/green_04.ppm b/task_058/solution/code/data/train/green_04.ppm new file mode 100644 index 0000000000000000000000000000000000000000..b69d37e2c94ee60bd0d8825b1ef1d81e4dbefff1 --- /dev/null +++ b/task_058/solution/code/data/train/green_04.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +46 186 31 +46 189 35 +41 196 38 +54 201 54 +27 212 49 +55 194 33 +47 200 54 +43 192 36 +41 187 45 +54 210 25 +46 203 35 +52 203 32 +30 200 40 +46 215 46 +55 189 53 +42 204 44 diff --git a/task_058/solution/code/data/train/red_00.ppm b/task_058/solution/code/data/train/red_00.ppm new file mode 100644 index 0000000000000000000000000000000000000000..aff3da61d5b35b3b48e3fee8ee702111b8aaa8de --- /dev/null +++ b/task_058/solution/code/data/train/red_00.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +187 29 42 +215 51 32 +207 30 54 +201 49 41 +207 49 37 +212 51 35 +189 47 42 +203 42 44 +204 52 39 +186 36 27 +214 36 49 +211 46 38 +213 26 44 +204 27 35 +192 44 50 +191 36 55 diff --git a/task_058/solution/code/data/train/red_01.ppm b/task_058/solution/code/data/train/red_01.ppm new file mode 100644 index 0000000000000000000000000000000000000000..b8f3f734d27aec4d2557feef5b5c9e263f3a67ef --- /dev/null +++ b/task_058/solution/code/data/train/red_01.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +215 41 47 +209 37 43 +200 26 25 +199 50 27 +211 34 38 +214 35 29 +200 46 49 +205 32 47 +210 25 52 +208 36 43 +196 38 30 +187 45 25 +191 49 31 +211 44 44 +202 48 29 +201 29 46 diff --git a/task_058/solution/code/data/train/red_02.ppm b/task_058/solution/code/data/train/red_02.ppm new file mode 100644 index 0000000000000000000000000000000000000000..bf9fc8fb10ad51e72cab82d4111e6848494c43b7 --- /dev/null +++ b/task_058/solution/code/data/train/red_02.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +214 33 45 +208 26 55 +214 44 39 +196 44 48 +196 34 37 +198 49 36 +192 34 25 +213 35 43 +193 28 42 +204 26 52 +191 42 43 +203 36 42 +190 35 34 +196 51 54 +193 47 47 +205 30 39 diff --git a/task_058/solution/code/data/train/red_03.ppm b/task_058/solution/code/data/train/red_03.ppm new file mode 100644 index 0000000000000000000000000000000000000000..52721b45db2aa1469b75a7d3a68d793d0eabdf10 --- /dev/null +++ b/task_058/solution/code/data/train/red_03.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +214 30 53 +185 55 42 +207 38 32 +191 39 33 +211 52 48 +190 36 55 +208 43 51 +212 38 41 +200 49 44 +203 40 51 +200 41 39 +208 48 50 +208 36 44 +188 47 46 +201 52 37 +211 43 29 diff --git a/task_058/solution/code/data/train/red_04.ppm b/task_058/solution/code/data/train/red_04.ppm new file mode 100644 index 0000000000000000000000000000000000000000..e1813b1346c44a42e8e622e51aedc5df53a677b4 --- /dev/null +++ b/task_058/solution/code/data/train/red_04.ppm @@ -0,0 +1,19 @@ +P3 +4 4 +255 +188 50 40 +200 28 42 +202 29 50 +209 33 32 +207 27 35 +197 55 34 +207 41 36 +197 42 52 +191 44 40 +206 54 46 +214 39 35 +215 39 54 +201 28 42 +210 39 27 +187 31 30 +204 53 35 diff --git a/task_058/solution/code/data/train_labels.csv b/task_058/solution/code/data/train_labels.csv new file mode 100644 index 0000000000000000000000000000000000000000..9105be64a18946e12de7ccad1e9ea1faa1d2e824 --- /dev/null +++ b/task_058/solution/code/data/train_labels.csv @@ -0,0 +1,16 @@ +filename,color +blue_00.ppm,blue +blue_01.ppm,blue +blue_02.ppm,blue +blue_03.ppm,blue +blue_04.ppm,blue +green_00.ppm,green +green_01.ppm,green +green_02.ppm,green +green_03.ppm,green +green_04.ppm,green +red_00.ppm,red +red_01.ppm,red +red_02.ppm,red +red_03.ppm,red +red_04.ppm,red diff --git a/task_058/solution/solve.sh b/task_058/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_058/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_058/task.toml b/task_058/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_058/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_058/task_meta.json b/task_058/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..9d3842bf5b757cde0051a4e07bb7132f503d1c81 --- /dev/null +++ b/task_058/task_meta.json @@ -0,0 +1,20 @@ +{ + "task_id": 103, + "task_category": "machine_learning", + "origin_model": "authored", + "sample_count": 0, + "user_turns": 0, + "language": "python", + "input_assets": [ + "data/train/*.ppm", + "data/train_labels.csv", + "data/test/*.ppm" + ], + "expected_outputs": [ + "classify.py", + "output/predictions.csv" + ], + "source_row_id": null, + "repair_revision": "2026-09-29", + "instruction_sha256": "56dc71b758d283f1af677a28f5105c9107d5be446edfca1df03652b7e4c18c73" +} diff --git a/task_058/tests/_shared/contract_checker.js b/task_058/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_058/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_058/tests/_shared/static_enhancer.sh b/task_058/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_058/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_058/tests/_shared/variant_runner.py b/task_058/tests/_shared/variant_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..9d30100fc3633d2211fef503a6e2a4d2e9f3a302 --- /dev/null +++ b/task_058/tests/_shared/variant_runner.py @@ -0,0 +1,73 @@ +import csv +import pathlib +import shutil +import subprocess +import sys +import tempfile +from contextlib import contextmanager + + +IGNORED = ("tests", "logs", "output", "__pycache__", "node_modules", ".git") + + +def read_csv(path): + with pathlib.Path(path).open(newline="", encoding="utf-8") as handle: + reader = csv.DictReader(handle) + return reader.fieldnames, list(reader) + + +def write_csv(path, columns, rows): + path = pathlib.Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=columns) + writer.writeheader() + writer.writerows(rows) + + +@contextmanager +def isolated_candidate(candidate, prefix): + with tempfile.TemporaryDirectory(prefix=prefix) as temp: + work = pathlib.Path(temp) / "candidate" + shutil.copytree( + pathlib.Path(candidate).resolve(), + work, + ignore=shutil.ignore_patterns(*IGNORED), + ) + yield work + + +def run_python(work, script=None, timeout=20, fixture_hint=None): + work = pathlib.Path(work) + if script is not None: + script_path = work / script + assert script_path.is_file(), f"instruction requires {script}" + else: + candidates = [ + path for path in work.rglob("*.py") + if not set(path.relative_to(work).parts) & set(IGNORED) + ] + if fixture_hint: + hinted = [ + path for path in candidates + if fixture_hint in path.read_text(encoding="utf-8", errors="ignore") + ] + if hinted: + candidates = hinted + assert candidates, "no candidate Python entrypoint found" + script_path = sorted(candidates)[0] + result = subprocess.run( + [sys.executable, str(script_path.relative_to(work))], + cwd=work, + capture_output=True, + text=True, + timeout=timeout, + ) + assert result.returncode == 0, ( + f"{script_path.name} failed with {result.returncode}:\n{result.stdout}\n{result.stderr}" + ) + return result + + +def assert_exact_header(actual, expected, label): + assert actual == expected, f"{label}: columns {actual!r}, expected {expected!r}" diff --git a/task_058/tests/enhancement_cases.json b/task_058/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..6bad8e381b905d8d926f157676c9dcd646de1419 --- /dev/null +++ b/task_058/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"id":"ENHANCED_CASE_1","requirement":"Parse asymmetric P3 pixel data and classify all red, green, and blue examples."}, + {"id":"ENHANCED_CASE_2","requirement":"Learn the label-to-color mapping from training fixtures rather than hardcoding channel names."}, + {"id":"ENHANCED_CASE_3","requirement":"Exact filename coverage for arbitrary names and deterministic predictions."} +] diff --git a/task_058/tests/review_hard.py b/task_058/tests/review_hard.py new file mode 100644 index 0000000000000000000000000000000000000000..26fff88e606fd43044efa05087112ac258cc7088 --- /dev/null +++ b/task_058/tests/review_hard.py @@ -0,0 +1,21 @@ +import sys, tempfile, math, importlib.util +from pathlib import Path +root=Path(sys.argv[1]).resolve() +def load(file): + sys.path.insert(0,str(root)) + spec=importlib.util.spec_from_file_location('review_module',root/file) + m=importlib.util.module_from_spec(spec) + sys.modules[spec.name]=m + spec.loader.exec_module(m) + return m +m=load('classify.py') +with tempfile.TemporaryDirectory() as td: + for w,h,maxv in [(1,3,15),(7,2,1023),(2,1,65535),(2,2,1)]: + pixels=[(maxv, maxv//3, 0) if i % 2 else (0, maxv, maxv) for i in range(w*h)] + p=Path(td)/'opaque.ppm' + p.write_text('P3 # header\n'+f'{w} {h}\n# max follows\n{maxv}\n'+'\n'.join(' '.join(map(str,x))+' # pixel' for x in pixels)) + got=m.parse_ppm(p) + expected=tuple(sum(pixel[channel] for pixel in pixels)*255/(w*h*maxv) for channel in range(3)) + assert isinstance(got,(tuple,list)) and len(got)==3, 'parse_ppm must return three RGB values' + assert all(math.isfinite(a) and abs(a-b)<1e-8 for a,b in zip(got,expected)), (got,expected) + print(f'P3 {w}x{h} maxval={maxv}: mean RGB {got}, expected {expected}') diff --git a/task_058/tests/review_legacy.sh b/task_058/tests/review_legacy.sh new file mode 100644 index 0000000000000000000000000000000000000000..16e3c3c0e18b6daedb37074eaf1834deec02f0c9 --- /dev/null +++ b/task_058/tests/review_legacy.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +set -euo pipefail +set +e +TASK_ID='103' +source "$(cd "$(dirname "$0")" && pwd)/_shared/static_enhancer.sh" +LOG_DIR="/logs/verifier" +if ! mkdir -p "$LOG_DIR" 2>/dev/null; then LOG_DIR="logs/verifier"; mkdir -p "$LOG_DIR"; fi +REWARD_FILE="$LOG_DIR/reward.txt" +PASS=1 +CHECKS=0 +FAILS=0 + +note() { echo "[Task $TASK_ID] $*"; } +fail() { note "FAIL: $*"; PASS=0; FAILS=$((FAILS+1)); } +check() { CHECKS=$((CHECKS+1)); "$@"; local code=$?; if [ $code -ne 0 ]; then fail "$*"; fi; } +have_any() { local pattern="$1"; compgen -G "$pattern" >/dev/null 2>&1; } +grep_any() { local pattern="$1"; shift; grep -REiq -- "$pattern" "$@" 2>/dev/null; } +source_files() { find . -type f \( -name '*.html' -o -name '*.js' -o -name '*.jsx' -o -name '*.ts' -o -name '*.tsx' -o -name '*.css' -o -name '*.py' -o -name '*.go' -o -name '*.swift' -o -name '*.svg' \) ! -path './tests/*' ! -path './logs/*'; } + +note "enhanced deterministic verifier start" +static_enhance_check "${TASK_ID}" "$(pwd)" +mapfile -t py_files < <(find . -type f -name '*.py' ! -path './tests/*') +if [ ${#py_files[@]} -eq 0 ]; then fail "no Python source found"; fi +if command -v python3 >/dev/null 2>&1; then + for f in "${py_files[@]}"; do python3 -m py_compile "$f" >/tmp/harbor_py_compile.log 2>&1 || fail "python compile failed: $f"; done +fi + +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +if command -v python3 >/dev/null 2>&1; then + check python3 "$TEST_DIR/validate_outputs.py" + check python3 "$TEST_DIR/validate_enhanced.py" +else + fail "python3 unavailable for output validation" +fi +# BEGIN AAAV_DYNAMIC_TEST +if [ -f "$TEST_DIR/validate_aaav_dynamic.js" ]; then + if command -v node >/dev/null 2>&1; then + check node "$TEST_DIR/validate_aaav_dynamic.js" + else + note "AAAV dynamic validation skipped (node unavailable in this runtime)" + fi +fi +# END AAAV_DYNAMIC_TEST +note "checks=$CHECKS fails=$FAILS" +if [ "$PASS" -eq 1 ]; then + echo 1 > "$REWARD_FILE" + note "PASS" + exit 0 +fi +echo 0 > "$REWARD_FILE" +note "FAIL" +exit 0 diff --git a/task_058/tests/test.sh b/task_058/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56b0776f3ccad7f2da017c3b6e7cd69a9a1454e6 --- /dev/null +++ b/task_058/tests/test.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -uo pipefail +bash /tests/review_legacy.sh +CORE=$(cat /logs/verifier/reward.txt 2>/dev/null || echo 0) +mkdir -p /logs/verifier +python3 /tests/review_hard.py /app 2>&1 | tee /logs/verifier/review_hard.log +RC=${PIPESTATUS[0]} +if [ "$RC" -ne 0 ]; then echo "REVIEW_HARD failed with exit code $RC"; fi +if [ "$RC" -eq 0 ]; then echo "$CORE"; else echo 0; fi > /logs/verifier/reward.txt +exit 0 diff --git a/task_058/tests/test_labels.csv b/task_058/tests/test_labels.csv new file mode 100644 index 0000000000000000000000000000000000000000..fedc3c9fe3512b3ac46d128aef8486d178cb7c64 --- /dev/null +++ b/task_058/tests/test_labels.csv @@ -0,0 +1,13 @@ +filename,color +img_000.ppm,red +img_001.ppm,green +img_002.ppm,blue +img_003.ppm,red +img_004.ppm,green +img_005.ppm,blue +img_006.ppm,red +img_007.ppm,green +img_008.ppm,blue +img_009.ppm,red +img_010.ppm,green +img_011.ppm,blue diff --git a/task_058/tests/validate_aaav_dynamic.js b/task_058/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..33a8612ed1d8205710e984e1c7f9e4685e124e1c --- /dev/null +++ b/task_058/tests/validate_aaav_dynamic.js @@ -0,0 +1,27 @@ +const fs = require('fs'); +const path = require('path'); +const child_process = require('child_process'); +const TASK_ID = 103; +const LANGUAGE = "python"; +const EXPECTED = []; +const SKIP_DIRS = new Set(["tests","logs","node_modules",".git"]); +function assert(condition, message) { if (!condition) throw new Error(message); } +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} +const files = walk(process.cwd()); +assert(files.length > 0, 'candidate workspace should contain files'); +const source = files.filter(f => /\.(js|jsx|ts|tsx|css|html|py|go|md|svg)$/i.test(f)); +assert(source.length > 0, 'candidate should contain source or report files'); +const pyFiles = files.filter(f => f.endsWith('.py')); +for (const f of pyFiles.slice(0, 20)) { + child_process.execFileSync('python3', ['-m', 'py_compile', f], { cwd: process.cwd(), stdio: 'pipe', timeout: 30000 }); +} +console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`); diff --git a/task_058/tests/validate_enhanced.py b/task_058/tests/validate_enhanced.py new file mode 100644 index 0000000000000000000000000000000000000000..d2a8771429eca124aa8760c6ecd118f96edc6509 --- /dev/null +++ b/task_058/tests/validate_enhanced.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +import pathlib +import ast +import json +import shutil +import re +import sys + +TEST_DIR = pathlib.Path(__file__).resolve().parent +sys.path.insert(0, str(TEST_DIR / "_shared")) +from variant_runner import assert_exact_header, isolated_candidate, read_csv, run_python, write_csv + + +def pixels(center, delta=12): + low = tuple(max(0, v - delta) for v in center) + high = tuple(min(255, v + delta) for v in center) + return [low, high] * 8 + + +def write_ppm(path, values): + path.parent.mkdir(parents=True, exist_ok=True) + flat = " ".join(str(channel) for pixel in values for channel in pixel) + path.write_text(f"P3\n4 4\n255\n{flat}\n", encoding="ascii") + + +def run_fixture(candidate, centers, test_specs, training_specs=None): + with isolated_candidate(candidate, "task103-") as work: + data = work / "data" + if data.exists(): + shutil.rmtree(data) + labels = [] + features = [] + if training_specs is None: + training_specs = [(f'train_{color}_{index}.ppm', color, tuple(v + index * 2 for v in center)) + for color, center in centers.items() for index in range(2)] + for name, color, center in training_specs: + varied = pixels(center, delta=10) + feature = tuple(sum(pixel[c] for pixel in varied) / len(varied) for c in range(3)) + features.append((feature, color)) + write_ppm(data / 'train' / name, varied) + labels.append({'filename': name, 'color': color}) + class_centers = {} + for color in ('red', 'green', 'blue'): + members = [feature for feature, label in features if label == color] + class_centers[color] = tuple(sum(feature[c] for feature in members) / len(members) for c in range(3)) + def predict(feature): + return min(class_centers, key=lambda color: sum((feature[c] - class_centers[color][c]) ** 2 for c in range(3))) + training_accuracy = sum(predict(feature) == label for feature, label in features) / len(features) + write_csv(data / "train_labels.csv", ["filename", "color"], labels) + truth = {} + for name, color, center in test_specs: + write_ppm(data / "test" / name, pixels(center, delta=15)) + truth[name] = color + + source = ast.parse((work / 'classify.py').read_text(encoding='utf-8')) + for node in ast.walk(source): + modules = [item.name for item in node.names] if isinstance(node, ast.Import) else ( + [node.module or ''] if isinstance(node, ast.ImportFrom) and node.level == 0 else []) + assert not any(module.split('.')[0].lower() in {'pil', 'numpy', 'cv2', 'imageio'} for module in modules), 'raster library import is forbidden' + result = run_python(work, "classify.py", timeout=15) + stated = re.search(r"(?:\btrain(?:ing)?[\s_-]*accuracy\b|训练(?:集)?准确率)\s*(?:=|:|:|is)?\s*([0-9]+(?:\.[0-9]+)?)\s*(%)?", result.stdout, re.I) + assert stated, "stdout must report training accuracy" + reported = float(stated.group(1)) / (100 if stated.group(2) else 1) + assert abs(reported - training_accuracy) < 0.001, f"wrong training accuracy: {stated.group(0)!r}; expected {training_accuracy}" + header, rows = read_csv(work / "output/predictions.csv") + assert_exact_header(header, ["filename", "predicted"], "predictions.csv") + assert len(rows) == len(test_specs), "must emit exactly one row per test image" + assert len({r["filename"] for r in rows}) == len(rows), "duplicate filenames" + got = {r["filename"]: r["predicted"] for r in rows} + assert set(got) == set(truth), "test filename coverage mismatch" + assert set(got.values()) <= {"red", "green", "blue"}, "illegal predicted color" + assert got == truth, f"predictions {got!r}, expected {truth!r}" + archive = pathlib.Path('/logs/verifier/semantic-review') + archive.mkdir(parents=True, exist_ok=True) + label = test_specs[0][0].removesuffix('.ppm') + (archive / f'{label}.json').write_text(json.dumps({'predictions': got, 'expected': truth, + 'reported_training_accuracy': reported, 'independent_training_accuracy': training_accuracy}, indent=2)) + + +def case_1(candidate): + centers = {"red": (180, 55, 45), "green": (40, 175, 60), "blue": (55, 45, 185)} + tests = [ + ("asymmetric-z.ppm", "red", (170, 60, 50)), + ("asymmetric-a.ppm", "green", (45, 165, 70)), + ("asymmetric-m.ppm", "blue", (65, 55, 175)), + ] + run_fixture(candidate, centers, tests) + + +def case_2(candidate): + centers = {"red": (205, 25, 25), "green": (25, 205, 25), "blue": (25, 25, 205)} + tests = [ + ("learn-red.ppm", "red", (195, 30, 35)), + ("learn-green.ppm", "green", (35, 195, 30)), + ("learn-blue.ppm", "blue", (30, 35, 195)), + ] + run_fixture(candidate, centers, tests) + + +def case_3(candidate): + centers = {"red": (210, 40, 40), "green": (40, 210, 40), "blue": (40, 40, 210)} + tests = [ + ("z-last.ppm", "blue", (50, 45, 190)), + ("001.ppm", "red", (190, 50, 45)), + ("odd name.ppm", "green", (45, 190, 50)), + ("another.ppm", "red", (175, 65, 55)), + ] + run_fixture(candidate, centers, tests) + + +def case_4(candidate): + training = [('a.ppm', 'red', (200, 20, 20)), ('b.ppm', 'red', (30, 200, 20)), + ('c.ppm', 'green', (20, 190, 30)), ('d.ppm', 'green', (40, 210, 10)), + ('e.ppm', 'blue', (20, 20, 200)), ('f.ppm', 'blue', (40, 30, 220))] + run_fixture(candidate, {}, [('centroid-not-largest.ppm', 'red', (120, 130, 20)), + ('true-green.ppm', 'green', (30, 200, 20))], training) + + +def main(): + candidate = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve() + for number, fn in enumerate((case_1, case_2, case_3, case_4), 1): + fn(candidate) + print(f"ENHANCED_CASE_{number} PASS") + + +if __name__ == "__main__": + main() diff --git a/task_058/tests/validate_outputs.py b/task_058/tests/validate_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..654ce9d05631dbf92ff14a4193d29a3796618a61 --- /dev/null +++ b/task_058/tests/validate_outputs.py @@ -0,0 +1,78 @@ +import csv +import pathlib + +root = pathlib.Path.cwd() + +def _py_sources(): + _skip = {"tests", "logs", "output", "__pycache__", "node_modules", ".git"} + return [p for p in root.rglob("*.py") + if not (set(p.relative_to(root).parts) & _skip) + and p.name != "validate_outputs.py"] + + +# --- (re)generate outputs by running the candidate script --------------------- +# The oracle overlays solution/code but does NOT execute it, and a real model may +# leave a script without having run it. Delete any pre-baked output/ and run the +# candidate analysis fresh so we always grade COMPUTED results (anti-hardcode). +import subprocess as _sp, sys as _sys, shutil as _shutil +_out_dir = root / "output" +if _out_dir.exists(): + _shutil.rmtree(_out_dir, ignore_errors=True) +_run = _sp.run([_sys.executable, str(root / 'classify.py')], cwd=root, + capture_output=True, text=True, timeout=120) +assert _run.returncode == 0, (_run.stdout, _run.stderr) +# ------------------------------------------------------------------------------ + +here = pathlib.Path(__file__).resolve().parent + +FLOOR = 0.85 # reference scores 1.0 on the test set; random/constant ~0.33 must fail. + +# --- candidate source must actually parse PPM + read the test fixtures (anti-hardcode) --- +py_files = [p for p in _py_sources() if p.name != "validate_outputs.py"] +assert py_files, "missing candidate python source (e.g. classify.py)" +src = "\n".join(p.read_text(encoding="utf-8", errors="ignore") for p in py_files).lower() + +# --- ground truth lives ONLY in tests/, never shipped to the candidate --- +labels_path = here / "test_labels.csv" +assert labels_path.exists(), "missing withheld tests/test_labels.csv" +truth = {} +with open(labels_path, newline="", encoding="utf-8") as fh: + for r in csv.DictReader(fh): + truth[r["filename"]] = r["color"] +assert len(truth) >= 9, f"unexpectedly small test set: {len(truth)}" +valid_colors = {"red", "green", "blue"} +assert set(truth.values()) <= valid_colors, "unexpected color in ground truth" + +# the candidate must NOT have been given the labels +assert not (root / "data" / "test_labels.csv").exists(), \ + "test labels leaked into candidate workspace" + +# --- read candidate predictions --- +pred_path = root / "output" / "predictions.csv" +assert pred_path.exists(), "candidate did not write output/predictions.csv" +preds = {} +with open(pred_path, newline="", encoding="utf-8") as fh: + reader = csv.DictReader(fh) + cols = [c.strip() for c in (reader.fieldnames or [])] + assert cols == ["filename", "predicted"], \ + f"unexpected columns {cols}; want filename,predicted" + for r in reader: + assert None not in r and r['filename'] not in preds, 'duplicate filename or extra CSV cells' + preds[r["filename"]] = r["predicted"].strip() + +# validity: covers every test id, every prediction is a legal color +missing = set(truth) - set(preds) +assert not missing, f"predictions missing for: {sorted(missing)}" +assert set(preds) == set(truth), 'predictions include unknown filenames' +bad = {p for p in preds.values() if p not in valid_colors} +assert not bad, f"predictions contain illegal colors: {bad}" + +# --- recompute accuracy from predictions vs withheld ground truth --- +correct = sum(1 for fn, c in truth.items() if preds.get(fn) == c) +acc = correct / len(truth) +assert acc >= FLOOR, ( + f"accuracy {acc:.4f} below floor {FLOOR} ({correct}/{len(truth)} correct)" +) + +print(f"validate_outputs OK: task_103 color classification accuracy={acc:.4f} " + f"({correct}/{len(truth)}) >= floor {FLOOR}") diff --git a/task_059/acceptance_checklist.json b/task_059/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..bc85facd2f623020da9cf5ea1392a1862616abb3 --- /dev/null +++ b/task_059/acceptance_checklist.json @@ -0,0 +1,20 @@ +{ + "task_id": 106, + "category": "frontend_development", + "language": "javascript", + "acceptance_items": [ + "init parses player/boxes/targets/walls/dims; status won iff all boxes start on targets, otherwise playing; moves 0.", + "Legal move increments moves; wall move is a no-op.", + "Box pushing works; pushing into wall/box is blocked.", + "Win when all boxes on targets; moves ignored after win.", + "Visible, non-overlapping DOM cells mirror box/player/target/wall positions before and after moves. Coordinate collections are unordered." + ], + "expected_outputs": [ + "index.html" + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "risk_notes": [ + "Render-reflection tier defeats no-render in-memory engines." + ], + "repair_revision": "2026-09-29" +} diff --git a/task_059/environment/Dockerfile b/task_059/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2f855b3d12b4e80dd6cd135513202206e95ccdba --- /dev/null +++ b/task_059/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# The mcr/playwright base ships browsers but NOT the `playwright` npm package, +# which the verifier's require('playwright') needs. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_059/environment/code/README.md b/task_059/environment/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b4308627f143f936816c1b027e52292e806a219c --- /dev/null +++ b/task_059/environment/code/README.md @@ -0,0 +1,6 @@ +# sokoban — starter + +Implement the game in a single self-contained `index.html` (inline CSS/JS, no +external network). Expose a deterministic `window.__game` API as described in the +task instruction so the verifier can drive it with explicit scenarios. The +rendered DOM must mirror the in-memory game state. diff --git a/task_059/environment/docker-compose.yaml b/task_059/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_059/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_059/instruction.md b/task_059/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..434600d100dd11be8c5899dca317fd398ab8cd47 --- /dev/null +++ b/task_059/instruction.md @@ -0,0 +1,16 @@ +# Build a Sokoban puzzle board + +Build a single self-contained offline `index.html` with inline CSS and JavaScript. Render a visible board that tracks the puzzle state. + +## Level and state + +Expose `window.__game.init(level)`, `.getState()` and `.move(dir)`. The level is `{grid:[...strings]}` with equal-length rows, exactly one player and at least one box. Meaning: `#` wall, space floor, `.` target, `$` box, `@` player, `*` box on target and `+` player on target. + +Use zero-based row and column. Return `{width,height,player:{r,c},boxes:[[r,c]],targets:[[r,c]],walls:[[r,c]],moves,status}` from initialization and moves as well as `getState()`. Box, target and wall arrays are coordinate sets whose order is unrestricted. Status is `playing` or `won`. + +## Acceptance Checklist + +- Parse the complete level, including both occupants on targets. Reset the move count; an initial layout with all boxes on targets is already won. +- A move `U`, `D`, `L` or `R` walks to a free floor/target cell or pushes one box into an unoccupied floor/target cell. Moving into a wall or outside the grid, or pushing into a wall, another box or outside the grid, leaves all state unchanged. No perimeter walls are required. +- Count only successful moves. Putting all boxes on targets wins; further moves are no-ops. +- Render every board position inside `#board` in a visible, non-overlapping grid. Each position is a `.cell` with `.wall`, `.target`, `.box` or `.player` as applicable. DOM positions and classes update synchronously with state, including composite cells. diff --git a/task_059/quality_notes.md b/task_059/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..42182495604f70e57392bd90047badae24cfce78 --- /dev/null +++ b/task_059/quality_notes.md @@ -0,0 +1,14 @@ +# Quality notes — task_106 + +## 2026-10-08 deep review + +- Active scoring is implemented by the executable verifier in tests/ and disclosed in instruction.md; older five-tier descriptions below refer to the base suite only. +- Coordinate collections compare without ordering; solved-at-init is explicitly won. Non-terminal wall blocks and visible post-move DOM positions are checked. +- Remote oracle/nop, targeted defect, alternate implementation, repeated runs, and screenshots are tracked separately in the review ledger. Static inspection alone is not a runtime pass or proof of model discrimination. + +- Deterministic: levels are explicit char grids; no RNG. +- Discrimination via 5 tiers (parse / move+wall / push+block / win / render-reflection), + fractional reward = tiers passed. An in-memory engine that doesn't render the + board fails T5; one that miscounts illegal moves fails T2; bad push rules fail T3. +- Verifier uses an independent reference simulation, not source grep. +- Enhanced coverage includes boundary walking and pushing without perimeter walls; the instruction now specifies both. diff --git a/task_059/solution/README.md b/task_059/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d35193d7156abfb316660c338f6793cb4f89e1f3 --- /dev/null +++ b/task_059/solution/README.md @@ -0,0 +1,6 @@ +# Reference solution — task_106 (Sokoban) + +Self-contained `index.html`. `window.__game` parses a char-grid level, supports +U/D/L/R moves with box-pushing and blocking rules, counts only successful moves, +detects win when every box is on a target, and renders a DOM board that mirrors +the state (`.cell.wall/.target/.box/.player`). diff --git a/task_059/solution/code/index.html b/task_059/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..3f60de9de8df7bb377910d6ecf807331704b5f46 --- /dev/null +++ b/task_059/solution/code/index.html @@ -0,0 +1,179 @@ + + + + +Sokoban + + + +

      Sokoban

      +

      Use the arrow keys or WASD to move. Push every box onto a gold-outlined target to win.

      +
      Moves: 0 — Status: playing
      + +
      + +
      +
      + + + + diff --git a/task_059/solution/solve.sh b/task_059/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_059/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_059/task.toml b/task_059/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_059/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_059/task_meta.json b/task_059/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..84b63830fb50c107fb33de104249007dadea8d97 --- /dev/null +++ b/task_059/task_meta.json @@ -0,0 +1,15 @@ +{ + "task_id": 106, + "task_category": "frontend_development", + "origin_model": "authored", + "sample_count": 0, + "user_turns": 0, + "language": "javascript", + "input_assets": [], + "expected_outputs": [ + "index.html" + ], + "source_row_id": null, + "repair_revision": "2026-09-29", + "instruction_sha256": "43327ad4accb8e62eadfbcc99645bc93634f90eb899a7e102ce67f9c6c24a6f5" +} diff --git a/task_059/tests/_shared/contract_checker.js b/task_059/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_059/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_059/tests/_shared/static_enhancer.sh b/task_059/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_059/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_059/tests/enhancement_cases.json b/task_059/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..c5931593b9a79500929034ec6150f8b8513491bf --- /dev/null +++ b/task_059/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","instruction_evidence":"'*' 箱子在目标点上,'+' 玩家在目标点上。","validator":"validate_enhanced_cases.js","behavior":"初始化包含 * 与 + 的显式关卡,验证组合字符同时贡献对应实体与目标。"}, + {"case_id":"ENHANCED_CASE_2","instruction_evidence":"若箱子前方一格是墙或另一个箱子 → 无操作(推不动)。","validator":"validate_enhanced_cases.js","behavior":"验证箱子后紧邻另一箱子时玩家、箱子、步数和状态完全不变。"}, + {"case_id":"ENHANCED_CASE_3","instruction_evidence":"当所有箱子都位于目标点上时 status='won';获胜后再调用 move 无效。","validator":"validate_enhanced_cases.js","behavior":"一推获胜后再次移动,验证完整状态被冻结。"} +] diff --git a/task_059/tests/state_equal.js b/task_059/tests/state_equal.js new file mode 100644 index 0000000000000000000000000000000000000000..eb320b3d79c6ab921c9c707694beaf1333f5578e --- /dev/null +++ b/task_059/tests/state_equal.js @@ -0,0 +1,9 @@ +// Coordinate arrays are sets; public object properties have no ordering. +const {isDeepStrictEqual} = require('node:util'); +function canonical(state) { + const positions = name => state[name].map(pair => pair.slice()).sort((a,b) => a[0]-b[0] || a[1]-b[1]); + return {width:state.width,height:state.height,player:{r:state.player.r,c:state.player.c}, + boxes:positions('boxes'),targets:positions('targets'),walls:positions('walls'), + moves:state.moves,status:state.status}; +} +module.exports = (left,right) => isDeepStrictEqual(canonical(left),canonical(right)); diff --git a/task_059/tests/test.sh b/task_059/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4d56311c78e5287caa7bd8cdd692648b18248ccc --- /dev/null +++ b/task_059/tests/test.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +[ -f index.html ] || exit 0 +OUT=$(run validate_ui_behavior.js 2>&1); RC=$?; printf '%s +' "$OUT" +CORE=$(printf '%s +' "$OUT" | sed -n 's/^SCORE=//p' | tail -1) +if [ "$RC" -ne 0 ] || [ -z "$CORE" ]; then CORE=0; fi +OUT=$(run validate_enhanced_cases.js 2>&1); RC=$?; printf '%s +' "$OUT" +ENH=$(printf '%s +' "$OUT" | sed -n 's/^ENHANCED_SCORE=//p' | tail -1) +if [ "$RC" -ne 0 ] || [ -z "$ENH" ]; then ENH=0; fi +node -e 'const [a,b]=process.argv.slice(1).map(Number);if(![a,b].every(x=>Number.isFinite(x)&&x>=0&&x<=1))process.exit(1);console.log((5*a+4*b)/9)' "$CORE" "$ENH" > "$REWARD_FILE" +cat "$REWARD_FILE" diff --git a/task_059/tests/validate_aaav_dynamic.js b/task_059/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..cced0e292e749a8a5d5cf20a4d79bf90c96f512c --- /dev/null +++ b/task_059/tests/validate_aaav_dynamic.js @@ -0,0 +1,17 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +const TASK_ID = 106; +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage(); + const errs = []; + page.on('pageerror', e => errs.push(e.message)); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + const ok = await page.evaluate(() => !!(window.__game && typeof window.__game.getState === 'function')); + await browser.close(); + if (errs.length) throw new Error('page errors: ' + errs.join(' | ')); + if (!ok) throw new Error('window.__game.getState missing'); + console.log('AAAV dynamic gate passed for task ' + TASK_ID); +})().catch(e => { console.error('AAAV FAIL: ' + e.message); process.exit(1); }); diff --git a/task_059/tests/validate_browser_smoke.js b/task_059/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_059/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_059/tests/validate_enhanced_cases.js b/task_059/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..c24930e6d3c7820ff0389050695d0dcb76ebdbae --- /dev/null +++ b/task_059/tests/validate_enhanced_cases.js @@ -0,0 +1,54 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +function assert(x, m) { if (!x) throw new Error(m); } + +(async () => { + const browser = await chromium.launch({ headless: true, args: ['--no-sandbox', '--disable-dev-shm-usage'] }); + const page = await browser.newPage({ viewport: { width: 520, height: 640 } }); + await page.route(/^https?:\/\//, route => route.abort()); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded', timeout: 10000 }); + const cases = [ + // ENHANCED_CASE_1: '*' and '+' each combine the two states defined by the instruction. + ['ENHANCED_CASE_1', async () => { + const level = { grid: ['######', '#+ *$#', '######'] }; + const st = await page.evaluate(L => window.__game.init(L), level); + assert(st.player.r === 1 && st.player.c === 1, '+ must parse as player'); + assert(st.targets.some(x => x[0] === 1 && x[1] === 1), '+ must parse as target'); + assert(st.boxes.some(x => x[0] === 1 && x[1] === 3), '* must parse as box'); + assert(st.targets.some(x => x[0] === 1 && x[1] === 3), '* must parse as target'); + const solved = await page.evaluate(() => window.__game.init({grid:['#####','#@* #','#####']})); + assert(solved.status === 'won' && solved.moves === 0, 'all boxes initially on targets must be won'); + const frozen = await page.evaluate(() => window.__game.move('R')); + assert(require('./state_equal.js')(solved,frozen), 'solved initial board must stay frozen'); + }], + // ENHANCED_CASE_2: a box directly backed by another box cannot be pushed. + ['ENHANCED_CASE_2', async () => { + const level = { grid: ['#######', '#@$$ .#', '#######'] }; + const before = await page.evaluate(L => window.__game.init(L), level); + const after = await page.evaluate(() => window.__game.move('R')); + assert(require('./state_equal.js')(after,before), 'box-against-box push must be a complete no-op'); + }], + // ENHANCED_CASE_3: winning freezes every state field. + ['ENHANCED_CASE_3', async () => { + const level = { grid: ['#####', '#@$.#', '#####'] }; + const won = await page.evaluate(L => { window.__game.init(L); return window.__game.move('R'); }, level); + assert(won.status === 'won' && won.moves === 1, 'last box on target must win'); + const after = await page.evaluate(() => window.__game.move('L')); + assert(require('./state_equal.js')(after,won), 'move after win must be ignored'); + }], + // ENHANCED_CASE_4: board boundaries block walking and pushing even without perimeter walls. + ['ENHANCED_CASE_4', async () => { + const level = { grid: ['@ $', ' .'] }; + const before = await page.evaluate(L => window.__game.init(L), level); + const outside = await page.evaluate(() => window.__game.move('U')); + assert(require('./state_equal.js')(outside, before), 'walking beyond top edge must be ignored'); + const atBox = await page.evaluate(() => window.__game.move('R')); + const blocked = await page.evaluate(() => window.__game.move('R')); + assert(require('./state_equal.js')(blocked, atBox), 'pushing a box beyond right edge must be ignored'); + }], + ]; + let passed=0; for (const [id, fn] of cases) { try { await fn(); passed++; console.log('PASS '+id); } catch(e) { console.error('FAIL '+id+': '+e.message); } } console.log('ENHANCED_SCORE='+(passed/cases.length)); + await browser.close(); +})().catch(e => { console.error(e.stack || e); process.exit(1); }); + diff --git a/task_059/tests/validate_render_mirror.js b/task_059/tests/validate_render_mirror.js new file mode 100644 index 0000000000000000000000000000000000000000..a9dc3edbaaff46467d6085e3e504af8f44c37af3 --- /dev/null +++ b/task_059/tests/validate_render_mirror.js @@ -0,0 +1,46 @@ +// Check the visible board against public state, independent of source names. +const assert = require('node:assert/strict'); +module.exports = async function mirror(page, id) { + const { state, cells } = await page.evaluate(id => { + const state = window.__game.getState(); + const selector = id === 108 ? '.tile' : '.cell'; + const cells = [...document.querySelectorAll('#board ' + selector)].map(element => { + const rect = element.getBoundingClientRect(); + return { classes: [...element.classList], value: Number(element.dataset.v), + text: element.textContent.trim(), top: rect.top, left: rect.left, + width: rect.width, height: rect.height, + visible: element.checkVisibility({checkOpacity:true, checkVisibilityCSS:true}) }; + }); + cells.sort((a, b) => Math.abs(a.top - b.top) > 2 ? a.top - b.top : a.left - b.left); + return { state, cells }; + }, id); + const width = id === 106 ? state.width : state.size; + const height = id === 106 ? state.height : state.size; + assert.equal(cells.length, width * height, 'board cell count'); + const at = (positions, r, c) => positions.some(p => p[0] === r && p[1] === c); + cells.forEach((cell, index) => { + const r = Math.floor(index / width), c = index % width; + assert(cell.visible && cell.width > 0 && cell.height > 0, 'visible cell ' + index); + if (c > 0) { + const previous = cells[index - 1]; + assert(cell.left >= previous.left + previous.width - 1, 'non-overlapping columns'); + } + if (r > 0) { + const above = cells[index - width]; + assert(cell.top >= above.top + above.height - 1, 'non-overlapping rows'); + } + const has = cls => cell.classes.includes(cls); + if (id === 106) { + for (const [cls, positions] of [['wall', state.walls], ['box', state.boxes], ['target', state.targets]]) { + assert.equal(has(cls), at(positions, r, c), cls + ' at ' + index); + } + assert.equal(has('player'), state.player.r === r && state.player.c === c, 'player position'); + } else if (id === 107) { + assert.equal(has('on'), state.grid[index], 'light position ' + index); + } else { + assert.equal(cell.value, state.tiles[index], 'tile data-v ' + index); + assert.equal(cell.text, state.tiles[index] ? String(state.tiles[index]) : '', 'visible tile label'); + assert.equal(has('blank'), state.tiles[index] === 0, 'blank position'); + } + }); +}; diff --git a/task_059/tests/validate_semantics.js b/task_059/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_059/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_059/tests/validate_ui_behavior.js b/task_059/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..e3266a1fb95e2900ca917a74a1aa5df63c3f7d1b --- /dev/null +++ b/task_059/tests/validate_ui_behavior.js @@ -0,0 +1,172 @@ +// Tiered deterministic correctness verifier for the Sokoban task. +// Drives window.__game with EXPLICIT levels (no RNG) and asserts exact state +// transitions against an independent reference simulation. Prints PASS/FAIL per +// tier and a final SCORE= used by test.sh as the (partial) reward. +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +function assert(cond, msg) { if (!cond) throw new Error(msg); } + +// --- independent reference model (mirrors the spec) ----------------------- +const DELTAS = { U: [-1, 0], D: [1, 0], L: [0, -1], R: [0, 1] }; + +function parse(grid) { + const rows = grid.map(r => r.split('')); + const height = rows.length; + const width = Math.max(...rows.map(r => r.length)); + const walls = new Set(), targets = [], boxes = []; + let player = null; + for (let r = 0; r < height; r++) for (let c = 0; c < width; c++) { + const ch = rows[r][c] || ' '; + if (ch === '#') walls.add(r + ',' + c); + if (ch === '.' || ch === '*' || ch === '+') targets.push([r, c]); + if (ch === '$' || ch === '*') boxes.push([r, c]); + if (ch === '@' || ch === '+') player = { r, c }; + } + return { width, height, walls, targets, boxes, player, moves: 0 }; +} + +function simMove(m, dir) { + const d = DELTAS[dir]; + if (!d) return m; + const won = m.boxes.every(b => m.targets.some(t => t[0] === b[0] && t[1] === b[1])); + if (won) return m; + const nr = m.player.r + d[0], nc = m.player.c + d[1]; + if (nr < 0 || nc < 0 || nr >= m.height || nc >= m.width || m.walls.has(nr + ',' + nc)) return m; + const bi = m.boxes.findIndex(b => b[0] === nr && b[1] === nc); + if (bi >= 0) { + const br = nr + d[0], bc = nc + d[1]; + if (br < 0 || bc < 0 || br >= m.height || bc >= m.width || m.walls.has(br + ',' + bc) || m.boxes.some(b => b[0] === br && b[1] === bc)) return m; + m.boxes[bi] = [br, bc]; + } + m.player = { r: nr, c: nc }; + m.moves += 1; + return m; +} + +function refStatus(m) { + return m.boxes.every(b => m.targets.some(t => t[0] === b[0] && t[1] === b[1])) ? 'won' : 'playing'; +} + +function sortBoxes(bs) { return bs.map(b => [b[0], b[1]]).sort((a, b) => a[0] - b[0] || a[1] - b[1]); } +function eqBoxes(a, b) { a = sortBoxes(a); b = sortBoxes(b); return a.length === b.length && a.every((x, i) => x[0] === b[i][0] && x[1] === b[i][1]); } + +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 520, height: 640 } }); + const errs = []; + await page.route(/^https?:\/\//, route => route.abort()); + page.on('pageerror', e => errs.push(e.message)); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(300); + const run = (fn, arg) => page.evaluate(fn, arg); + + const hasApi = await page.evaluate(() => !!(window.__game + && typeof window.__game.init === 'function' + && typeof window.__game.getState === 'function' + && typeof window.__game.move === 'function')); + + // Level: player can walk right on floor, push a box onto the target. + // row0: ####### + // row1: #@ $ .# (player at (1,1), box at (1,3), target at (1,5)) + // row2: ####### + const L = { grid: ['#######', '#@ $ .#', '#######'] }; + + const tiers = [ + ['T1 API + init parses level (player/boxes/targets/dims, status playing, moves 0)', async () => { + assert(hasApi, 'window.__game with init/getState/move is required'); + assert(errs.length === 0, 'no page errors allowed: ' + errs.join(' | ')); + const st = await run((L) => window.__game.init(L), L); + const ref = parse(L.grid); + assert(st.width === ref.width && st.height === ref.height, `dims must be ${ref.width}x${ref.height}, got ${st.width}x${st.height}`); + assert(st.player.r === ref.player.r && st.player.c === ref.player.c, 'player start position wrong'); + assert(eqBoxes(st.boxes, ref.boxes), 'boxes parsed wrong: ' + JSON.stringify(st.boxes)); + assert(eqBoxes(st.targets, ref.targets), 'target coordinates wrong'); + assert(eqBoxes(st.walls, [...ref.walls].map(key => key.split(',').map(Number))), 'wall coordinates wrong'); + assert(st.status === 'playing', 'fresh status must be playing, got ' + st.status); + assert(st.moves === 0, 'fresh moves must be 0, got ' + st.moves); + }], + + ['T2 legal floor move updates player + increments moves; wall move is a no-op', async () => { + let st = await run((L) => window.__game.init(L), L); + const ref = parse(L.grid); + // move Right onto floor (1,2) + st = await run(() => window.__game.move('R')); + simMove(ref, 'R'); + assert(st.player.r === ref.player.r && st.player.c === ref.player.c, 'player should move right onto floor'); + assert(st.moves === ref.moves && st.moves === 1, 'successful move must increment moves to 1, got ' + st.moves); + // move Up into wall (0,2) -> no-op + st = await run(() => window.__game.move('U')); + assert(st.player.r === ref.player.r && st.player.c === ref.player.c, 'wall move must not change player position'); + assert(st.moves === 1, 'illegal (wall) move must not increment moves, got ' + st.moves); + }], + + ['T3 push box onto floor; pushing a box into a wall is blocked', async () => { + // fresh: from start, R puts player at (1,2); R again pushes box (1,3)->(1,4), player (1,3) + let st = await run((L) => { window.__game.init(L); window.__game.move('R'); return window.__game.move('R'); }, L); + const ref = parse(L.grid); simMove(ref, 'R'); simMove(ref, 'R'); + assert(st.player.r === 1 && st.player.c === 3, 'player should be at (1,3) after pushing box'); + assert(eqBoxes(st.boxes, ref.boxes) && st.boxes.some(b => b[0] === 1 && b[1] === 4), 'box should be pushed to (1,4)'); + assert(st.moves === 2, 'two successful moves expected, got ' + st.moves); + // Now box at (1,4), target at (1,5). Push R: box ->(1,5) on target. + // Then try push again R: box would go to (1,6) which is wall -> blocked. + st = await run(() => window.__game.move('R')); + assert(st.boxes.some(b => b[0] === 1 && b[1] === 5), 'box should be pushed onto target (1,5)'); + const before = st.boxes; + st = await run(() => window.__game.move('R')); + assert(eqBoxes(st.boxes, before), 'pushing box into wall must be blocked (boxes unchanged)'); + // A non-terminal wall block cannot be masked by the won-state freeze. + const blockedLevel = {grid:['######','#@$#.#','######']}; + const blockedStart = await run(level => window.__game.init(level), blockedLevel); + const blockedEnd = await run(() => window.__game.move('R')); + assert(require('./state_equal.js')(blockedStart,blockedEnd), 'non-terminal wall-backed box must not move'); + }], + + ['T4 win detection: pushing the last box onto target sets status won', async () => { + // One push solves it: player @ (1,1), box (1,2), target (1,3) + const W = { grid: ['#####', '#@$.#', '#####'] }; + let st = await run((W) => { window.__game.init(W); return window.__game.move('R'); }, W); + assert(st.boxes.some(b => b[0] === 1 && b[1] === 3), 'box should reach target (1,3)'); + assert(st.status === 'won', 'all boxes on targets must set status won, got ' + st.status); + // further moves are no-ops once won + const movesAtWin = st.moves; + st = await run(() => window.__game.move('L')); + assert(st.status === 'won' && st.moves === movesAtWin, 'moves after win must be ignored'); + }], + + ['T5 render-reflection: DOM mirrors state (box/player/target cells)', async () => { + const st = await run((L) => window.__game.init(L), L); + const dom = await run(() => ({ + boxes: document.querySelectorAll('#board .cell.box').length, + player: document.querySelectorAll('#board .cell.player').length, + targets: document.querySelectorAll('#board .cell.target').length, + cells: document.querySelectorAll('#board .cell').length, + })); + assert(dom.cells === st.width * st.height, `DOM must render ${st.width * st.height} cells, got ${dom.cells}`); + assert(dom.boxes === st.boxes.length, `DOM .box count ${dom.boxes} must equal boxes ${st.boxes.length}`); + assert(dom.player === 1, 'exactly one .player cell must be rendered'); + assert(dom.targets === st.targets.length, `DOM .target count ${dom.targets} must equal targets ${st.targets.length}`); + // after a push the DOM must update too + await run(() => { window.__game.move('R'); window.__game.move('R'); }); + const dom2 = await run(() => document.querySelectorAll('#board .cell.box').length); + const st2 = await run(() => window.__game.getState()); + assert(dom2 === st2.boxes.length, 'DOM box count must track state after moves'); + await require('./validate_render_mirror.js')(page,106); + const fs = require('node:fs'); + fs.mkdirSync('/logs/verifier/visual',{recursive:true}); + await page.screenshot({path:'/logs/verifier/visual/board-desktop.png',fullPage:true}); + await page.setViewportSize({width:390,height:844}); + await page.screenshot({path:'/logs/verifier/visual/board-mobile.png',fullPage:true}); + }], + ]; + + let passed = 0; + for (const [name, fn] of tiers) { + try { await fn(); if(name.startsWith('T5'))await require('./validate_render_mirror.js')(page,106); passed++; console.log('PASS ' + name); } + catch (e) { console.log('FAIL ' + name + ': ' + (e && e.message || e)); } + } + console.log('TIERS ' + passed + '/' + tiers.length); + console.log('SCORE=' + (passed / tiers.length).toFixed(3)); + await browser.close(); +})().catch(e => { console.log('FATAL ' + (e && e.stack || e)); console.log('SCORE=0'); }); diff --git a/task_060/acceptance_checklist.json b/task_060/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..aeda721f8b9f378d72a3f2c5df5a28d129cd8d5d --- /dev/null +++ b/task_060/acceptance_checklist.json @@ -0,0 +1,22 @@ +{ + "task_id": 107, + "category": "frontend_development", + "language": "javascript", + "acceptance_items": [ + "init builds size*size grid from lit set; status correct, moves 0.", + "Single press toggles center + in-bounds neighbors only; moves+1.", + "Two presses compose; pressing same cell twice restores grid unless first press already wins.", + "Win when all lights off; presses ignored after win.", + "Visible, non-overlapping DOM positions mirror state after every transition; actual cells and history buttons are interactive.", + "Undo/redo/reset preserve complete state and history semantics, including terminal restoration and no-op actions; history is an explicit hard gate." + ], + "expected_outputs": [ + "index.html" + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "risk_notes": [ + "Render-reflection tier defeats no-render in-memory engines.", + "Corner-press tier defeats fixed-5-cell toggles that ignore board bounds." + ], + "repair_revision": "2026-09-29" +} diff --git a/task_060/environment/Dockerfile b/task_060/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2f855b3d12b4e80dd6cd135513202206e95ccdba --- /dev/null +++ b/task_060/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# The mcr/playwright base ships browsers but NOT the `playwright` npm package, +# which the verifier's require('playwright') needs. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_060/environment/code/README.md b/task_060/environment/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5b46c50ad63068c4709d9596bb93a5015cc3800f --- /dev/null +++ b/task_060/environment/code/README.md @@ -0,0 +1,6 @@ +# lightsout — starter + +Implement the game in a single self-contained `index.html` (inline CSS/JS, no +external network). Expose a deterministic `window.__game` API as described in the +task instruction so the verifier can drive it with explicit scenarios. The +rendered DOM must mirror the in-memory game state. diff --git a/task_060/environment/docker-compose.yaml b/task_060/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_060/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_060/instruction.md b/task_060/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fcb1f8d3941d4ad677b031cf5cdabd2d565dc584 --- /dev/null +++ b/task_060/instruction.md @@ -0,0 +1,17 @@ +# Build Lights Out with undo and redo + +Create one self-contained offline `index.html`. Show a square board of lights and visible clickable Undo and Redo buttons. + +## State and controls + +Expose `window.__game` with `init(level)`, `getState()`, `press(r,c)`, `undo()`, `redo()` and `reset()`. Each action returns the resulting `{size,grid,moves,status}`. + +The level is `{size,on:[[r,c],...]}`, with positive size and zero-based coordinates. `grid` is a row-major boolean array of length `size*size`; `true` means lit. Status is `playing` or `won`. Inside `#board`, use one visible `.cell` per position in row-major order, with class `on` only when lit. Mark the history buttons `data-testid="undo"` and `"redo"`. + +## Acceptance Checklist + +- Initialize from the supplied set of lit cells, ignoring out-of-bounds positions, resetting moves to zero and immediately recognizing an all-off winning board. +- An in-bounds press during play toggles the chosen light and its existing orthogonal neighbors, never diagonals or cells across an edge. Count one move per valid press. Two presses on the same cell restore the layout if the first did not already win. +- Winning freezes further presses; out-of-bounds presses are no-ops. Neither changes history. +- Undo and redo step through complete previous and next states, including moves and status, and do nothing when there is no state in that direction. Undo can leave a winning state; redo can restore it. A new legal press after undo discards the abandoned future. Init and reset clear the history; reset restores the most recent initial layout. +- Cell clicks and history buttons use the same state transitions as the API. Render a non-overlapping grid that mirrors every light position immediately after each action. diff --git a/task_060/quality_notes.md b/task_060/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..c78316aeeaa9fa1f40d9d5b252080c0fd5b6f0d6 --- /dev/null +++ b/task_060/quality_notes.md @@ -0,0 +1,15 @@ +# Quality notes — task_107 + +## 2026-10-08 deep review + +- Active scoring is implemented by the executable verifier in tests/ and disclosed in instruction.md; older five-tier descriptions below refer to the base suite only. +- History is an explicitly disclosed hard gate. Independent state/history traces use semantic field comparison, real button clicks, terminal undo/redo, invalid actions, reset, and per-step visible DOM checks. +- Remote oracle/nop, targeted defect, alternate implementation, repeated runs, and screenshots are tracked separately in the review ledger. Static inspection alone is not a runtime pass or proof of model discrimination. + +- Deterministic: levels are explicit `{size, on}` layouts; no RNG. +- Discrimination via 5 tiers (init / single-press toggle set / composition / + win / render-reflection), fractional reward = tiers passed. +- T2 uses a corner press so a solution that toggles a fixed 5-cell plus without + clipping to bounds fails. T3 checks toggle is its own inverse. An in-memory + engine that does not render fails T5. +- Verifier uses an independent reference simulation, not source grep. diff --git a/task_060/solution/README.md b/task_060/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bcc91f532749b521869cc99a5283378dc901f08e --- /dev/null +++ b/task_060/solution/README.md @@ -0,0 +1,11 @@ +# Reference solution — task_107 (Lights Out) + +Self-contained `index.html`. `window.__game` builds a `size×size` boolean light +grid from an explicit lit set, `press(r,c)` toggles the cell plus its in-bounds +orthogonal neighbors, counts only legal presses, detects win when all lights are +off, and renders a DOM board that mirrors state (`.cell`, `.cell.on`). + +Two snapshot stacks implement undo/redo, including after winning. Legal presses +clear the redo stack; invalid and frozen presses leave history untouched. Reset +restores the last initialized layout and clears history. Actual buttons use the +same history functions as the deterministic API. diff --git a/task_060/solution/code/index.html b/task_060/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..21750d58ded80f71685a4b499421760e31e7b625 --- /dev/null +++ b/task_060/solution/code/index.html @@ -0,0 +1,130 @@ + + + + +Lights Out + + + +
      Moves: 0 — Status: playing
      +
      + + + diff --git a/task_060/solution/solve.sh b/task_060/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_060/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_060/task.toml b/task_060/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_060/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_060/task_meta.json b/task_060/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..951162040754148576b5ee83fb24dfa3c4d66304 --- /dev/null +++ b/task_060/task_meta.json @@ -0,0 +1,15 @@ +{ + "task_id": 107, + "task_category": "frontend_development", + "origin_model": "authored", + "sample_count": 0, + "user_turns": 0, + "language": "javascript", + "input_assets": [], + "expected_outputs": [ + "index.html" + ], + "source_row_id": null, + "repair_revision": "2026-09-29", + "instruction_sha256": "f771338e6d1cded6beb17ca34c85bfe04dcd8c4fc6de0ae505b8ba5c14fae887" +} diff --git a/task_060/tests/_shared/contract_checker.js b/task_060/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_060/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_060/tests/_shared/static_enhancer.sh b/task_060/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_060/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_060/tests/enhancement_cases.json b/task_060/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..9aa05981dce07fd0751423584ff7b9f93cfd9c1a --- /dev/null +++ b/task_060/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","instruction_evidence":"创建 size×size 的网格,把 on 中列出的坐标点亮(其余熄灭)……越界坐标忽略。","validator":"validate_enhanced_cases.js","behavior":"混入负行、行上界、列上界三种越界坐标,验证仅合法坐标点亮。"}, + {"case_id":"ENHANCED_CASE_2","instruction_evidence":"角格只有 2 个邻居、边格 3 个邻居、内格 4 个邻居;只切换在界内的格子(连同自身)。","validator":"validate_enhanced_cases.js","behavior":"按下 5×5 顶边非角格,精确验证四个切换位置。"}, + {"case_id":"ENHANCED_CASE_3","instruction_evidence":"若初始即全灭则为 'won'……获胜后再调用 press 无效。","validator":"validate_enhanced_cases.js","behavior":"全灭初始化后按合法格,验证状态完全不变。"} +] diff --git a/task_060/tests/review_hard.js b/task_060/tests/review_hard.js new file mode 100644 index 0000000000000000000000000000000000000000..77dbec3506e114c23aabcac48ab3adfe9b93a52e --- /dev/null +++ b/task_060/tests/review_hard.js @@ -0,0 +1,4 @@ +require('./review_history.js')(107).catch(error => { + console.error(error); + process.exitCode = 1; +}); diff --git a/task_060/tests/review_history.js b/task_060/tests/review_history.js new file mode 100644 index 0000000000000000000000000000000000000000..52d5a6a6ab3b9a347f175d0e00f5d1bdb6b57cf2 --- /dev/null +++ b/task_060/tests/review_history.js @@ -0,0 +1,103 @@ +// Independent transition/history model; object key order is not semantic. +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const {pathToFileURL} = require('node:url'); +const {chromium} = require('playwright'); +const mirror = require('./validate_render_mirror.js'); +const clone = value => JSON.parse(JSON.stringify(value)); + +module.exports = async function checkHistory(id) { + const browser = await chromium.launch({headless:true, args:['--no-sandbox']}); + try { + const page = await browser.newPage({viewport:{width:520,height:640}}); + page.setDefaultTimeout(5000); + await page.route(/^https?:\/\//, route => route.abort()); + await page.goto(pathToFileURL(path.join(process.argv[2] || process.cwd(), 'index.html')).href); + let state, initial, timeline, cursor; + const terminal = id === 107 ? 'won' : 'solved'; + const action = id === 107 ? 'press' : 'move'; + const project = value => id === 107 + ? {size:value.size,grid:value.grid,moves:value.moves,status:value.status} + : {size:value.size,tiles:value.tiles,blank:value.blank,moves:value.moves,status:value.status}; + function setStatus() { + state.status = id === 107 + ? (state.grid.every(value => value === false) ? terminal : 'playing') + : (state.tiles.every((value,index) => value === (index + 1) % state.tiles.length) ? terminal : 'playing'); + } + function initialize(level) { + if (id === 107) { + const grid = Array(level.size ** 2).fill(false); + for (const [r,c] of level.on) if (r >= 0 && c >= 0 && r < level.size && c < level.size) grid[r*level.size+c] = true; + state = {size:level.size,grid,moves:0}; + } else state = {size:level.size,tiles:level.tiles.slice(),blank:level.tiles.indexOf(0),moves:0}; + setStatus(); initial = clone(state); timeline = [clone(state)]; cursor = 0; + } + function transition(method,args) { + if (method === 'init') return initialize(args[0]); + if (method === 'reset') { state = clone(initial); timeline = [clone(state)]; cursor = 0; return; } + if (method === 'undo' || method === 'redo') { + cursor = Math.max(0,Math.min(timeline.length-1,cursor+(method==='undo'?-1:1))); + state = clone(timeline[cursor]); return; + } + const [r,c] = args; + if (state.status === terminal || r < 0 || c < 0 || r >= state.size || c >= state.size) return; + if (id === 107) { + for (let row=0;rowwindow.__game[method](...args),{method,args}); + assert.deepEqual(project(result),state,method+' return state'); + } + const actual=await page.evaluate(()=>window.__game.getState()); + assert.deepEqual(project(actual),state,method+' getState'); + await mirror(page,id); + console.log('PASS history '+method+' '+JSON.stringify(args)+(button?' real-click':'')); + } + const level=id===107?{size:3,on:[[0,0]]}:{size:3,tiles:[1,2,3,4,0,6,7,5,8]}; + await step('init',[level]); + await step('undo'); await step('redo'); + await step(action,[0,1],true); await step(action,[1,1]); + await step('undo',[],true); await step('undo'); await step('undo'); + await step(action,[-1,-1]); await step('redo'); await step('redo',[],true); await step('redo'); + await step('undo',[],true); await step(action,[0,0],true); await step('redo'); + await step('reset'); await step('undo'); await step('redo'); + // Solve in one move, attempt a frozen action, then restore both sides of the terminal state. + const winning=id===107?{size:1,on:[[0,0]]}:{size:2,tiles:[1,2,0,3]}; + await step('init',[winning]); + await step(action,id===107?[0,0]:[1,1],true); + await step(action,[0,0]); + await step('undo',[],true); await step('redo',[],true); + await step('undo'); await step('init',[level]); await step('redo'); await step('undo'); + // Longer deterministic traces exercise mixed no-ops and history boundaries. + for (const coords of [[2,1],[1,2],[2,2],[0,0],[1,0],[0,2],[1,1]]) await step(action,coords); + for (let i=0;i<9;i++) await step('undo'); + for (let i=0;i<9;i++) await step('redo'); + const directory='/logs/verifier/visual'; + fs.mkdirSync(directory,{recursive:true}); + await page.screenshot({path:path.join(directory,'history-desktop.png'),fullPage:true}); + await page.setViewportSize({width:390,height:844}); + await page.screenshot({path:path.join(directory,'history-mobile.png'),fullPage:true}); + console.log('PASS history, terminal restoration, DOM and real buttons'); + } finally { await browser.close(); } +}; + diff --git a/task_060/tests/review_legacy.sh b/task_060/tests/review_legacy.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d550948c62e3205779de94410435fe363acddc8 --- /dev/null +++ b/task_060/tests/review_legacy.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +[ -f index.html ] || exit 0 +OUT=$(run validate_ui_behavior.js 2>&1); RC=$?; printf '%s +' "$OUT" +CORE=$(printf '%s +' "$OUT" | sed -n 's/^SCORE=//p' | tail -1) +if [ "$RC" -ne 0 ] || [ -z "$CORE" ]; then CORE=0; fi +OUT=$(run validate_enhanced_cases.js 2>&1); RC=$?; printf '%s +' "$OUT" +ENH=$(printf '%s +' "$OUT" | sed -n 's/^ENHANCED_SCORE=//p' | tail -1) +if [ "$RC" -ne 0 ] || [ -z "$ENH" ]; then ENH=0; fi +node -e 'const [a,b]=process.argv.slice(1).map(Number);if(![a,b].every(x=>Number.isFinite(x)&&x>=0&&x<=1))process.exit(1);console.log((5*a+3*b)/8)' "$CORE" "$ENH" > "$REWARD_FILE" +cat "$REWARD_FILE" diff --git a/task_060/tests/test.sh b/task_060/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a220175c3cba51e53d35c25d20af343b1f3df372 --- /dev/null +++ b/task_060/tests/test.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -uo pipefail +bash /tests/review_legacy.sh +CORE=$(cat /logs/verifier/reward.txt 2>/dev/null || echo 0) +mkdir -p /logs/verifier +timeout -k 5s 90s node /tests/review_hard.js /app 2>&1 | tee /logs/verifier/review_hard.log +RC=${PIPESTATUS[0]} +if [ "$RC" -ne 0 ]; then echo "REVIEW_HARD failed with exit code $RC"; fi +if [ "$RC" -eq 0 ]; then echo "$CORE"; else echo 0; fi > /logs/verifier/reward.txt +exit 0 diff --git a/task_060/tests/validate_aaav_dynamic.js b/task_060/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..edbde691853822808ba647c585460fedafef4e53 --- /dev/null +++ b/task_060/tests/validate_aaav_dynamic.js @@ -0,0 +1,17 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +const TASK_ID = 107; +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage(); + const errs = []; + page.on('pageerror', e => errs.push(e.message)); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + const ok = await page.evaluate(() => !!(window.__game && typeof window.__game.getState === 'function')); + await browser.close(); + if (errs.length) throw new Error('page errors: ' + errs.join(' | ')); + if (!ok) throw new Error('window.__game.getState missing'); + console.log('AAAV dynamic gate passed for task ' + TASK_ID); +})().catch(e => { console.error('AAAV FAIL: ' + e.message); process.exit(1); }); diff --git a/task_060/tests/validate_browser_smoke.js b/task_060/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_060/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_060/tests/validate_enhanced_cases.js b/task_060/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..77306bfa8c6ce87a7b0abb16560b0267f5566f8a --- /dev/null +++ b/task_060/tests/validate_enhanced_cases.js @@ -0,0 +1,34 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +function assert(x, m) { if (!x) throw new Error(m); } +(async () => { + const browser = await chromium.launch({ headless: true, args: ['--no-sandbox', '--disable-dev-shm-usage'] }); + const page = await browser.newPage({ viewport: { width: 520, height: 640 } }); + await page.route(/^https?:\/\//, route => route.abort()); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded', timeout: 10000 }); + const cases = [ + // ENHANCED_CASE_1: out-of-range initial coordinates are ignored. + ['ENHANCED_CASE_1', async () => { + const st = await page.evaluate(() => window.__game.init({ size: 3, on: [[0, 0], [-1, 0], [3, 2], [1, 3]] })); + assert(st.grid.length === 9 && st.grid.filter(Boolean).length === 1 && st.grid[0] === true, 'only the in-range light may be on'); + assert(st.moves === 0 && st.status === 'playing', 'init must reset moves and status'); + }], + // ENHANCED_CASE_2: an edge (non-corner) press toggles self plus exactly three neighbors. + ['ENHANCED_CASE_2', async () => { + const st = await page.evaluate(() => { window.__game.init({ size: 5, on: [[4, 4]] }); return window.__game.press(0, 2); }); + const lit = st.grid.map((v, i) => v ? i : -1).filter(i => i >= 0); + assert(require("node:util").isDeepStrictEqual(lit,[1, 2, 3, 7, 24]), 'top-edge press must toggle indices 1,2,3,7 and preserve unrelated light 24'); + assert(st.moves === 1, 'legal edge press increments moves once'); + }], + // ENHANCED_CASE_3: an all-off initial board is won and immutable. + ['ENHANCED_CASE_3', async () => { + const won = await page.evaluate(() => window.__game.init({ size: 2, on: [] })); + assert(won.status === 'won' && won.moves === 0, 'all-off init must be won'); + const after = await page.evaluate(() => window.__game.press(0, 0)); + assert(require("node:util").isDeepStrictEqual(after,won), 'press after win must be ignored'); + }], + ]; + let passed=0; for (const [id, fn] of cases) { try { await fn(); passed++; console.log('PASS '+id); } catch(e) { console.error('FAIL '+id+': '+e.message); } } console.log('ENHANCED_SCORE='+(passed/cases.length)); + await browser.close(); +})().catch(e => { console.error(e.stack || e); process.exit(1); }); diff --git a/task_060/tests/validate_render_mirror.js b/task_060/tests/validate_render_mirror.js new file mode 100644 index 0000000000000000000000000000000000000000..a9dc3edbaaff46467d6085e3e504af8f44c37af3 --- /dev/null +++ b/task_060/tests/validate_render_mirror.js @@ -0,0 +1,46 @@ +// Check the visible board against public state, independent of source names. +const assert = require('node:assert/strict'); +module.exports = async function mirror(page, id) { + const { state, cells } = await page.evaluate(id => { + const state = window.__game.getState(); + const selector = id === 108 ? '.tile' : '.cell'; + const cells = [...document.querySelectorAll('#board ' + selector)].map(element => { + const rect = element.getBoundingClientRect(); + return { classes: [...element.classList], value: Number(element.dataset.v), + text: element.textContent.trim(), top: rect.top, left: rect.left, + width: rect.width, height: rect.height, + visible: element.checkVisibility({checkOpacity:true, checkVisibilityCSS:true}) }; + }); + cells.sort((a, b) => Math.abs(a.top - b.top) > 2 ? a.top - b.top : a.left - b.left); + return { state, cells }; + }, id); + const width = id === 106 ? state.width : state.size; + const height = id === 106 ? state.height : state.size; + assert.equal(cells.length, width * height, 'board cell count'); + const at = (positions, r, c) => positions.some(p => p[0] === r && p[1] === c); + cells.forEach((cell, index) => { + const r = Math.floor(index / width), c = index % width; + assert(cell.visible && cell.width > 0 && cell.height > 0, 'visible cell ' + index); + if (c > 0) { + const previous = cells[index - 1]; + assert(cell.left >= previous.left + previous.width - 1, 'non-overlapping columns'); + } + if (r > 0) { + const above = cells[index - width]; + assert(cell.top >= above.top + above.height - 1, 'non-overlapping rows'); + } + const has = cls => cell.classes.includes(cls); + if (id === 106) { + for (const [cls, positions] of [['wall', state.walls], ['box', state.boxes], ['target', state.targets]]) { + assert.equal(has(cls), at(positions, r, c), cls + ' at ' + index); + } + assert.equal(has('player'), state.player.r === r && state.player.c === c, 'player position'); + } else if (id === 107) { + assert.equal(has('on'), state.grid[index], 'light position ' + index); + } else { + assert.equal(cell.value, state.tiles[index], 'tile data-v ' + index); + assert.equal(cell.text, state.tiles[index] ? String(state.tiles[index]) : '', 'visible tile label'); + assert.equal(has('blank'), state.tiles[index] === 0, 'blank position'); + } + }); +}; diff --git a/task_060/tests/validate_semantics.js b/task_060/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_060/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_060/tests/validate_ui_behavior.js b/task_060/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..b53b20f2c6b1ff7d30cfbb861fa94d55abac1f4c --- /dev/null +++ b/task_060/tests/validate_ui_behavior.js @@ -0,0 +1,141 @@ +// Tiered deterministic correctness verifier for the Lights Out task. +// Drives window.__game with EXPLICIT levels (no RNG) and asserts exact state +// transitions against an INDEPENDENT reference simulation. Prints PASS/FAIL per +// tier and a final SCORE= used by test.sh as the (partial) reward. +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +function assert(cond, msg) { if (!cond) throw new Error(msg); } + +// --- independent reference model (mirrors the spec) ----------------------- +const DELTAS = [[0, 0], [-1, 0], [1, 0], [0, -1], [0, 1]]; + +function refInit(level) { + const size = level.size; + const grid = new Array(size * size).fill(false); + for (const [r, c] of (level.on || [])) { + if (r >= 0 && r < size && c >= 0 && c < size) grid[r * size + c] = true; + } + return { size, grid, moves: 0, status: refStatus(grid) }; +} +function refStatus(grid) { return grid.every(v => !v) ? 'won' : 'playing'; } +function refPress(m, r, c) { + if (m.status === 'won') return m; + const size = m.size; + if (r < 0 || r >= size || c < 0 || c >= size) return m; + for (const [dr, dc] of DELTAS) { + const nr = r + dr, nc = c + dc; + if (nr >= 0 && nr < size && nc >= 0 && nc < size) { + const i = nr * size + nc; + m.grid[i] = !m.grid[i]; + } + } + m.moves += 1; + m.status = refStatus(m.grid); + return m; +} +function eqGrid(a, b) { + return a.length === b.length && a.every((v, i) => !!v === !!b[i]); +} +function litCount(grid) { return grid.reduce((n, v) => n + (v ? 1 : 0), 0); } + +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 520, height: 640 } }); + const errs = []; + await page.route(/^https?:\/\//, route => route.abort()); + page.on('pageerror', e => errs.push(e.message)); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(300); + const run = (fn, arg) => page.evaluate(fn, arg); + + const hasApi = await page.evaluate(() => !!(window.__game + && typeof window.__game.init === 'function' + && typeof window.__game.getState === 'function' + && typeof window.__game.press === 'function')); + + // A 4x4 level with a scattered lit set (no special structure). + const L = { size: 4, on: [[0, 0], [0, 2], [1, 3], [2, 1], [3, 3]] }; + + const tiers = [ + ['T1 API + init parses level (size/dims/initial lit set, status playing, moves 0)', async () => { + assert(hasApi, 'window.__game with init/getState/press is required'); + assert(errs.length === 0, 'no page errors allowed: ' + errs.join(' | ')); + const st = await run((L) => window.__game.init(L), L); + const ref = refInit(L); + assert(st.size === ref.size, `size must be ${ref.size}, got ${st.size}`); + assert(Array.isArray(st.grid) && st.grid.length === ref.size * ref.size, + `grid must be ${ref.size * ref.size} booleans, got ${st.grid && st.grid.length}`); + assert(eqGrid(st.grid, ref.grid), 'initial lit set wrong: ' + JSON.stringify(st.grid)); + assert(st.status === 'playing', 'fresh status must be playing, got ' + st.status); + assert(st.moves === 0, 'fresh moves must be 0, got ' + st.moves); + }], + + ['T2 single press toggles exactly center + in-bounds neighbors; moves+1', async () => { + let st = await run((L) => window.__game.init(L), L); + const ref = refInit(L); + // press a corner (0,0): toggles (0,0),(1,0),(0,1) — only 3 in-bounds. + st = await run(() => window.__game.press(0, 0)); + refPress(ref, 0, 0); + assert(eqGrid(st.grid, ref.grid), 'corner press did not toggle exactly center+in-bounds neighbors: ' + JSON.stringify(st.grid)); + assert(st.moves === ref.moves && st.moves === 1, 'press must increment moves to 1, got ' + st.moves); + // press an interior cell (2,2): toggles 5 cells. + st = await run(() => window.__game.press(2, 2)); + refPress(ref, 2, 2); + assert(eqGrid(st.grid, ref.grid), 'interior press did not toggle exactly the 5-cell plus: ' + JSON.stringify(st.grid)); + assert(st.moves === 2, 'second press must increment moves to 2, got ' + st.moves); + }], + + ['T3 two presses compose (order-independent toggling) correctly', async () => { + // Compose two presses and compare to independent recompute. + let st = await run((L) => { window.__game.init(L); window.__game.press(1, 1); return window.__game.press(3, 0); }, L); + const ref = refInit(L); refPress(ref, 1, 1); refPress(ref, 3, 0); + assert(eqGrid(st.grid, ref.grid), 'two composed presses wrong: ' + JSON.stringify(st.grid)); + assert(st.moves === 2, 'two presses expected, got ' + st.moves); + // Pressing the same cell twice must cancel back to the post-init grid. + const baseRef = refInit(L); + let st2 = await run((L) => { window.__game.init(L); window.__game.press(2, 2); return window.__game.press(2, 2); }, L); + assert(eqGrid(st2.grid, baseRef.grid), 'pressing a cell twice must restore the grid (toggle is its own inverse)'); + assert(st2.moves === 2, 'two presses must still count as 2 moves, got ' + st2.moves); + }], + + ['T4 reaching all-off sets status won (known solvable plus pattern)', async () => { + // Start all-off, then a single press on (1,1) of a 3x3 lights the plus. + // So if we INIT with exactly that plus lit, pressing (1,1) clears it. + const W = { size: 3, on: [[1, 1], [0, 1], [2, 1], [1, 0], [1, 2]] }; + const ref = refInit(W); refPress(ref, 1, 1); + assert(ref.status === 'won', 'reference: pressing center should clear the plus'); + let st = await run((W) => { window.__game.init(W); return window.__game.press(1, 1); }, W); + assert(eqGrid(st.grid, ref.grid) && st.grid.every(v => !v), 'grid should be all-off after the solving press'); + assert(st.status === 'won', 'all lights off must set status won, got ' + st.status); + // further presses ignored once won + const movesAtWin = st.moves; + st = await run(() => window.__game.press(0, 0)); + assert(st.status === 'won' && st.moves === movesAtWin, 'presses after win must be ignored'); + }], + + ['T5 render-reflection: DOM .cell.on count == lit count, .cell count == size*size', async () => { + const st = await run((L) => window.__game.init(L), L); + const dom = await run(() => ({ + cells: document.querySelectorAll('#board .cell').length, + on: document.querySelectorAll('#board .cell.on').length, + })); + assert(dom.cells === st.size * st.size, `DOM must render ${st.size * st.size} cells, got ${dom.cells}`); + assert(dom.on === litCount(st.grid), `DOM .cell.on count ${dom.on} must equal lit count ${litCount(st.grid)}`); + // after a press the DOM must update too + const st2 = await run(() => window.__game.press(1, 1)); + const dom2 = await run(() => document.querySelectorAll('#board .cell.on').length); + assert(dom2 === litCount(st2.grid), `DOM .cell.on must track state after press: dom ${dom2} vs lit ${litCount(st2.grid)}`); + }], + ]; + + let passed = 0; + for (const [name, fn] of tiers) { + try { await fn(); if(name.startsWith('T5'))await require('./validate_render_mirror.js')(page,107); passed++; console.log('PASS ' + name); } + catch (e) { console.log('FAIL ' + name + ': ' + (e && e.message || e)); } + } + console.log('TIERS ' + passed + '/' + tiers.length); + console.log('SCORE=' + (passed / tiers.length).toFixed(3)); + await browser.close(); +})().catch(e => { console.log('FATAL ' + (e && e.stack || e)); console.log('SCORE=0'); }); diff --git a/task_061/acceptance_checklist.json b/task_061/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..9ef455f61cd33c41a4c04266bb13f1d0d5965d01 --- /dev/null +++ b/task_061/acceptance_checklist.json @@ -0,0 +1,22 @@ +{ + "task_id": 108, + "category": "frontend_development", + "language": "javascript", + "acceptance_items": [ + "init parses size/tiles/blank; status correct, moves 0.", + "Valid slide swaps tile and blank; moves+1; blank index updates.", + "Non-adjacent / out-of-bounds move is a no-op with no move count.", + "Reaching [1..n-1,0] sets status solved; moves ignored after.", + "Visible, non-overlapping DOM tiles show numbers and match data-v order; exactly one blank follows the state.", + "Undo/redo/reset preserve complete state and history semantics, including terminal restoration and no-op actions; actual cell/history buttons work; history is an explicit hard gate." + ], + "expected_outputs": [ + "index.html" + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "risk_notes": [ + "Render-reflection tier defeats no-render in-memory engines.", + "Invalid-move tier defeats solutions that swap any clicked cell." + ], + "repair_revision": "2026-09-29" +} diff --git a/task_061/environment/Dockerfile b/task_061/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2f855b3d12b4e80dd6cd135513202206e95ccdba --- /dev/null +++ b/task_061/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# The mcr/playwright base ships browsers but NOT the `playwright` npm package, +# which the verifier's require('playwright') needs. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_061/environment/code/README.md b/task_061/environment/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c1cbcbc40d2381e1d3a2ca087556b5476b15a4ab --- /dev/null +++ b/task_061/environment/code/README.md @@ -0,0 +1,6 @@ +# slidingpuzzle — starter + +Implement the game in a single self-contained `index.html` (inline CSS/JS, no +external network). Expose a deterministic `window.__game` API as described in the +task instruction so the verifier can drive it with explicit scenarios. The +rendered DOM must mirror the in-memory game state. diff --git a/task_061/environment/docker-compose.yaml b/task_061/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_061/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_061/instruction.md b/task_061/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..24ee784fcbca17c64d7eb2b0e4589b8d27c79999 --- /dev/null +++ b/task_061/instruction.md @@ -0,0 +1,17 @@ +# Build a sliding puzzle with move history + +Create one self-contained offline `index.html` for a square sliding puzzle. Render the board and usable Undo and Redo buttons. + +## State and controls + +Expose `window.__game` with `init(level)`, `getState()`, `move(r,c)`, `undo()`, `redo()` and `reset()`. Each action returns `{size,tiles,blank,moves,status}`. + +- A level is `{size,tiles}`, with a row-major array of the tile numbers `0` through `size*size-1` and exactly one zero. Zero is the blank and `blank` is its row-major index. Use zero-based coordinates. The solved order is `[1,2,...,size*size-1,0]`; status is `playing` or `solved`. +- In `#board`, render visible `.tile` elements in row-major order with `data-v` equal to each value. Only the zero tile has class `blank` and no number; every other tile shows its value. Mark the history buttons `data-testid="undo"` and `"redo"`. + +## Acceptance Checklist + +- Initialize the supplied size and layout with zero moves, including levels that are already solved. A legal slide swaps an orthogonally adjacent tile into the blank, updates the blank index and counts exactly one move. +- Out-of-bounds, diagonal, distant and post-solve moves leave state and history unchanged. The solved order ends play. +- Undo/redo recover the exact board, blank index, move count and status across multiple moves, including leaving and restoring the solved state. Empty directions in history are no-ops. New legal branches clear redo, while ignored moves do not. Reset restores the latest initialized layout and clears both directions, as does a new init. +- Tile and history button clicks drive the same transitions as API calls. Keep the whole non-overlapping grid and visible numbers synchronized after every operation. diff --git a/task_061/quality_notes.md b/task_061/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..4157131dc2c0a2993488a042e599a80460360360 --- /dev/null +++ b/task_061/quality_notes.md @@ -0,0 +1,15 @@ +# Quality notes — task_108 + +## 2026-10-08 deep review + +- Active scoring is implemented by the executable verifier in tests/ and disclosed in instruction.md; older five-tier descriptions below refer to the base suite only. +- History is an explicitly disclosed hard gate. Independent state/history traces use semantic field comparison, real button clicks, terminal undo/redo, invalid actions, reset, and per-step visible DOM checks. +- Remote oracle/nop, targeted defect, alternate implementation, repeated runs, and screenshots are tracked separately in the review ledger. Static inspection alone is not a runtime pass or proof of model discrimination. + +- Deterministic: layouts are explicit `{size, tiles}`; no RNG. +- Discrimination via 5 tiers (init / valid slide / invalid no-op / solved / + render-reflection), fractional reward = tiers passed. +- T3 covers diagonal, distance-2, and out-of-bounds moves so a solution that + swaps any clicked cell or counts no-ops fails. T5 checks data-v ordering and a + single blank, defeating no-render engines. +- Verifier uses an independent reference simulation, not source grep. diff --git a/task_061/solution/README.md b/task_061/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3dfdf458644a23cb82e61cc52a6176c22c69f7e2 --- /dev/null +++ b/task_061/solution/README.md @@ -0,0 +1,11 @@ +# Reference solution — task_108 (Sliding Puzzle) + +Self-contained `index.html`. `window.__game` holds a `size*size` tile array +(0 = blank), `move(r,c)` slides a tile into the blank only when orthogonally +adjacent (else no-op, no count), detects solved when tiles are `[1..n-1,0]`, and +renders a DOM board that mirrors state (`.tile[data-v]`, single `.tile.blank`). + +Two snapshot stacks implement undo/redo, including after solving. Legal slides +clear redo; invalid and frozen moves leave history untouched. Reset restores the +last initialized layout and clears history. Actual buttons share the API's +history functions. diff --git a/task_061/solution/code/index.html b/task_061/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..a702493de6504867cdd79803e098faa1e96c9b02 --- /dev/null +++ b/task_061/solution/code/index.html @@ -0,0 +1,134 @@ + + + + +Sliding Puzzle + + + +
      Moves: 0 — Status: playing
      +
      + + + diff --git a/task_061/solution/solve.sh b/task_061/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_061/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_061/task.toml b/task_061/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_061/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_061/task_meta.json b/task_061/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..f9b75b0eb37a2ef19e163b819c7fc483aa55d5dc --- /dev/null +++ b/task_061/task_meta.json @@ -0,0 +1,15 @@ +{ + "task_id": 108, + "task_category": "frontend_development", + "origin_model": "authored", + "sample_count": 0, + "user_turns": 0, + "language": "javascript", + "input_assets": [], + "expected_outputs": [ + "index.html" + ], + "source_row_id": null, + "repair_revision": "2026-09-29", + "instruction_sha256": "0cc608c866d9fd9aeca78676bea570f62af32c6cf9766a00173357cd5313936c" +} diff --git a/task_061/tests/_shared/contract_checker.js b/task_061/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_061/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_061/tests/_shared/static_enhancer.sh b/task_061/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_061/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_061/tests/enhancement_cases.json b/task_061/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..eb4f8ff2de6557293a0858980063e4935035ea1c --- /dev/null +++ b/task_061/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","instruction_evidence":"棋盘是 size × size 的方格……当且仅当 (r,c) 与空格正交相邻时……两者交换,moves 加 1。","validator":"validate_enhanced_cases.js","behavior":"使用 4×4 合法布局验证尺寸泛化、交换、blank 和 moves。"}, + {"case_id":"ENHANCED_CASE_2","instruction_evidence":"(r,c) 越界 → 无操作。非相邻(含对角线、距离 ≥ 2)→ 无操作。","validator":"validate_enhanced_cases.js","behavior":"在同一显式状态分别验证对角线和越界移动均为完整无操作。"}, + {"case_id":"ENHANCED_CASE_3","instruction_evidence":"若初始即已解则 'solved'……已解后再调用 move 无效。","validator":"validate_enhanced_cases.js","behavior":"2×2 已解布局初始化后尝试合法相邻移动,验证冻结。"} +] diff --git a/task_061/tests/review_hard.js b/task_061/tests/review_hard.js new file mode 100644 index 0000000000000000000000000000000000000000..68a57973361566334df8471b2674fdc0259a5d65 --- /dev/null +++ b/task_061/tests/review_hard.js @@ -0,0 +1,4 @@ +require('./review_history.js')(108).catch(error => { + console.error(error); + process.exitCode = 1; +}); diff --git a/task_061/tests/review_history.js b/task_061/tests/review_history.js new file mode 100644 index 0000000000000000000000000000000000000000..e5ad8f2f229600605ee7817bbb5ea863dfedbfda --- /dev/null +++ b/task_061/tests/review_history.js @@ -0,0 +1,109 @@ +// Independent transition/history model; object key order is not semantic. +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const {pathToFileURL} = require('node:url'); +const {chromium} = require('playwright'); +const mirror = require('./validate_render_mirror.js'); +const clone = value => JSON.parse(JSON.stringify(value)); + +module.exports = async function checkHistory(id) { + const browser = await chromium.launch({headless:true, args:['--no-sandbox']}); + try { + const page = await browser.newPage({viewport:{width:520,height:640}}); + page.setDefaultTimeout(5000); + await page.route(/^https?:\/\//, route => route.abort()); + await page.goto(pathToFileURL(path.join(process.argv[2] || process.cwd(), 'index.html')).href); + let state, initial, timeline, cursor; + const terminal = id === 107 ? 'won' : 'solved'; + const action = id === 107 ? 'press' : 'move'; + const project = value => id === 107 + ? {size:value.size,grid:value.grid,moves:value.moves,status:value.status} + : {size:value.size,tiles:value.tiles,blank:value.blank,moves:value.moves,status:value.status}; + function setStatus() { + state.status = id === 107 + ? (state.grid.every(value => value === false) ? terminal : 'playing') + : (state.tiles.every((value,index) => value === (index + 1) % state.tiles.length) ? terminal : 'playing'); + } + function initialize(level) { + if (id === 107) { + const grid = Array(level.size ** 2).fill(false); + for (const [r,c] of level.on) if (r >= 0 && c >= 0 && r < level.size && c < level.size) grid[r*level.size+c] = true; + state = {size:level.size,grid,moves:0}; + } else state = {size:level.size,tiles:level.tiles.slice(),blank:level.tiles.indexOf(0),moves:0}; + setStatus(); initial = clone(state); timeline = [clone(state)]; cursor = 0; + } + function transition(method,args) { + if (method === 'init') return initialize(args[0]); + if (method === 'reset') { state = clone(initial); timeline = [clone(state)]; cursor = 0; return; } + if (method === 'undo' || method === 'redo') { + cursor = Math.max(0,Math.min(timeline.length-1,cursor+(method==='undo'?-1:1))); + state = clone(timeline[cursor]); return; + } + const [r,c] = args; + if (state.status === terminal || r < 0 || c < 0 || r >= state.size || c >= state.size) return; + if (id === 107) { + for (let row=0;rowwindow.__game[method](...args),{method,args}); + assert.deepEqual(project(result),state,method+' return state'); + } + const actual=await page.evaluate(()=>window.__game.getState()); + assert.deepEqual(project(actual),state,method+' getState'); + await mirror(page,id); + console.log('PASS history '+method+' '+JSON.stringify(args)+(button?' real-click':'')); + } + const level=id===107?{size:3,on:[[0,0]]}:{size:3,tiles:[1,2,3,4,0,6,7,5,8]}; + await step('init',[level]); + await step('undo'); await step('redo'); + await step(action,[0,1],true); await step(action,[1,1]); + await step('undo',[],true); await step('undo'); await step('undo'); + await step(action,[-1,-1]); await step('redo'); await step('redo',[],true); await step('redo'); + await step('undo',[],true); await step(action,[0,0],true); await step('redo'); + await step('reset'); await step('undo'); await step('redo'); + // Solve in one move, attempt a frozen action, then restore both sides of the terminal state. + const winning=id===107?{size:1,on:[[0,0]]}:{size:2,tiles:[1,2,0,3]}; + await step('init',[winning]); + await step(action,id===107?[0,0]:[1,1],true); + await step(action,[0,0]); + await step('undo',[],true); await step('redo',[],true); + await step('undo'); await step('init',[level]); await step('redo'); await step('undo'); + // Longer deterministic traces exercise mixed no-ops and history boundaries. + for (const coords of [[2,1],[1,2],[2,2],[0,0],[1,0],[0,2],[1,1]]) await step(action,coords); + for (let i=0;i<9;i++) await step('undo'); + for (let i=0;i<9;i++) await step('redo'); + // Avoid an early solved state masking implementations that retain only two moves. + await step('init',[{size:4,tiles:Array.from({length:16},(_,index)=>15-index)}]); + for (let cycle=0;cycle<3;cycle++) { + for (const coords of [[3,2],[2,2],[2,3],[3,3]]) await step(action,coords); + } + for (let i=0;i<14;i++) await step('undo'); + for (let i=0;i<14;i++) await step('redo'); + const directory='/logs/verifier/visual'; + fs.mkdirSync(directory,{recursive:true}); + await page.screenshot({path:path.join(directory,'history-desktop.png'),fullPage:true}); + await page.setViewportSize({width:390,height:844}); + await page.screenshot({path:path.join(directory,'history-mobile.png'),fullPage:true}); + console.log('PASS history, terminal restoration, DOM and real buttons'); + } finally { await browser.close(); } +}; diff --git a/task_061/tests/review_legacy.sh b/task_061/tests/review_legacy.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d550948c62e3205779de94410435fe363acddc8 --- /dev/null +++ b/task_061/tests/review_legacy.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +[ -f index.html ] || exit 0 +OUT=$(run validate_ui_behavior.js 2>&1); RC=$?; printf '%s +' "$OUT" +CORE=$(printf '%s +' "$OUT" | sed -n 's/^SCORE=//p' | tail -1) +if [ "$RC" -ne 0 ] || [ -z "$CORE" ]; then CORE=0; fi +OUT=$(run validate_enhanced_cases.js 2>&1); RC=$?; printf '%s +' "$OUT" +ENH=$(printf '%s +' "$OUT" | sed -n 's/^ENHANCED_SCORE=//p' | tail -1) +if [ "$RC" -ne 0 ] || [ -z "$ENH" ]; then ENH=0; fi +node -e 'const [a,b]=process.argv.slice(1).map(Number);if(![a,b].every(x=>Number.isFinite(x)&&x>=0&&x<=1))process.exit(1);console.log((5*a+3*b)/8)' "$CORE" "$ENH" > "$REWARD_FILE" +cat "$REWARD_FILE" diff --git a/task_061/tests/test.sh b/task_061/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a220175c3cba51e53d35c25d20af343b1f3df372 --- /dev/null +++ b/task_061/tests/test.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -uo pipefail +bash /tests/review_legacy.sh +CORE=$(cat /logs/verifier/reward.txt 2>/dev/null || echo 0) +mkdir -p /logs/verifier +timeout -k 5s 90s node /tests/review_hard.js /app 2>&1 | tee /logs/verifier/review_hard.log +RC=${PIPESTATUS[0]} +if [ "$RC" -ne 0 ]; then echo "REVIEW_HARD failed with exit code $RC"; fi +if [ "$RC" -eq 0 ]; then echo "$CORE"; else echo 0; fi > /logs/verifier/reward.txt +exit 0 diff --git a/task_061/tests/validate_aaav_dynamic.js b/task_061/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..95837c1e40bc8a04e1c731237aef3a5306896788 --- /dev/null +++ b/task_061/tests/validate_aaav_dynamic.js @@ -0,0 +1,17 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +const TASK_ID = 108; +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage(); + const errs = []; + page.on('pageerror', e => errs.push(e.message)); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + const ok = await page.evaluate(() => !!(window.__game && typeof window.__game.getState === 'function')); + await browser.close(); + if (errs.length) throw new Error('page errors: ' + errs.join(' | ')); + if (!ok) throw new Error('window.__game.getState missing'); + console.log('AAAV dynamic gate passed for task ' + TASK_ID); +})().catch(e => { console.error('AAAV FAIL: ' + e.message); process.exit(1); }); diff --git a/task_061/tests/validate_browser_smoke.js b/task_061/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_061/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_061/tests/validate_enhanced_cases.js b/task_061/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..441419bfea5b117ca4511df561d24ceb13d3297b --- /dev/null +++ b/task_061/tests/validate_enhanced_cases.js @@ -0,0 +1,38 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +function assert(x, m) { if (!x) throw new Error(m); } +(async () => { + const browser = await chromium.launch({ headless: true, args: ['--no-sandbox', '--disable-dev-shm-usage'] }); + const page = await browser.newPage({ viewport: { width: 520, height: 640 } }); + await page.route(/^https?:\/\//, route => route.abort()); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded', timeout: 10000 }); + const cases = [ + // ENHANCED_CASE_1: legal movement must work for the level-provided size, not just 3x3. + ['ENHANCED_CASE_1', async () => { + const tiles = [1,2,3,4,5,6,7,8,9,10,11,12,13,0,14,15]; + const st = await page.evaluate(T => { window.__game.init({ size: 4, tiles: T }); return window.__game.move(3, 2); }, tiles); + assert(st.size === 4 && st.blank === 14 && st.moves === 1, '4x4 legal slide must update blank and moves'); + assert(st.tiles[13] === 14 && st.tiles[14] === 0, 'adjacent tile and blank must swap'); + }], + // ENHANCED_CASE_2: diagonal and out-of-range coordinates are both complete no-ops. + ['ENHANCED_CASE_2', async () => { + const tiles = [1,2,3,4,0,5,6,7,8]; + const before = await page.evaluate(T => window.__game.init({ size: 3, tiles: T }), tiles); + const diagonal = await page.evaluate(() => window.__game.move(0, 0)); + const outside = await page.evaluate(() => window.__game.move(-1, 1)); + assert(require("node:util").isDeepStrictEqual(diagonal,before), 'diagonal move must be ignored'); + assert(require("node:util").isDeepStrictEqual(outside,before), 'out-of-range move must be ignored'); + }], + // ENHANCED_CASE_3: solved-at-init boards are frozen. + ['ENHANCED_CASE_3', async () => { + const won = await page.evaluate(() => window.__game.init({ size: 2, tiles: [1,2,3,0] })); + assert(won.status === 'solved' && won.blank === 3 && won.moves === 0, 'solved layout must be recognized at init'); + const after = await page.evaluate(() => window.__game.move(1, 0)); + assert(require("node:util").isDeepStrictEqual(after,won), 'move after solved must be ignored'); + }], + ]; + let passed=0; for (const [id, fn] of cases) { try { await fn(); passed++; console.log('PASS '+id); } catch(e) { console.error('FAIL '+id+': '+e.message); } } console.log('ENHANCED_SCORE='+(passed/cases.length)); + await browser.close(); +})().catch(e => { console.error(e.stack || e); process.exit(1); }); + diff --git a/task_061/tests/validate_render_mirror.js b/task_061/tests/validate_render_mirror.js new file mode 100644 index 0000000000000000000000000000000000000000..a9dc3edbaaff46467d6085e3e504af8f44c37af3 --- /dev/null +++ b/task_061/tests/validate_render_mirror.js @@ -0,0 +1,46 @@ +// Check the visible board against public state, independent of source names. +const assert = require('node:assert/strict'); +module.exports = async function mirror(page, id) { + const { state, cells } = await page.evaluate(id => { + const state = window.__game.getState(); + const selector = id === 108 ? '.tile' : '.cell'; + const cells = [...document.querySelectorAll('#board ' + selector)].map(element => { + const rect = element.getBoundingClientRect(); + return { classes: [...element.classList], value: Number(element.dataset.v), + text: element.textContent.trim(), top: rect.top, left: rect.left, + width: rect.width, height: rect.height, + visible: element.checkVisibility({checkOpacity:true, checkVisibilityCSS:true}) }; + }); + cells.sort((a, b) => Math.abs(a.top - b.top) > 2 ? a.top - b.top : a.left - b.left); + return { state, cells }; + }, id); + const width = id === 106 ? state.width : state.size; + const height = id === 106 ? state.height : state.size; + assert.equal(cells.length, width * height, 'board cell count'); + const at = (positions, r, c) => positions.some(p => p[0] === r && p[1] === c); + cells.forEach((cell, index) => { + const r = Math.floor(index / width), c = index % width; + assert(cell.visible && cell.width > 0 && cell.height > 0, 'visible cell ' + index); + if (c > 0) { + const previous = cells[index - 1]; + assert(cell.left >= previous.left + previous.width - 1, 'non-overlapping columns'); + } + if (r > 0) { + const above = cells[index - width]; + assert(cell.top >= above.top + above.height - 1, 'non-overlapping rows'); + } + const has = cls => cell.classes.includes(cls); + if (id === 106) { + for (const [cls, positions] of [['wall', state.walls], ['box', state.boxes], ['target', state.targets]]) { + assert.equal(has(cls), at(positions, r, c), cls + ' at ' + index); + } + assert.equal(has('player'), state.player.r === r && state.player.c === c, 'player position'); + } else if (id === 107) { + assert.equal(has('on'), state.grid[index], 'light position ' + index); + } else { + assert.equal(cell.value, state.tiles[index], 'tile data-v ' + index); + assert.equal(cell.text, state.tiles[index] ? String(state.tiles[index]) : '', 'visible tile label'); + assert.equal(has('blank'), state.tiles[index] === 0, 'blank position'); + } + }); +}; diff --git a/task_061/tests/validate_semantics.js b/task_061/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_061/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_061/tests/validate_ui_behavior.js b/task_061/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..9f5980294a737071e37cf7ee925716639e306710 --- /dev/null +++ b/task_061/tests/validate_ui_behavior.js @@ -0,0 +1,140 @@ +// Tiered deterministic correctness verifier for the Sliding Puzzle task. +// Drives window.__game with EXPLICIT layouts (no RNG) and asserts exact state +// transitions against an INDEPENDENT reference simulation. Prints PASS/FAIL per +// tier and a final SCORE= used by test.sh as the (partial) reward. +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +function assert(cond, msg) { if (!cond) throw new Error(msg); } + +// --- independent reference model (mirrors the spec) ----------------------- +function refInit(level) { + const size = level.size; + const tiles = level.tiles.slice(); + return { size, tiles, blank: tiles.indexOf(0), moves: 0, status: refStatus(tiles) }; +} +function refStatus(tiles) { + const n = tiles.length; + for (let i = 0; i < n - 1; i++) if (tiles[i] !== i + 1) return 'playing'; + return tiles[n - 1] === 0 ? 'solved' : 'playing'; +} +function refMove(m, r, c) { + if (m.status === 'solved') return m; + const size = m.size; + if (r < 0 || r >= size || c < 0 || c >= size) return m; + const idx = r * size + c; + const br = Math.floor(m.blank / size), bc = m.blank % size; + if (Math.abs(r - br) + Math.abs(c - bc) !== 1) return m; // not adjacent + m.tiles[m.blank] = m.tiles[idx]; + m.tiles[idx] = 0; + m.blank = idx; + m.moves += 1; + m.status = refStatus(m.tiles); + return m; +} +function eqTiles(a, b) { return a.length === b.length && a.every((v, i) => v === b[i]); } + +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 520, height: 640 } }); + const errs = []; + await page.route(/^https?:\/\//, route => route.abort()); + page.on('pageerror', e => errs.push(e.message)); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(300); + const run = (fn, arg) => page.evaluate(fn, arg); + + const hasApi = await page.evaluate(() => !!(window.__game + && typeof window.__game.init === 'function' + && typeof window.__game.getState === 'function' + && typeof window.__game.move === 'function')); + + // 3x3 layout, blank at (1,1) = index 4. + // 1 2 3 + // 4 0 6 + // 7 8 5 + const L = { size: 3, tiles: [1, 2, 3, 4, 0, 6, 7, 8, 5] }; + + const tiers = [ + ['T1 API + init (size/dims/tiles/blank index, status playing, moves 0)', async () => { + assert(hasApi, 'window.__game with init/getState/move is required'); + assert(errs.length === 0, 'no page errors allowed: ' + errs.join(' | ')); + const st = await run((L) => window.__game.init(L), L); + const ref = refInit(L); + assert(st.size === ref.size, `size must be ${ref.size}, got ${st.size}`); + assert(eqTiles(st.tiles, ref.tiles), 'tiles parsed wrong: ' + JSON.stringify(st.tiles)); + assert(st.blank === ref.blank, `blank index must be ${ref.blank}, got ${st.blank}`); + assert(st.status === 'playing', 'fresh status must be playing, got ' + st.status); + assert(st.moves === 0, 'fresh moves must be 0, got ' + st.moves); + }], + + ['T2 valid slide swaps tile/blank + moves+1', async () => { + let st = await run((L) => window.__game.init(L), L); + const ref = refInit(L); + // slide tile at (2,1)=8 (below blank, adjacent) into blank. + st = await run(() => window.__game.move(2, 1)); + refMove(ref, 2, 1); + assert(eqTiles(st.tiles, ref.tiles), 'valid slide produced wrong tiles: ' + JSON.stringify(st.tiles)); + assert(st.blank === ref.blank && st.blank === 7, 'blank should move to the slid tile cell (index 7)'); + assert(st.moves === ref.moves && st.moves === 1, 'valid slide must increment moves to 1, got ' + st.moves); + }], + + ['T3 invalid move (non-adjacent or out-of-bounds) is a no-op + no move count', async () => { + let st = await run((L) => window.__game.init(L), L); + const ref = refInit(L); + const before = JSON.stringify(st.tiles); + // (0,0)=1 is diagonal to blank (1,1): NOT orthogonally adjacent -> no-op. + st = await run(() => window.__game.move(0, 0)); + refMove(ref, 0, 0); + assert(JSON.stringify(st.tiles) === before, 'non-adjacent move must not change tiles'); + assert(st.moves === 0, 'non-adjacent move must not increment moves, got ' + st.moves); + // (2,2)=5 is two cells from blank -> no-op. + st = await run(() => window.__game.move(2, 2)); + assert(JSON.stringify(st.tiles) === before && st.moves === 0, 'distant move must be a no-op'); + // out-of-bounds -> no-op. + st = await run(() => window.__game.move(3, 0)); + assert(JSON.stringify(st.tiles) === before && st.moves === 0, 'out-of-bounds move must be a no-op'); + }], + + ['T4 one-move-from-solved layout -> move -> status solved', async () => { + // Solved is [1,2,3,4,5,6,7,8,0]. Put blank at index 7 and 8 at index 8: + // 1 2 3 / 4 5 6 / 7 0 8 -> slide (2,2)=8 into blank (2,1) -> solved. + const W = { size: 3, tiles: [1, 2, 3, 4, 5, 6, 7, 0, 8] }; + const ref = refInit(W); refMove(ref, 2, 2); + assert(ref.status === 'solved', 'reference: sliding 8 should solve it'); + let st = await run((W) => { window.__game.init(W); return window.__game.move(2, 2); }, W); + assert(eqTiles(st.tiles, [1, 2, 3, 4, 5, 6, 7, 8, 0]), 'tiles should be in solved order'); + assert(st.status === 'solved', 'reaching solved order must set status solved, got ' + st.status); + // moves after solved are ignored + const movesAtSolved = st.moves; + st = await run(() => window.__game.move(2, 1)); + assert(st.status === 'solved' && st.moves === movesAtSolved, 'moves after solved must be ignored'); + }], + + ['T5 render-reflection: DOM .tile[data-v] order matches tiles; exactly one .blank', async () => { + const st = await run((L) => window.__game.init(L), L); + const dom = await run(() => ({ + vals: Array.from(document.querySelectorAll('#board .tile')).map(t => Number(t.dataset.v)), + blanks: document.querySelectorAll('#board .tile.blank').length, + count: document.querySelectorAll('#board .tile').length, + })); + assert(dom.count === st.tiles.length, `DOM must render ${st.tiles.length} tiles, got ${dom.count}`); + assert(eqTiles(dom.vals, st.tiles), 'DOM data-v order must match tiles: ' + JSON.stringify(dom.vals)); + assert(dom.blanks === 1, 'exactly one .blank tile must be rendered, got ' + dom.blanks); + // after a slide the DOM must update too + const st2 = await run(() => window.__game.move(2, 1)); + const dom2 = await run(() => Array.from(document.querySelectorAll('#board .tile')).map(t => Number(t.dataset.v))); + assert(eqTiles(dom2, st2.tiles), 'DOM data-v must track tiles after a slide'); + }], + ]; + + let passed = 0; + for (const [name, fn] of tiers) { + try { await fn(); if(name.startsWith('T5'))await require('./validate_render_mirror.js')(page,108); passed++; console.log('PASS ' + name); } + catch (e) { console.log('FAIL ' + name + ': ' + (e && e.message || e)); } + } + console.log('TIERS ' + passed + '/' + tiers.length); + console.log('SCORE=' + (passed / tiers.length).toFixed(3)); + await browser.close(); +})().catch(e => { console.log('FATAL ' + (e && e.stack || e)); console.log('SCORE=0'); }); diff --git a/task_062/acceptance_checklist.json b/task_062/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..f92cb1db10ff0440d1fa5ddf7d5ea3f7afdf115f --- /dev/null +++ b/task_062/acceptance_checklist.json @@ -0,0 +1,22 @@ +{ + "task_id": 109, + "category": "frontend_development", + "language": "javascript", + "acceptance_items": [ + "init sets maxGuesses, empty rows, status playing; answer not leaked.", + "Non-duplicate guess yields correct g/y/b marks.", + "Duplicate-letter marks honor answer multiplicity (greens first, then yellows while counts remain).", + "Exact match sets won; exhausting guesses sets lost; guesses ignored after end.", + "DOM mirrors state: last row tile classes match marks.", + "All contract board elements are visible; all historical rows/cells mirror state after updates and reset." + ], + "expected_outputs": [ + "index.html" + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "risk_notes": [ + "Duplicate-letter tier defeats naive scorers that mark all present letters yellow.", + "Render-reflection tier defeats no-render in-memory engines." + ], + "repair_revision": "2026-10-07" +} diff --git a/task_062/environment/Dockerfile b/task_062/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2f855b3d12b4e80dd6cd135513202206e95ccdba --- /dev/null +++ b/task_062/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# The mcr/playwright base ships browsers but NOT the `playwright` npm package, +# which the verifier's require('playwright') needs. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_062/environment/code/README.md b/task_062/environment/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..603ee0126b04481e55192c70f2c62c3b1e8a705b --- /dev/null +++ b/task_062/environment/code/README.md @@ -0,0 +1,6 @@ +# wordle — starter + +Implement the game in a single self-contained `index.html` (inline CSS/JS, no +external network). Expose a deterministic `window.__game` API as described in the +task instruction so the verifier can drive it with explicit scenarios. The +rendered DOM must mirror the in-memory game state. diff --git a/task_062/environment/docker-compose.yaml b/task_062/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_062/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_062/instruction.md b/task_062/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..be944e056f72a757b6a8e576518281538fd1f491 --- /dev/null +++ b/task_062/instruction.md @@ -0,0 +1,14 @@ +# Build Wordle with repeated-letter feedback + +Create a single self-contained offline `index.html` with inline CSS and JavaScript. Show the guess board and feedback visibly. + +## State interface + +Expose `window.__game.init({answer,maxGuesses})`, `.getState()` and `.guess(word)`. The answer is a lowercase five-letter word. `init` and `guess` return the resulting state `{rows,status,maxGuesses}`; each row is `{word,marks}` with a five-character marks array. Status is `playing`, `won` or `lost`. Do not expose the secret as a separate field or value in public state; submitted words remain visible. + +## Acceptance Checklist + +- Init clears prior rows and starts playing with the requested limit. Normalize five-letter guesses to lowercase before storing, scoring and checking for a win. +- Mark exact matches `g` first. Then process other positions left to right: mark `y` only if an unused occurrence of that letter remains in the answer, consuming it; otherwise mark `b`. Each answer occurrence can contribute to at most one mark. +- A correct guess wins; an incorrect guess at the limit loses. All guesses after either outcome leave state unchanged. +- Within `#board`, show each guess as a visible `.row` with five `.tile` cells in letter order. Each filled cell shows its letter and exactly one matching class `g`, `y` or `b`, with visually distinguishable feedback. Empty rows are allowed but contain no old letters or marks; reinitializing clears all previous guesses. diff --git a/task_062/quality_notes.md b/task_062/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..6f1557683add74cd4fb0703a21a8c80e36910a05 --- /dev/null +++ b/task_062/quality_notes.md @@ -0,0 +1,14 @@ +# Quality notes — task_109 + +- Deterministic: explicit answer + guesses; no RNG, no word list lookups. +- Discrimination via 5 tiers (init / simple marks / DUPLICATE trap / win+lose / + render-reflection), fractional reward = tiers passed. +- T3 is the discrimination: naive scorers that mark every present letter yellow + (ignoring multiplicity) fail on answer `allee`/`abbey` and similar. The + reference scorer assigns greens first (consuming counts) then yellows only + while counts remain. T1 also checks the answer is not leaked. +- Verifier uses an independent, multiplicity-aware reference scorer, not grep. + +## 2026-10-07 review + +The historical five-tier description above describes only the base suite. The active contract has eight equal-weight tiers (five base plus three enhanced). Additional cases strengthen each existing tier without changing its weight. Current checks include visible DOM, multi-step state changes, and independently recomputed contract facts. Specific tested incorrect implementations lose credit; this is not empirical proof of model discrimination or a target model ordering. diff --git a/task_062/solution/README.md b/task_062/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9633256ef3c6ea3c735674a6911c47a7e472c495 --- /dev/null +++ b/task_062/solution/README.md @@ -0,0 +1,8 @@ +# Reference solution — task_109 (Wordle) + +Self-contained `index.html`. `window.__game` scores each guess with correct +duplicate-letter semantics: greens are assigned first and consume answer-letter +occurrences, then yellows are assigned left-to-right only while unused +occurrences of that letter remain (else black). Detects won on exact match and +lost when guesses are exhausted; getState never leaks the answer. The DOM renders +`.row`/`.tile` with `g`/`y`/`b` classes that mirror each row's marks. diff --git a/task_062/solution/code/index.html b/task_062/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..a85baf67425c0b3246644629c212d36495a431c7 --- /dev/null +++ b/task_062/solution/code/index.html @@ -0,0 +1,168 @@ + + + + +Wordle + + + +

      Wordle

      +

      Enter a five-letter word, then press Enter or Guess. Green means correct position, yellow means wrong position, and gray means absent.

      +
      Status: playing
      + +
      + + + +
      +
      + + + + diff --git a/task_062/solution/solve.sh b/task_062/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_062/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_062/task.toml b/task_062/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_062/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_062/task_meta.json b/task_062/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..37156a6cae25155c14521c2920a0d55394ec290b --- /dev/null +++ b/task_062/task_meta.json @@ -0,0 +1,15 @@ +{ + "task_id": 109, + "task_category": "frontend_development", + "origin_model": "authored", + "sample_count": 0, + "user_turns": 0, + "language": "javascript", + "input_assets": [], + "expected_outputs": [ + "index.html" + ], + "source_row_id": null, + "repair_revision": "2026-10-07", + "instruction_sha256": "b411ad847e0c56efa5b8b247dca7b6d230225914f28ea57a875576bc170e715a" +} diff --git a/task_062/tests/_shared/contract_checker.js b/task_062/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_062/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_062/tests/_shared/static_enhancer.sh b/task_062/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_062/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_062/tests/assert_visible.js b/task_062/tests/assert_visible.js new file mode 100644 index 0000000000000000000000000000000000000000..9fbe4fb579ae0e76c915813a8d47d4a1ba67d38f --- /dev/null +++ b/task_062/tests/assert_visible.js @@ -0,0 +1,13 @@ +// Visible contract elements must not be a hidden DOM-only scoring facade. +module.exports = async function assertVisibleBoard(page, selector) { + const failures = await page.locator(selector).evaluateAll(elements => elements.flatMap((element,index) => { + const box = element.getBoundingClientRect(); + let hidden = box.width <= 0 || box.height <= 0; + for(let node=element; node instanceof Element; node=node.parentElement) { + const style = getComputedStyle(node); + hidden ||= style.display==='none' || style.visibility==='hidden' || style.visibility==='collapse' || Number(style.opacity)===0; + } + return hidden ? [index] : []; + })); + if(failures.length) throw new Error('Board elements are not visible: '+failures.join(',')); +}; diff --git a/task_062/tests/enhancement_cases.json b/task_062/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..bc7555cbd5e38838af75bf2c28a8fc77fd2fdba1 --- /dev/null +++ b/task_062/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","instruction_evidence":"把 word(小写化)作为一行追加到 rows……若 word == answer → status='won'。","validator":"validate_enhanced_cases.js","behavior":"提交大写的正确答案,验证小写化后存储、全绿并获胜。"}, + {"case_id":"ENHANCED_CASE_2","instruction_evidence":"必须先分配所有 'g',再对非绿色字母从左到右分配 'y'……每个答案字母的出现次数只能被消耗有限次。","validator":"validate_enhanced_cases.js","behavior":"用 civic/vivid 新重复字母组合与独立 oracle 精确比较 marks。"}, + {"case_id":"ENHANCED_CASE_3","instruction_evidence":"不得在 getState() 中泄露 answer。","validator":"validate_enhanced_cases.js","behavior":"猜测后再次读取并序列化状态,验证不存在 answer 字段或答案值。"} +] diff --git a/task_062/tests/test.sh b/task_062/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d550948c62e3205779de94410435fe363acddc8 --- /dev/null +++ b/task_062/tests/test.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +[ -f index.html ] || exit 0 +OUT=$(run validate_ui_behavior.js 2>&1); RC=$?; printf '%s +' "$OUT" +CORE=$(printf '%s +' "$OUT" | sed -n 's/^SCORE=//p' | tail -1) +if [ "$RC" -ne 0 ] || [ -z "$CORE" ]; then CORE=0; fi +OUT=$(run validate_enhanced_cases.js 2>&1); RC=$?; printf '%s +' "$OUT" +ENH=$(printf '%s +' "$OUT" | sed -n 's/^ENHANCED_SCORE=//p' | tail -1) +if [ "$RC" -ne 0 ] || [ -z "$ENH" ]; then ENH=0; fi +node -e 'const [a,b]=process.argv.slice(1).map(Number);if(![a,b].every(x=>Number.isFinite(x)&&x>=0&&x<=1))process.exit(1);console.log((5*a+3*b)/8)' "$CORE" "$ENH" > "$REWARD_FILE" +cat "$REWARD_FILE" diff --git a/task_062/tests/validate_aaav_dynamic.js b/task_062/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..3cf5e05dce9b98352c84e3440c1f7bd7be4f3fee --- /dev/null +++ b/task_062/tests/validate_aaav_dynamic.js @@ -0,0 +1,17 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +const TASK_ID = 109; +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage(); + const errs = []; + page.on('pageerror', e => errs.push(e.message)); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + const ok = await page.evaluate(() => !!(window.__game && typeof window.__game.getState === 'function')); + await browser.close(); + if (errs.length) throw new Error('page errors: ' + errs.join(' | ')); + if (!ok) throw new Error('window.__game.getState missing'); + console.log('AAAV dynamic gate passed for task ' + TASK_ID); +})().catch(e => { console.error('AAAV FAIL: ' + e.message); process.exit(1); }); diff --git a/task_062/tests/validate_browser_smoke.js b/task_062/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_062/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_062/tests/validate_enhanced_cases.js b/task_062/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..17123d150af1f61de13fd6aa2ad53a58f6ef7e9b --- /dev/null +++ b/task_062/tests/validate_enhanced_cases.js @@ -0,0 +1,40 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +function assert(x, m) { if (!x) throw new Error(m); } +function marks(answer, word) { + const out = Array(5).fill('b'), left = {}; + for (let i = 0; i < 5; i++) if (word[i] === answer[i]) out[i] = 'g'; else left[answer[i]] = (left[answer[i]] || 0) + 1; + for (let i = 0; i < 5; i++) if (out[i] !== 'g' && left[word[i]]) { out[i] = 'y'; left[word[i]]--; } + return out; +} +(async () => { + const browser = await chromium.launch({ headless: true, args: ['--no-sandbox', '--disable-dev-shm-usage'] }); + const page = await browser.newPage({ viewport: { width: 520, height: 640 } }); + await page.route(/^https?:\/\//, route => route.abort()); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded', timeout: 10000 }); + const cases = [ + // ENHANCED_CASE_1: guess input is lowercased before storage, scoring, and win detection. + ['ENHANCED_CASE_1', async () => { + const st = await page.evaluate(() => { window.__game.init({ answer: 'crane', maxGuesses: 3 }); return window.__game.guess('CRANE'); }); + assert(st.status === 'won', 'uppercase exact guess must win after lowercasing'); + assert(st.rows.length === 1 && st.rows[0].word === 'crane', 'stored guess must be lowercase'); + assert(st.rows[0].marks.every(x => x === 'g'), 'lowercased exact guess must be all green'); + }], + // ENHANCED_CASE_2: another duplicate-letter allocation is checked independently. + ['ENHANCED_CASE_2', async () => { + const answer = 'civic', word = 'vivid', expected = marks(answer, word); + const st = await page.evaluate(p => { window.__game.init({ answer: p.answer, maxGuesses: 4 }); return window.__game.guess(p.word); }, { answer, word }); + assert(require("node:util").isDeepStrictEqual(st.rows[0].marks,expected), `marks must be ${expected}, got ${st.rows[0].marks}`); + }], + // ENHANCED_CASE_3: the public state must not expose the answer, including after guesses. + ['ENHANCED_CASE_3', async () => { + const st = await page.evaluate(() => { window.__game.init({ answer: 'allee', maxGuesses: 2 }); window.__game.guess('eagle'); return window.__game.getState(); }); + assert(!Object.prototype.hasOwnProperty.call(st, 'answer'), 'getState must not have an answer property'); + assert(!JSON.stringify(st).includes('allee'), 'serialized state must not leak the answer'); + }], + ]; + let passed=0; for (const [id, fn] of cases) { try { await fn(); passed++; console.log('PASS '+id); } catch(e) { console.error('FAIL '+id+': '+e.message); } } console.log('ENHANCED_SCORE='+(passed/cases.length)); + await browser.close(); +})().catch(e => { console.error(e.stack || e); process.exit(1); }); + diff --git a/task_062/tests/validate_render_mirror.js b/task_062/tests/validate_render_mirror.js new file mode 100644 index 0000000000000000000000000000000000000000..008d6eaf7bb06b3331c4547b643c015191603458 --- /dev/null +++ b/task_062/tests/validate_render_mirror.js @@ -0,0 +1,20 @@ +const {isDeepStrictEqual:eq}=require('node:util'); +module.exports=async function mirror(page,id){ + const x=await page.evaluate(id=>{const s=window.__game.getState();const sel=id===109?'.row':id===108?'.tile':'.cell'; + let cells=[...document.querySelectorAll('#board '+sel)]; + if(id!==109)cells.sort((a,b)=>{const x=a.getBoundingClientRect(),y=b.getBoundingClientRect();return Math.abs(x.top-y.top)>2?x.top-y.top:x.left-y.left}); + return {s,dom:cells.map(e=>({classes:[...e.classList],text:e.textContent.trim(),sides:e.dataset.sides,v:e.dataset.v,tiles:[...e.querySelectorAll('.tile')].map(t=>({text:t.textContent.trim(),marks:['g','y','b'].filter(c=>t.classList.contains(c)),mark:['g','y','b'].find(c=>t.classList.contains(c))}))}))}},id); + const {s,dom}=x;const a=(ok,msg)=>{if(!ok)throw Error('render mirror: '+msg)}; + const at=(p,r,c)=>p.some(q=>q[0]===r&&q[1]===c); + if(id===109){const filled=dom.filter(r=>r.tiles.some(t=>t.mark));a(filled.length===s.rows.length,'guessed rows');s.rows.forEach((r,i)=>{a(eq(filled[i].tiles.map(t=>t.text.toLowerCase()),r.word.toLowerCase().split('')),'letters row '+i);a(eq(filled[i].tiles.map(t=>t.mark),r.marks),'marks row '+i);a(filled[i].tiles.every(t=>t.marks.length===1),'one mark per filled tile')});a(dom.filter(r=>!filled.includes(r)).every(r=>r.tiles.every(t=>!t.text)),'unfilled rows must be empty');return} + if(id===108){a(eq(dom.map(e=>+e.v),s.tiles),'tile positions');a(eq(dom.map(e=>e.text),s.tiles.map(v=>v?String(v):'')),'tile numbers');return} + dom.forEach((e,i)=>{const has=c=>e.classes.includes(c); + if(id===106){const r=Math.floor(i/s.width),c=i%s.width;a(has('box')===at(s.boxes,r,c),'box '+i);a(has('target')===at(s.targets,r,c),'target '+i);a(has('wall')===at(s.walls,r,c),'wall '+i);a(has('player')===(s.player.r===r&&s.player.c===c),'player '+i)} + if(id===107)a(has('on')===s.grid[i],'light '+i); + if(id===111){const r=Math.floor(i/s.cols),c=i%s.cols;a(has('source')===(s.source[0]===r&&s.source[1]===c),'source '+i);a(has('sink')===(s.sink[0]===r&&s.sink[1]===c),'sink '+i);a(e.sides===s.cells[i].sides.join(''),'pipe sides '+i)} + if(id===112){const r=Math.floor(i/s.cols),c=i%s.cols;a(has('beam')===at(s.path,r,c),'beam '+i);a(has('source')===(s.source.r===r&&s.source.c===c),'source '+i);a(has('target')===(s.target.r===r&&s.target.c===c),'target '+i)} + if(id===113){a(has('r')===(s.board[i]===1),'red '+i);a(has('y')===(s.board[i]===2),'yellow '+i)} + if(id===114)a(has('alive')===s.grid[i],'life '+i); + if(id===115){a(e.text===(s.grid[i]?String(s.grid[i]):''),'number '+i);a(has('given')===s.givens[i],'given '+i);a(has('conflict')===s.conflicts.includes(i),'conflict '+i)} + }); +}; diff --git a/task_062/tests/validate_semantics.js b/task_062/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_062/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_062/tests/validate_ui_behavior.js b/task_062/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..e62bf1f0958b773dbab76a1e3cd54d47c347f016 --- /dev/null +++ b/task_062/tests/validate_ui_behavior.js @@ -0,0 +1,152 @@ +// Tiered deterministic correctness verifier for the Wordle task. +// Drives window.__game with EXPLICIT answers/guesses (no RNG) and asserts the +// per-letter marks against an INDEPENDENT, multiplicity-aware reference scorer. +// Prints PASS/FAIL per tier and a final SCORE= used by test.sh. +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +function assert(cond, msg) { if (!cond) throw new Error(msg); } + +// --- independent reference model (mirrors the spec; duplicate-aware) ------- +function refScore(answer, word) { + const n = answer.length; + const marks = new Array(n).fill('b'); + const counts = {}; + for (let i = 0; i < n; i++) counts[answer[i]] = (counts[answer[i]] || 0) + 1; + for (let i = 0; i < n; i++) { + if (word[i] === answer[i]) { marks[i] = 'g'; counts[word[i]]--; } + } + for (let i = 0; i < n; i++) { + if (marks[i] === 'g') continue; + const ch = word[i]; + if (counts[ch] > 0) { marks[i] = 'y'; counts[ch]--; } + else marks[i] = 'b'; + } + return marks; +} +function eqMarks(a, b) { return a.length === b.length && a.every((v, i) => v === b[i]); } + +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 520, height: 640 } }); + const errs = []; + page.on('pageerror', e => errs.push(e.message)); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(300); + const run = (fn, arg) => page.evaluate(fn, arg); + + const hasApi = await page.evaluate(() => !!(window.__game + && typeof window.__game.init === 'function' + && typeof window.__game.getState === 'function' + && typeof window.__game.guess === 'function')); + + const tiers = [ + ['T1 API + init (maxGuesses, empty rows, status playing, answer hidden)', async () => { + assert(hasApi, 'window.__game with init/getState/guess is required'); + assert(errs.length === 0, 'no page errors allowed: ' + errs.join(' | ')); + const st = await run(() => window.__game.init({ answer: 'crane', maxGuesses: 6 })); + assert(st.maxGuesses === 6, 'maxGuesses must be 6, got ' + st.maxGuesses); + assert(Array.isArray(st.rows) && st.rows.length === 0, 'fresh rows must be empty'); + assert(st.status === 'playing', 'fresh status must be playing, got ' + st.status); + assert(st.answer === undefined, 'getState must NOT leak the answer'); + }], + + ['T2 non-duplicate guess produces correct g/y/b marks', async () => { + // answer 'crane', guess 'slate': + // s(b) l(b) a(g) t(b) e(g) + const answer = 'crane', word = 'slate'; + const st = await run((a) => { window.__game.init({ answer: a.answer, maxGuesses: 6 }); return window.__game.guess(a.word); }, { answer, word }); + const ref = refScore(answer, word); + assert(st.rows.length === 1, 'one row expected after a guess'); + assert(st.rows[0].word === word, 'row word must equal the guess'); + assert(eqMarks(st.rows[0].marks, ref), 'marks wrong: got ' + JSON.stringify(st.rows[0].marks) + ' expected ' + JSON.stringify(ref)); + assert(st.status === 'playing', 'non-winning guess keeps playing'); + }], + + ['T3 DUPLICATE-LETTER trap: extra guess letters beyond answer count are black', async () => { + // These cases DISTINGUISH the multiplicity-aware rule from a naive "letter + // appears anywhere -> yellow" scorer: + // answer 'abbey' (two b), guess 'bobby' (three b) -> y b g b g + // (one green b at pos2 consumes a b; one yellow b at pos0; the extra b + // at pos3 must be BLACK, not yellow.) + // answer 'crane' (one e), guess 'eerie' -> b b y b g + // (the green e at pos4 consumes the only e; the leading e's are black.) + const cases = [ + { answer: 'abbey', word: 'bobby', expect: ['y', 'b', 'g', 'b', 'g'] }, + { answer: 'crane', word: 'eerie', expect: ['b', 'b', 'y', 'b', 'g'] }, + { answer: 'allee', word: 'eagle', expect: ['y', 'y', 'b', 'y', 'g'] }, + ]; + for (const { answer, word, expect } of cases) { + // Pin the independent reference against the hand-computed vector first. + assert(eqMarks(refScore(answer, word), expect), + `ref scorer wrong for ${answer}/${word}: ` + JSON.stringify(refScore(answer, word))); + const st = await run((a) => { window.__game.init({ answer: a.answer, maxGuesses: 6 }); return window.__game.guess(a.word); }, { answer, word }); + assert(eqMarks(st.rows[0].marks, expect), + `duplicate marks wrong for answer=${answer} guess=${word}: got ` + + JSON.stringify(st.rows[0].marks) + ' expected ' + JSON.stringify(expect)); + } + // Alphabet permutations preserve multiplicity but defeat fixture-only lookup tables. + for (const offset of [1, 7, 19]) { + const shift = word => [...word].map(c => String.fromCharCode(97 + (c.charCodeAt(0) - 97 + offset) % 26)).join(''); + for (const sample of cases) { + const answer = shift(sample.answer), word = shift(sample.word); + const st = await run(p => { window.__game.init({answer:p.answer,maxGuesses:3}); return window.__game.guess(p.word); }, {answer,word}); + assert(st.rows[0].word === word && eqMarks(st.rows[0].marks, refScore(answer, word)), 'permuted duplicate scoring'); + } + } + }], + + ['T4 win on exact match sets won; running out of guesses sets lost', async () => { + // Win + let st = await run(() => { window.__game.init({ answer: 'crane', maxGuesses: 6 }); return window.__game.guess('crane'); }); + assert(eqMarks(st.rows[0].marks, ['g', 'g', 'g', 'g', 'g']), 'exact match must be all green'); + assert(st.status === 'won', 'exact match must set status won, got ' + st.status); + // further guesses ignored after win + st = await run(() => window.__game.guess('slate')); + assert(st.status === 'won' && st.rows.length === 1, 'guesses after win must be ignored'); + // Lose: maxGuesses=2, two wrong guesses -> lost + st = await run(() => { + window.__game.init({ answer: 'crane', maxGuesses: 2 }); + window.__game.guess('slate'); + return window.__game.guess('plumb'); + }); + assert(st.rows.length === 2, 'two guessed rows expected'); + assert(st.status === 'lost', 'running out of guesses must set status lost, got ' + st.status); + st = await run(() => window.__game.guess('crane')); + assert(st.status === 'lost' && st.rows.length === 2, 'guesses after loss must be ignored'); + }], + + ['T5 render-reflection: last row tile classes match marks', async () => { + const answer = 'abbey', word = 'bobby'; + const st = await run((a) => { window.__game.init({ answer: a.answer, maxGuesses: 6 }); return window.__game.guess(a.word); }, { answer, word }); + const ref = refScore(answer, word); + const dom = await run(() => { + const rows = document.querySelectorAll('#board .row'); + const lastFilled = Array.from(rows).filter(rw => + Array.from(rw.querySelectorAll('.tile')).some(t => t.classList.contains('g') || t.classList.contains('y') || t.classList.contains('b')) + ); + const tiles = Array.from(lastFilled[lastFilled.length - 1].querySelectorAll('.tile')); + return tiles.map(t => t.classList.contains('g') ? 'g' : t.classList.contains('y') ? 'y' : t.classList.contains('b') ? 'b' : '?'); + }); + assert(eqMarks(dom, ref), 'DOM tile classes must match marks: got ' + JSON.stringify(dom) + ' expected ' + JSON.stringify(ref)); + assert(eqMarks(dom, st.rows[0].marks), 'DOM tile classes must match getState marks'); + await run(() => { window.__game.guess('eagle'); window.__game.guess('abbey'); }); + await require('./validate_render_mirror.js')(page,109); + await require('./assert_visible.js')(page,'#board .tile'); + await page.screenshot({path:'/logs/verifier/wordle-history.png',fullPage:true}); + await run(() => window.__game.init({answer:'civic',maxGuesses:2})); + await require('./validate_render_mirror.js')(page,109); + await page.screenshot({path:'/logs/verifier/wordle-reset.png',fullPage:true}); + }], + ]; + + let passed = 0; + for (const [name, fn] of tiers) { + try { await fn(); if(name.startsWith('T5'))await require('./validate_render_mirror.js')(page,109); passed++; console.log('PASS ' + name); } + catch (e) { console.log('FAIL ' + name + ': ' + (e && e.message || e)); } + } + console.log('TIERS ' + passed + '/' + tiers.length); + console.log('SCORE=' + (passed / tiers.length).toFixed(3)); + await browser.close(); +})().catch(e => { console.log('FATAL ' + (e && e.stack || e)); console.log('SCORE=0'); }); diff --git a/task_063/acceptance_checklist.json b/task_063/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..8307e52cd26d879ca10e9c0435897c96418c9d9d --- /dev/null +++ b/task_063/acceptance_checklist.json @@ -0,0 +1,22 @@ +{ + "task_id": 110, + "category": "frontend_development", + "language": "javascript", + "acceptance_items": [ + "init: status playing, rows empty, maxGuesses surfaced.", + "No-duplicate guess produces correct black/white.", + "Duplicate-color trap counted with multiset-aware peg counting.", + "All-black guess -> won; exhausting maxGuesses -> lost; post-game guesses ignored.", + "DOM last row .black/.white dot counts match feedback.", + "All contract board elements are visible; all historical rows/cells mirror state after updates and reset." + ], + "expected_outputs": [ + "index.html" + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "risk_notes": [ + "Duplicate-color peg counting (T3) is the discriminator against naive set-intersection.", + "Render-reflection tier defeats no-render in-memory engines." + ], + "repair_revision": "2026-10-07" +} diff --git a/task_063/environment/Dockerfile b/task_063/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2f855b3d12b4e80dd6cd135513202206e95ccdba --- /dev/null +++ b/task_063/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# The mcr/playwright base ships browsers but NOT the `playwright` npm package, +# which the verifier's require('playwright') needs. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_063/environment/code/README.md b/task_063/environment/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..23df919b51fbea6b126e030b03b99ff2f5015995 --- /dev/null +++ b/task_063/environment/code/README.md @@ -0,0 +1,6 @@ +# mastermind — starter + +Implement the game in a single self-contained `index.html` (inline CSS/JS, no +external network). Expose a deterministic `window.__game` API as described in the +task instruction so the verifier can drive it with explicit scenarios. The +rendered DOM must mirror the in-memory game state. diff --git a/task_063/environment/docker-compose.yaml b/task_063/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_063/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_063/instruction.md b/task_063/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fcd82a40625d15cd51c460bb0ec7b3c092747a3e --- /dev/null +++ b/task_063/instruction.md @@ -0,0 +1,20 @@ +# Build Mastermind with duplicate-aware feedback + +Create one self-contained offline `index.html` with inline CSS and JavaScript. Display the guessed code pegs and their feedback in a visible board. + +## State interface + +Expose `window.__game.init({secret,maxGuesses})`, `.getState()` and `.guess(code)`. The secret and guesses are arrays of integer colors from 1 to 6; each guess has the secret's length, which need not be four. Initialization and guessing return the resulting state: + +``` +{rows:[{guess:[...],black,white}], status, maxGuesses} +``` + +Use `playing`, `won` or `lost` for `status`. + +## Acceptance Checklist + +- Init starts play with an empty visible and in-memory history. For each guess, count black pegs for exact positional matches. Remove those matches from both sequences; white counts matched colors among the remaining pegs, limited by their remaining multiplicities. Store the guess in its original order. +- Matching every position wins, including on the final allowed guess. Otherwise, reaching the limit loses. Guesses after either outcome are no-ops. +- Render exactly one `.row` per stored guess inside `#board`; do not use `.row` on empty placeholders. Each guess peg is a visible `.peg` with its `data-color` from 1 to 6 in guess order. Each row's `.feedback` holds the matching numbers of visible `.black` and `.white` dots. +- Keep the current history and displayed pegs synchronized after guesses and resets. diff --git a/task_063/quality_notes.md b/task_063/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..f8d2436cdddb09558e04c8e6fee71601d965359a --- /dev/null +++ b/task_063/quality_notes.md @@ -0,0 +1,14 @@ +# Quality notes — task_110 + +- Deterministic: explicit secret + scripted guesses; no RNG. +- Discrimination via 5 tiers (init / no-dup feedback / duplicate-color trap / + win+lost / render-reflection), fractional reward = tiers passed. +- The duplicate-color peg counting is the core discriminator: a naive + set-intersection or double-counting implementation passes T2 but fails T3. +- An engine that doesn't render feedback dots fails T5; missing lost/won handling + fails T4. +- Verifier uses an INDEPENDENT peg-counting reference model, not source grep. + +## 2026-10-07 review + +The historical five-tier description above describes only the base suite. The active contract has eight equal-weight tiers (five base plus three enhanced). Additional cases strengthen each existing tier without changing its weight. Current checks include visible DOM, multi-step state changes, and independently recomputed contract facts. Specific tested incorrect implementations lose credit; this is not empirical proof of model discrimination or a target model ordering. diff --git a/task_063/solution/README.md b/task_063/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e19401517350d624546614f015d2e8ebb7bb5463 --- /dev/null +++ b/task_063/solution/README.md @@ -0,0 +1,9 @@ +# Reference solution — task_110 (Mastermind) + +Self-contained `index.html`. `window.__game` keeps a secret color code and scores +each `guess(code)` with correct peg counting: `black` = exact-position matches, +`white` = multiset-aware color matches among the remaining (non-black) pegs +(`min(count_in_guess_rest, count_in_secret_rest)` per color). Sets `status` to +`won` (all black) or `lost` (maxGuesses exhausted), ignores guesses after the game +ends, and renders a `#board` of `.row`s whose `.feedback` shows `.black`/`.white` +peg dots matching the computed feedback. diff --git a/task_063/solution/code/index.html b/task_063/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..4656a56ade1f05738e0ae2366669dd0dc2f2191f --- /dev/null +++ b/task_063/solution/code/index.html @@ -0,0 +1,208 @@ + + + + +Mastermind + + + +

      Mastermind

      +

      The code contains four colors (1–6). Click the color swatches to build a guess, then press Submit. +Feedback: a black peg means the color and position are correct; a white peg means the color is correct but the position is not.

      +
      Status: playing — Rows: 0/0
      + +
      +
      + Your Guess: + + + +
      +
      + + + + diff --git a/task_063/solution/solve.sh b/task_063/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_063/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_063/task.toml b/task_063/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_063/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_063/task_meta.json b/task_063/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..b2dd6b7f6bfe2e5008fe26a897361616e857094f --- /dev/null +++ b/task_063/task_meta.json @@ -0,0 +1,15 @@ +{ + "task_id": 110, + "task_category": "frontend_development", + "origin_model": "authored", + "sample_count": 0, + "user_turns": 0, + "language": "javascript", + "input_assets": [], + "expected_outputs": [ + "index.html" + ], + "source_row_id": null, + "repair_revision": "2026-10-07", + "instruction_sha256": "d386f9f765ace21286ee718ec40a2af31952bdcf4db66ea99ea38ab73f6c6c98" +} diff --git a/task_063/tests/_shared/contract_checker.js b/task_063/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_063/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_063/tests/_shared/static_enhancer.sh b/task_063/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_063/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_063/tests/assert_visible.js b/task_063/tests/assert_visible.js new file mode 100644 index 0000000000000000000000000000000000000000..9fbe4fb579ae0e76c915813a8d47d4a1ba67d38f --- /dev/null +++ b/task_063/tests/assert_visible.js @@ -0,0 +1,13 @@ +// Visible contract elements must not be a hidden DOM-only scoring facade. +module.exports = async function assertVisibleBoard(page, selector) { + const failures = await page.locator(selector).evaluateAll(elements => elements.flatMap((element,index) => { + const box = element.getBoundingClientRect(); + let hidden = box.width <= 0 || box.height <= 0; + for(let node=element; node instanceof Element; node=node.parentElement) { + const style = getComputedStyle(node); + hidden ||= style.display==='none' || style.visibility==='hidden' || style.visibility==='collapse' || Number(style.opacity)===0; + } + return hidden ? [index] : []; + })); + if(failures.length) throw new Error('Board elements are not visible: '+failures.join(',')); +}; diff --git a/task_063/tests/enhancement_cases.json b/task_063/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..d556d4cc8d3221d1177399b2f699a5ca5a4b29d1 --- /dev/null +++ b/task_063/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","instruction_evidence":"密码长度由 secret 决定,通常为 4。","validator":"validate_enhanced_cases.js","behavior":"使用长度 5 的 secret/guess,独立计算并验证反馈及保存的猜测长度。"}, + {"case_id":"ENHANCED_CASE_2","instruction_evidence":"先数完所有 black,再对每种颜色累加 min(该颜色在 guess 剩余里的个数, 该颜色在 secret 剩余里的个数)。","validator":"validate_enhanced_cases.js","behavior":"用双方均含重复颜色的新陷阱验证扣除 black 后的多重集合 white。"}, + {"case_id":"ENHANCED_CASE_3","instruction_evidence":"若 rows.length >= maxGuesses → status='lost'。游戏结束后再调用 guess 无效。","validator":"validate_enhanced_cases.js","behavior":"maxGuesses=1 首次失败即 lost,随后正确猜测也不能改变状态。"} +] diff --git a/task_063/tests/test.sh b/task_063/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d550948c62e3205779de94410435fe363acddc8 --- /dev/null +++ b/task_063/tests/test.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +[ -f index.html ] || exit 0 +OUT=$(run validate_ui_behavior.js 2>&1); RC=$?; printf '%s +' "$OUT" +CORE=$(printf '%s +' "$OUT" | sed -n 's/^SCORE=//p' | tail -1) +if [ "$RC" -ne 0 ] || [ -z "$CORE" ]; then CORE=0; fi +OUT=$(run validate_enhanced_cases.js 2>&1); RC=$?; printf '%s +' "$OUT" +ENH=$(printf '%s +' "$OUT" | sed -n 's/^ENHANCED_SCORE=//p' | tail -1) +if [ "$RC" -ne 0 ] || [ -z "$ENH" ]; then ENH=0; fi +node -e 'const [a,b]=process.argv.slice(1).map(Number);if(![a,b].every(x=>Number.isFinite(x)&&x>=0&&x<=1))process.exit(1);console.log((5*a+3*b)/8)' "$CORE" "$ENH" > "$REWARD_FILE" +cat "$REWARD_FILE" diff --git a/task_063/tests/validate_aaav_dynamic.js b/task_063/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..653bf4311e4204ad5d4fbcae970636ad72be2b84 --- /dev/null +++ b/task_063/tests/validate_aaav_dynamic.js @@ -0,0 +1,17 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +const TASK_ID = 110; +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage(); + const errs = []; + page.on('pageerror', e => errs.push(e.message)); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + const ok = await page.evaluate(() => !!(window.__game && typeof window.__game.getState === 'function')); + await browser.close(); + if (errs.length) throw new Error('page errors: ' + errs.join(' | ')); + if (!ok) throw new Error('window.__game.getState missing'); + console.log('AAAV dynamic gate passed for task ' + TASK_ID); +})().catch(e => { console.error('AAAV FAIL: ' + e.message); process.exit(1); }); diff --git a/task_063/tests/validate_browser_smoke.js b/task_063/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_063/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_063/tests/validate_enhanced_cases.js b/task_063/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..6c8c5f48036d14c129d7fe54bf1793c72ea7eb10 --- /dev/null +++ b/task_063/tests/validate_enhanced_cases.js @@ -0,0 +1,45 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +function assert(x, m) { if (!x) throw new Error(m); } +function feedback(secret, guess) { + let black = 0; const s = {}, g = {}; + for (let i = 0; i < secret.length; i++) { if (secret[i] === guess[i]) black++; else { s[secret[i]] = (s[secret[i]] || 0) + 1; g[guess[i]] = (g[guess[i]] || 0) + 1; } } + let white = 0; for (const k of Object.keys(g)) white += Math.min(g[k], s[k] || 0); + return { black, white }; +} +(async () => { + const browser = await chromium.launch({ headless: true, args: ['--no-sandbox', '--disable-dev-shm-usage'] }); + const page = await browser.newPage({ viewport: { width: 520, height: 640 } }); + await page.route(/^https?:\/\//, route => route.abort()); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded', timeout: 10000 }); + const cases = [ + // ENHANCED_CASE_1: secret length determines code length; it is not fixed to four. + ['ENHANCED_CASE_1', async () => { + const secret = [1,2,3,4,5], guess = [1,3,2,6,5], exp = feedback(secret, guess); + const st = await page.evaluate(p => { window.__game.init({ secret: p.secret, maxGuesses: 4 }); return window.__game.guess(p.guess); }, { secret, guess }); + const row = st.rows[0]; + assert(row.guess.length === 5, 'five-peg secret must retain five-peg guesses'); + assert(row.black === exp.black && row.white === exp.white, 'five-peg feedback mismatch'); + }], + // ENHANCED_CASE_2: excess duplicates in both secret and guess use multiset counts after black removal. + ['ENHANCED_CASE_2', async () => { + const secret = [2,2,3,3], guess = [3,3,3,2], exp = feedback(secret, guess); + const st = await page.evaluate(p => { window.__game.init({ secret: p.secret, maxGuesses: 3 }); return window.__game.guess(p.guess); }, { secret, guess }); + const row = st.rows[0]; + assert(row.black === exp.black && row.white === exp.white, `expected ${exp.black}/${exp.white}, got ${row.black}/${row.white}`); + }], + // ENHANCED_CASE_3: maxGuesses=1 loses immediately on a miss and freezes rows. + ['ENHANCED_CASE_3', async () => { + const lost = await page.evaluate(() => { window.__game.init({ secret: [6,5,4,3], maxGuesses: 1 }); return window.__game.guess([1,1,1,1]); }); + assert(lost.status === 'lost' && lost.rows.length === 1, 'first miss at maxGuesses=1 must lose'); + const after = await page.evaluate(() => window.__game.guess([6,5,4,3])); + assert(require("node:util").isDeepStrictEqual(after,lost), 'guess after loss must be ignored'); + const won = await page.evaluate(() => { window.__game.init({ secret: [6,5,4,3], maxGuesses: 1 }); return window.__game.guess([6,5,4,3]); }); + assert(won.status === 'won' && won.rows.length === 1, 'exact guess on final allowed turn must win, not lose'); + }], + ]; + let passed=0; for (const [id, fn] of cases) { try { await fn(); passed++; console.log('PASS '+id); } catch(e) { console.error('FAIL '+id+': '+e.message); } } console.log('ENHANCED_SCORE='+(passed/cases.length)); + await browser.close(); +})().catch(e => { console.error(e.stack || e); process.exit(1); }); + diff --git a/task_063/tests/validate_semantics.js b/task_063/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_063/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_063/tests/validate_ui_behavior.js b/task_063/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..59e92556de8365bc69d5bfdb1d4d7108b5cdf1d5 --- /dev/null +++ b/task_063/tests/validate_ui_behavior.js @@ -0,0 +1,158 @@ +// Tiered deterministic correctness verifier for the Mastermind task. +// Drives window.__game with EXPLICIT secrets/guesses (no RNG) and asserts exact +// feedback against an INDEPENDENT reference peg-counting model. Prints PASS/FAIL +// per tier and a final SCORE= used by test.sh as the (partial) reward. +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +function assert(cond, msg) { if (!cond) throw new Error(msg); } + +// --- independent reference model (mirrors the spec) ----------------------- +// black = exact position matches; white = of the remaining non-black pegs, +// per-color min(count_in_guess_rest, count_in_secret_rest), summed. +function refFeedback(secret, guess) { + const n = secret.length; + let black = 0; + const secRest = {}, guessRest = {}; + for (let i = 0; i < n; i++) { + if (guess[i] === secret[i]) { black++; } + else { + secRest[secret[i]] = (secRest[secret[i]] || 0) + 1; + guessRest[guess[i]] = (guessRest[guess[i]] || 0) + 1; + } + } + let white = 0; + for (const color in guessRest) { + if (secRest[color]) white += Math.min(guessRest[color], secRest[color]); + } + return { black, white }; +} + +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 520, height: 640 } }); + const errs = []; + page.on('pageerror', e => errs.push(e.message)); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(300); + const run = (fn, arg) => page.evaluate(fn, arg); + + const hasApi = await page.evaluate(() => !!(window.__game + && typeof window.__game.init === 'function' + && typeof window.__game.getState === 'function' + && typeof window.__game.guess === 'function')); + + const tiers = [ + ['T1 API + init (status playing, no rows, maxGuesses surfaced)', async () => { + assert(hasApi, 'window.__game with init/getState/guess is required'); + assert(errs.length === 0, 'no page errors allowed: ' + errs.join(' | ')); + const st = await run(() => window.__game.init({ secret: [1, 2, 3, 4], maxGuesses: 8 })); + assert(st.status === 'playing', 'fresh status must be playing, got ' + st.status); + assert(Array.isArray(st.rows) && st.rows.length === 0, 'fresh rows must be empty'); + assert(st.maxGuesses === 8, 'maxGuesses must be 8, got ' + st.maxGuesses); + }], + + ['T2 black/white for a no-duplicate guess (independent recompute)', async () => { + const secret = [1, 2, 3, 4]; + const g = [1, 3, 2, 5]; // black: pos0 (1). rest secret {2,3,4} guess {3,2,5} -> 2,3 match => white 2 + const st = await run((p) => window.__game.init(p).status === 'playing' + ? window.__game.guess([1, 3, 2, 5]) : null, { secret, maxGuesses: 8 }); + const ref = refFeedback(secret, g); + const last = st.rows[st.rows.length - 1]; + assert(last.black === ref.black, `black must be ${ref.black}, got ${last.black}`); + assert(last.white === ref.white, `white must be ${ref.white}, got ${last.white}`); + }], + + ['T3 the DUPLICATE-color trap (multiset-aware recompute)', async () => { + const secret = [1, 1, 2, 3]; + const g = [1, 2, 1, 1]; // black: pos0 (1). rest secret {1,2,3} guess {2,1,1}. + // color1: min(2,1)=1; color2: min(1,1)=1 => white 2 + const ref = refFeedback(secret, g); + const st = await run((p) => { window.__game.init(p); return window.__game.guess([1, 2, 1, 1]); }, + { secret, maxGuesses: 8 }); + const last = st.rows[st.rows.length - 1]; + assert(last.black === ref.black, `dup-trap black must be ${ref.black}, got ${last.black}`); + assert(last.white === ref.white, `dup-trap white must be ${ref.white}, got ${last.white}`); + // a second trap: secret all same, guess one match + const secret2 = [4, 4, 4, 4], g2 = [4, 1, 1, 1]; + const ref2 = refFeedback(secret2, g2); // black 1, white 0 + const st2 = await run((p) => { window.__game.init(p); return window.__game.guess([4, 1, 1, 1]); }, + { secret: secret2, maxGuesses: 8 }); + const l2 = st2.rows[st2.rows.length - 1]; + assert(l2.black === ref2.black && l2.white === ref2.white, + `all-same trap must be black ${ref2.black}/white ${ref2.white}, got ${l2.black}/${l2.white}`); + for (let offset = 1; offset < 6; offset++) { + const shiftedSecret = secret.map(c => (c-1+offset)%6+1); + const shiftedGuess = g.map(c => (c-1+offset)%6+1); + const state = await run(p => { window.__game.init({secret:p.secret,maxGuesses:3}); return window.__game.guess(p.guess); }, {secret:shiftedSecret,guess:shiftedGuess}); + const row = state.rows[0], expected = refFeedback(shiftedSecret,shiftedGuess); + assert(row.black===expected.black && row.white===expected.white, 'color permutation feedback'); + assert(require('node:util').isDeepStrictEqual(row.guess,shiftedGuess), 'stored guess must retain all colors'); + } + }], + + ['T4 all-correct -> won; exhausting guesses -> lost', async () => { + const secret = [2, 4, 6, 1]; + let st = await run((p) => { window.__game.init(p); return window.__game.guess([2, 4, 6, 1]); }, + { secret, maxGuesses: 3 }); + const last = st.rows[st.rows.length - 1]; + assert(last.black === 4 && last.white === 0, 'exact guess must be 4 black / 0 white'); + assert(st.status === 'won', 'all-black guess must set status won, got ' + st.status); + // further guesses ignored once won + const rowsAtWin = st.rows.length; + st = await run(() => window.__game.guess([1, 1, 1, 1])); + assert(st.status === 'won' && st.rows.length === rowsAtWin, 'guesses after win must be ignored'); + // lost path: 2 maxGuesses, never solve + st = await run((p) => { window.__game.init(p); window.__game.guess([1, 1, 1, 1]); return window.__game.guess([1, 1, 1, 1]); }, + { secret: [2, 3, 4, 5], maxGuesses: 2 }); + assert(st.status === 'lost', 'exhausting maxGuesses without solving must set status lost, got ' + st.status); + // further guesses ignored once lost + const rowsAtLoss = st.rows.length; + st = await run(() => window.__game.guess([2, 3, 4, 5])); + assert(st.status === 'lost' && st.rows.length === rowsAtLoss, 'guesses after loss must be ignored'); + }], + + ['T5 render-reflection: every DOM row mirrors history and init clears it', async () => { + const secret = [1, 1, 2, 3]; + const guesses = [[1, 2, 1, 1], [6, 6, 6, 6], [1, 1, 2, 3]]; + const st = await run(({ secret, guesses }) => { + window.__game.init({ secret, maxGuesses: 8 }); + for (const guess of guesses) window.__game.guess(guess); + return window.__game.getState(); + }, { secret, guesses }); + const domRows = await run(() => Array.from(document.querySelectorAll('#board .row'), row => ({ + black: row.querySelectorAll('.feedback .black').length, + white: row.querySelectorAll('.feedback .white').length, + pegs: row.querySelectorAll('.peg').length, + colors: Array.from(row.querySelectorAll('.peg'), peg => Number(peg.dataset.color)), + }))); + assert(domRows.length === st.rows.length, `DOM must render ${st.rows.length} rows, got ${domRows.length}`); + st.rows.forEach((row, index) => { + const dom = domRows[index]; + assert(dom.pegs === row.guess.length, `row ${index} must render ${row.guess.length} code pegs, got ${dom.pegs}`); + assert(require('node:util').isDeepStrictEqual(dom.colors,row.guess), `row ${index} visible peg order must mirror guess`); + assert(dom.black === row.black, `row ${index} black pegs ${dom.black} must equal ${row.black}`); + assert(dom.white === row.white, `row ${index} white pegs ${dom.white} must equal ${row.white}`); + }); + await require('./assert_visible.js')(page,'#board .peg, #board .feedback .black, #board .feedback .white'); + await page.screenshot({path:'/logs/verifier/mastermind-history.png',fullPage:true}); + await run(() => window.__game.init({ secret: [4, 3, 2, 1], maxGuesses: 2 })); + const cleared = await run(() => ({ + state: window.__game.getState(), + rows: document.querySelectorAll('#board .row').length, + })); + assert(cleared.state.rows.length === 0 && cleared.rows === 0, 'init must clear visible and in-memory history'); + await page.screenshot({path:'/logs/verifier/mastermind-reset.png',fullPage:true}); + }], + ]; + + let passed = 0; + for (const [name, fn] of tiers) { + try { await fn(); passed++; console.log('PASS ' + name); } + catch (e) { console.log('FAIL ' + name + ': ' + (e && e.message || e)); } + } + console.log('TIERS ' + passed + '/' + tiers.length); + console.log('SCORE=' + (passed / tiers.length).toFixed(3)); + await browser.close(); +})().catch(e => { console.log('FATAL ' + (e && e.stack || e)); console.log('SCORE=0'); }); diff --git a/task_064/acceptance_checklist.json b/task_064/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..7453b54a1017a292f050fdc5922b3b1e0ce5d49a --- /dev/null +++ b/task_064/acceptance_checklist.json @@ -0,0 +1,22 @@ +{ + "task_id": 111, + "category": "frontend_development", + "language": "javascript", + "acceptance_items": [ + "init parses dims/source/sink and computes per-cell sides from type+rotation.", + "rotate cycles a cell's open sides correctly through 4 states.", + "connected is false on a deliberately-broken layout.", + "Rotating the right cell completes the path (connected true); rotating again breaks it.", + "DOM data-sides / .pipe count mirrors each cell's state sides.", + "All contract board elements are visible; all historical rows/cells mirror state after updates and reset." + ], + "expected_outputs": [ + "index.html" + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "risk_notes": [ + "Mutual-opening connectivity rule (T3/T4) discriminates against single-border-open shortcuts.", + "Render-reflection tier defeats no-render in-memory engines." + ], + "repair_revision": "2026-10-07" +} diff --git a/task_064/environment/Dockerfile b/task_064/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2f855b3d12b4e80dd6cd135513202206e95ccdba --- /dev/null +++ b/task_064/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# The mcr/playwright base ships browsers but NOT the `playwright` npm package, +# which the verifier's require('playwright') needs. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_064/environment/code/README.md b/task_064/environment/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e6ad62086f1233e8702ab7d74df0bbe0dc9818ef --- /dev/null +++ b/task_064/environment/code/README.md @@ -0,0 +1,6 @@ +# pipepuzzle — starter + +Implement the game in a single self-contained `index.html` (inline CSS/JS, no +external network). Expose a deterministic `window.__game` API as described in the +task instruction so the verifier can drive it with explicit scenarios. The +rendered DOM must mirror the in-memory game state. diff --git a/task_064/environment/docker-compose.yaml b/task_064/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_064/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_064/instruction.md b/task_064/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ca8c39581e70fb1ee3cb37e722e08039f93627d2 --- /dev/null +++ b/task_064/instruction.md @@ -0,0 +1,18 @@ +# Build a rotating pipe-connection puzzle + +Create a single self-contained offline `index.html` with inline CSS and JavaScript. Show a visible pipe grid with distinct source and sink markers. + +## State interface + +Expose `window.__game.init(level)`, `.getState()` and `.rotate(r,c)`. Initialization and rotation return the resulting state. + +- Level: `{rows,cols,cells:[{type,rotation}],source:[r,c],sink:[r,c]}`. Use row-major cells and zero-based coordinates. Types are `straight`, `elbow` and `empty`; rotations are 0, 90, 180 and 270 degrees clockwise. +- State: `{rows,cols,cells:[{type,rotation,sides}],connected,source,sink}`. Each `sides` array lists open edges in `N,E,S,W` order. +- At rotation 0 a straight pipe opens north and south, an elbow opens north and east, and an empty cell has no openings. A clockwise quarter turn maps `N→E→S→W→N`; an empty pipe never gains openings. + +## Acceptance Checklist + +- Initialize from the supplied layout and calculate each opening by type and rotation. Rotate one valid cell clockwise by 90 degrees modulo 360; out-of-bounds requests do not change state. +- The source and sink are connected only when there is a path of adjacent cells open to each other along each common edge. Paths may bend or offer multiple routes; a one-sided opening never connects. A source equal to the sink is connected even in an empty cell. +- Recalculate connectivity and rendering after rotations, both when completing a path and when breaking it. +- In `#board`, render each position as a visible `.cell` with `data-sides` equal to its opening letters concatenated in canonical order and one visible `.pipe` per opening. Apply `.source` and `.sink` to the corresponding marked positions. diff --git a/task_064/quality_notes.md b/task_064/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..794494da76b333da31ce8b3625bdab3f13dddd7b --- /dev/null +++ b/task_064/quality_notes.md @@ -0,0 +1,15 @@ +# Quality notes — task_111 + +- Deterministic: explicit grid layouts + scripted rotations; no RNG. +- Discrimination via 5 tiers (init sides / rotation cycle / disconnected / + rotate-to-connect / render-reflection), fractional reward = tiers passed. +- The side-rotation mapping and the mutual-opening connectivity rule are the + discriminators: an impl with a wrong rotation direction fails T2; one that + treats a single open border (not mutual) as connected, or ignores rotation in + connectivity, fails T3/T4. +- A no-render engine fails T5 (data-sides / .pipe reflection). +- Verifier uses an INDEPENDENT side-recompute + BFS reference, not source grep. + +## 2026-10-07 review + +The historical five-tier description above describes only the base suite. The active contract has eight equal-weight tiers (five base plus three enhanced). Additional cases strengthen each existing tier without changing its weight. Current checks include visible DOM, multi-step state changes, and independently recomputed contract facts. Specific tested incorrect implementations lose credit; this is not empirical proof of model discrimination or a target model ordering. diff --git a/task_064/solution/README.md b/task_064/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d5cf9968e29c8e6b8d6cde2b9420f986f66a0176 --- /dev/null +++ b/task_064/solution/README.md @@ -0,0 +1,9 @@ +# Reference solution — task_111 (Pipe puzzle) + +Self-contained `index.html`. `window.__game` stores a grid of pipe cells +(`straight`/`elbow`/`empty`) each with a rotation. Open sides are derived from +type+rotation (clockwise `N->E->S->W` mapping). `rotate(r,c)` advances a cell's +rotation by 90 deg and recomputes sides + connectivity. `connected` is true iff a +BFS from `source` reaches `sink` through adjacent cells that each open the shared +border. The DOM renders each `.cell` with a `data-sides` attribute and matching +`.pipe` elements mirroring the state. diff --git a/task_064/solution/code/index.html b/task_064/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..cd8de698c0c423a65dfc45601da7e21be62568fc --- /dev/null +++ b/task_064/solution/code/index.html @@ -0,0 +1,209 @@ + + + + +Pipe Puzzle + + + +

      Pipe Puzzle

      +

      Click any pipe tile to rotate it 90° clockwise. Build a connected route from the green source to the red sink.

      +
      Connected: false
      + +
      +
      + + + + diff --git a/task_064/solution/solve.sh b/task_064/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_064/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_064/task.toml b/task_064/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_064/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_064/task_meta.json b/task_064/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..4c915e1703a5c908aaeda3b7e53d94bfa0d0e940 --- /dev/null +++ b/task_064/task_meta.json @@ -0,0 +1,15 @@ +{ + "task_id": 111, + "task_category": "frontend_development", + "origin_model": "authored", + "sample_count": 0, + "user_turns": 0, + "language": "javascript", + "input_assets": [], + "expected_outputs": [ + "index.html" + ], + "source_row_id": null, + "repair_revision": "2026-10-07", + "instruction_sha256": "4bdb2532492756cbabd2a48ac0f0daa70a9976323bbcf6c2c3ef981c90e4b4ac" +} diff --git a/task_064/tests/_shared/contract_checker.js b/task_064/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_064/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_064/tests/_shared/static_enhancer.sh b/task_064/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_064/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_064/tests/assert_visible.js b/task_064/tests/assert_visible.js new file mode 100644 index 0000000000000000000000000000000000000000..9fbe4fb579ae0e76c915813a8d47d4a1ba67d38f --- /dev/null +++ b/task_064/tests/assert_visible.js @@ -0,0 +1,13 @@ +// Visible contract elements must not be a hidden DOM-only scoring facade. +module.exports = async function assertVisibleBoard(page, selector) { + const failures = await page.locator(selector).evaluateAll(elements => elements.flatMap((element,index) => { + const box = element.getBoundingClientRect(); + let hidden = box.width <= 0 || box.height <= 0; + for(let node=element; node instanceof Element; node=node.parentElement) { + const style = getComputedStyle(node); + hidden ||= style.display==='none' || style.visibility==='hidden' || style.visibility==='collapse' || Number(style.opacity)===0; + } + return hidden ? [index] : []; + })); + if(failures.length) throw new Error('Board elements are not visible: '+failures.join(',')); +}; diff --git a/task_064/tests/enhancement_cases.json b/task_064/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..731ace7e618c7067dce046f0de04dc5737df5507 --- /dev/null +++ b/task_064/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","instruction_evidence":"source===sink 视为已连通。","validator":"validate_enhanced_cases.js","behavior":"单个 empty 格同时作为 source/sink,验证无需开放边也 connected。"}, + {"case_id":"ENHANCED_CASE_2","instruction_evidence":"rotate(r,c)……越界为无操作。","validator":"validate_enhanced_cases.js","behavior":"验证上、下、左、右四类越界坐标都不改变任何状态。"}, + {"case_id":"ENHANCED_CASE_3","instruction_evidence":"两相邻格连通当且仅当各自都开放共享的那条边。","validator":"validate_enhanced_cases.js","behavior":"显式弯折路径先连通,再旋转移除互相开口并验证断开。"} +] diff --git a/task_064/tests/test.sh b/task_064/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d550948c62e3205779de94410435fe363acddc8 --- /dev/null +++ b/task_064/tests/test.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +[ -f index.html ] || exit 0 +OUT=$(run validate_ui_behavior.js 2>&1); RC=$?; printf '%s +' "$OUT" +CORE=$(printf '%s +' "$OUT" | sed -n 's/^SCORE=//p' | tail -1) +if [ "$RC" -ne 0 ] || [ -z "$CORE" ]; then CORE=0; fi +OUT=$(run validate_enhanced_cases.js 2>&1); RC=$?; printf '%s +' "$OUT" +ENH=$(printf '%s +' "$OUT" | sed -n 's/^ENHANCED_SCORE=//p' | tail -1) +if [ "$RC" -ne 0 ] || [ -z "$ENH" ]; then ENH=0; fi +node -e 'const [a,b]=process.argv.slice(1).map(Number);if(![a,b].every(x=>Number.isFinite(x)&&x>=0&&x<=1))process.exit(1);console.log((5*a+3*b)/8)' "$CORE" "$ENH" > "$REWARD_FILE" +cat "$REWARD_FILE" diff --git a/task_064/tests/validate_aaav_dynamic.js b/task_064/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..f7516d1641104094c77d9c8d42bf98a178fe2ff0 --- /dev/null +++ b/task_064/tests/validate_aaav_dynamic.js @@ -0,0 +1,17 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +const TASK_ID = 111; +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage(); + const errs = []; + page.on('pageerror', e => errs.push(e.message)); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + const ok = await page.evaluate(() => !!(window.__game && typeof window.__game.getState === 'function')); + await browser.close(); + if (errs.length) throw new Error('page errors: ' + errs.join(' | ')); + if (!ok) throw new Error('window.__game.getState missing'); + console.log('AAAV dynamic gate passed for task ' + TASK_ID); +})().catch(e => { console.error('AAAV FAIL: ' + e.message); process.exit(1); }); diff --git a/task_064/tests/validate_browser_smoke.js b/task_064/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_064/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_064/tests/validate_enhanced_cases.js b/task_064/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..cb3cb03bc8e7398c267f2cd2d4927acfb711b329 --- /dev/null +++ b/task_064/tests/validate_enhanced_cases.js @@ -0,0 +1,40 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +function assert(x, m) { if (!x) throw new Error(m); } +(async () => { + const browser = await chromium.launch({ headless: true, args: ['--no-sandbox', '--disable-dev-shm-usage'] }); + const page = await browser.newPage({ viewport: { width: 520, height: 640 } }); + await page.route(/^https?:\/\//, route => route.abort()); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded', timeout: 10000 }); + const cases = [ + // ENHANCED_CASE_1: source equal to sink is connected even for an empty pipe. + ['ENHANCED_CASE_1', async () => { + const st = await page.evaluate(() => window.__game.init({ rows: 1, cols: 1, cells: [{ type: 'empty', rotation: 270 }], source: [0,0], sink: [0,0] })); + assert(st.connected === true, 'source===sink must be connected'); + assert(st.cells[0].sides.length === 0, 'empty cell must have no sides at any rotation'); + }], + // ENHANCED_CASE_2: every out-of-bounds rotate is a complete no-op. + ['ENHANCED_CASE_2', async () => { + const L = { rows: 2, cols: 2, cells: Array(4).fill(0).map(() => ({ type: 'elbow', rotation: 0 })), source: [0,0], sink: [1,1] }; + const before = await page.evaluate(L => window.__game.init(L), L); + for (const rc of [[-1,0],[0,-1],[2,0],[0,2]]) { + const after = await page.evaluate(p => window.__game.rotate(p[0], p[1]), rc); + assert(require("node:util").isDeepStrictEqual(after,before), `rotate ${rc} must be ignored`); + } + }], + // ENHANCED_CASE_3: connectivity follows a bent path only through mutual openings. + ['ENHANCED_CASE_3', async () => { + const L = { rows: 2, cols: 2, cells: [ + {type:'elbow',rotation:90}, {type:'elbow',rotation:180}, + {type:'empty',rotation:0}, {type:'straight',rotation:0}], source:[0,0], sink:[1,1] }; + const st = await page.evaluate(L => window.__game.init(L), L); + assert(st.connected === true, 'E/S then W/S path must connect source to sink'); + const broken = await page.evaluate(() => window.__game.rotate(0, 1)); + assert(broken.connected === false, 'removing the reciprocal west opening must break the path'); + }], + ]; + let passed=0; for (const [id, fn] of cases) { try { await fn(); passed++; console.log('PASS '+id); } catch(e) { console.error('FAIL '+id+': '+e.message); } } console.log('ENHANCED_SCORE='+(passed/cases.length)); + await browser.close(); +})().catch(e => { console.error(e.stack || e); process.exit(1); }); + diff --git a/task_064/tests/validate_render_mirror.js b/task_064/tests/validate_render_mirror.js new file mode 100644 index 0000000000000000000000000000000000000000..42ace31655042be1cda18fa5bf9a74ec13b8600c --- /dev/null +++ b/task_064/tests/validate_render_mirror.js @@ -0,0 +1,20 @@ +const {isDeepStrictEqual:eq}=require('node:util'); +module.exports=async function mirror(page,id){ + const x=await page.evaluate(id=>{const s=window.__game.getState();const sel=id===109?'.row':id===108?'.tile':'.cell'; + let cells=[...document.querySelectorAll('#board '+sel)]; + if(id!==109)cells.sort((a,b)=>{const x=a.getBoundingClientRect(),y=b.getBoundingClientRect();return Math.abs(x.top-y.top)>2?x.top-y.top:x.left-y.left}); + return {s,dom:cells.map(e=>({classes:[...e.classList],text:e.textContent.trim(),sides:e.dataset.sides,v:e.dataset.v,tiles:[...e.querySelectorAll('.tile')].map(t=>({text:t.textContent.trim(),mark:['g','y','b'].find(c=>t.classList.contains(c))}))}))}},id); + const {s,dom}=x;const a=(ok,msg)=>{if(!ok)throw Error('render mirror: '+msg)}; + const at=(p,r,c)=>p.some(q=>q[0]===r&&q[1]===c); + if(id===109){const filled=dom.filter(r=>r.tiles.some(t=>t.mark));a(filled.length===s.rows.length,'guessed rows');s.rows.forEach((r,i)=>{a(eq(filled[i].tiles.map(t=>t.text.toLowerCase()),r.word.toLowerCase().split('')),'letters row '+i);a(eq(filled[i].tiles.map(t=>t.mark),r.marks),'marks row '+i)});return} + if(id===108){a(eq(dom.map(e=>+e.v),s.tiles),'tile positions');a(eq(dom.map(e=>e.text),s.tiles.map(v=>v?String(v):'')),'tile numbers');return} + dom.forEach((e,i)=>{const has=c=>e.classes.includes(c); + if(id===106){const r=Math.floor(i/s.width),c=i%s.width;a(has('box')===at(s.boxes,r,c),'box '+i);a(has('target')===at(s.targets,r,c),'target '+i);a(has('wall')===at(s.walls,r,c),'wall '+i);a(has('player')===(s.player.r===r&&s.player.c===c),'player '+i)} + if(id===107)a(has('on')===s.grid[i],'light '+i); + if(id===111){const r=Math.floor(i/s.cols),c=i%s.cols;a(has('source')===(s.source[0]===r&&s.source[1]===c),'source '+i);a(has('sink')===(s.sink[0]===r&&s.sink[1]===c),'sink '+i);a(e.sides===s.cells[i].sides.join(''),'pipe sides '+i)} + if(id===112){const r=Math.floor(i/s.cols),c=i%s.cols;a(has('beam')===at(s.path,r,c),'beam '+i);a(has('source')===(s.source.r===r&&s.source.c===c),'source '+i);a(has('target')===(s.target.r===r&&s.target.c===c),'target '+i)} + if(id===113){a(has('r')===(s.board[i]===1),'red '+i);a(has('y')===(s.board[i]===2),'yellow '+i)} + if(id===114)a(has('alive')===s.grid[i],'life '+i); + if(id===115){a(e.text===(s.grid[i]?String(s.grid[i]):''),'number '+i);a(has('given')===s.givens[i],'given '+i);a(has('conflict')===s.conflicts.includes(i),'conflict '+i)} + }); +}; diff --git a/task_064/tests/validate_semantics.js b/task_064/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_064/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_064/tests/validate_ui_behavior.js b/task_064/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..d3da395efdd8719b3e47db8e61eacd8842974385 --- /dev/null +++ b/task_064/tests/validate_ui_behavior.js @@ -0,0 +1,216 @@ +// Tiered deterministic correctness verifier for the Pipe-puzzle task. +// Drives window.__game with EXPLICIT layouts (no RNG) and asserts open-sides and +// connectivity against an INDEPENDENT reference model (sides recomputed from +// type+rotation; connectivity via own BFS). Prints PASS/FAIL per tier and a final +// SCORE= used by test.sh as the (partial) reward. +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +function assert(cond, msg) { if (!cond) throw new Error(msg); } + +// --- independent reference model (mirrors the spec) ----------------------- +const ROT = { N: 'E', E: 'S', S: 'W', W: 'N' }; +const OPP = { N: 'S', S: 'N', E: 'W', W: 'E' }; +const DELTA = { N: [-1, 0], S: [1, 0], E: [0, 1], W: [0, -1] }; +const BASE = { straight: ['N', 'S'], elbow: ['N', 'E'], empty: [] }; + +function refSides(type, rotation) { + const steps = (((rotation % 360) + 360) % 360) / 90 % 4; + const out = (BASE[type] || []).map(s => { + let x = s; for (let i = 0; i < steps; i++) x = ROT[x]; return x; + }); + return ['N', 'E', 'S', 'W'].filter(s => out.includes(s)); +} + +function refConnected(level) { + const { rows, cols, cells, source, sink } = level; + const idx = (r, c) => r * cols + c; + const sidesOf = i => refSides(cells[i].type, cells[i].rotation || 0); + const seen = new Set([idx(source[0], source[1])]); + const stack = [[source[0], source[1]]]; + let connected = (source[0] === sink[0] && source[1] === sink[1]); + while (stack.length) { + const [r, c] = stack.pop(); + for (const s of sidesOf(idx(r, c))) { + const [dr, dc] = DELTA[s]; + const nr = r + dr, nc = c + dc; + if (nr < 0 || nc < 0 || nr >= rows || nc >= cols) continue; + if (!sidesOf(idx(nr, nc)).includes(OPP[s])) continue; + const k = idx(nr, nc); + if (seen.has(k)) continue; + seen.add(k); + if (nr === sink[0] && nc === sink[1]) connected = true; + stack.push([nr, nc]); + } + } + return connected; +} + +function eqSides(a, b) { + return Array.isArray(a) && a.length === b.length && a.every((side, i) => side === b[i]); +} + +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 640, height: 640 } }); + const errs = []; + page.on('pageerror', e => errs.push(e.message)); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(300); + const run = (fn, arg) => page.evaluate(fn, arg); + + const hasApi = await page.evaluate(() => !!(window.__game + && typeof window.__game.init === 'function' + && typeof window.__game.getState === 'function' + && typeof window.__game.rotate === 'function')); + + // A 2x2 layout used by several tiers. + const L = { + rows: 2, cols: 2, + cells: [ + { type: 'elbow', rotation: 90 }, // (0,0) + { type: 'elbow', rotation: 180 }, // (0,1) + { type: 'elbow', rotation: 0 }, // (1,0) + { type: 'elbow', rotation: 270 }, // (1,1) + ], + source: [0, 0], sink: [1, 1], + }; + + const tiers = [ + ['T1 init: dims/source/sink + initial sides per cell (independent recompute)', async () => { + assert(hasApi, 'window.__game with init/getState/rotate is required'); + assert(errs.length === 0, 'no page errors allowed: ' + errs.join(' | ')); + const st = await run((L) => window.__game.init(L), L); + assert(st.rows === L.rows && st.cols === L.cols, `dims must be ${L.rows}x${L.cols}`); + assert(st.source[0] === 0 && st.source[1] === 0, 'source must be (0,0)'); + assert(st.sink[0] === 1 && st.sink[1] === 1, 'sink must be (1,1)'); + for (let i = 0; i < L.cells.length; i++) { + const ref = refSides(L.cells[i].type, L.cells[i].rotation); + assert(eqSides(st.cells[i].sides, ref), + `cell ${i} sides must be [${ref}], got [${st.cells[i].sides}]`); + } + }], + + ['T2 rotate cycles a cell through 4 correct side-states', async () => { + // single straight cell; rotate 4 times -> back to start, each step recomputed + const S = { rows: 1, cols: 1, cells: [{ type: 'straight', rotation: 0 }], source: [0, 0], sink: [0, 0] }; + let st = await run((S) => window.__game.init(S), S); + let rot = 0; + for (let step = 0; step < 5; step++) { + const ref = refSides('straight', rot); + assert(eqSides(st.cells[0].sides, ref), + `straight @${rot} sides must be [${ref}], got [${st.cells[0].sides}]`); + assert(st.cells[0].rotation === ((rot % 360) + 360) % 360, + `rotation must be ${rot % 360}, got ${st.cells[0].rotation}`); + st = await run(() => window.__game.rotate(0, 0)); + rot = (rot + 90) % 360; + } + // also verify an elbow cycles through all four distinct states + const E = { rows: 1, cols: 1, cells: [{ type: 'elbow', rotation: 0 }], source: [0, 0], sink: [0, 0] }; + st = await run((E) => window.__game.init(E), E); + const seen = []; + for (let step = 0; step < 4; step++) { + seen.push(st.cells[0].sides.join('')); + const ref = refSides('elbow', step * 90); + assert(eqSides(st.cells[0].sides, ref), + `elbow @${step * 90} sides must be [${ref}], got [${st.cells[0].sides}]`); + st = await run(() => window.__game.rotate(0, 0)); + } + assert(new Set(seen).size === 4, 'elbow must produce 4 distinct rotation states, got ' + seen.join(',')); + }], + + ['T3 connectivity false on a deliberately-broken config', async () => { + // straight row but middle cell turned the wrong way -> broken + const B = { + rows: 1, cols: 3, + cells: [ + { type: 'straight', rotation: 90 }, // {E,W} + { type: 'straight', rotation: 0 }, // {N,S} <- breaks the horizontal run + { type: 'straight', rotation: 90 }, // {E,W} + ], + source: [0, 0], sink: [0, 2], + }; + const st = await run((B) => window.__game.init(B), B); + const ref = refConnected(B); + assert(ref === false, 'reference sanity: broken layout must be disconnected'); + assert(st.connected === ref, `connected must be ${ref}, got ${st.connected}`); + }], + + ['T4 rotating the right cell completes the path -> connected true (and a miss -> false)', async () => { + const B = { + rows: 1, cols: 3, + cells: [ + { type: 'straight', rotation: 90 }, // {E,W} + { type: 'straight', rotation: 0 }, // {N,S} broken + { type: 'straight', rotation: 90 }, // {E,W} + ], + source: [0, 0], sink: [0, 2], + }; + let st = await run((B) => window.__game.init(B), B); + assert(st.connected === false, 'starts disconnected'); + // rotate middle cell once: {N,S} -> {E,W}, now a full horizontal run + st = await run(() => window.__game.rotate(0, 1)); + const fixed = JSON.parse(JSON.stringify(B)); + fixed.cells[1].rotation = 90; + const ref = refConnected(fixed); + assert(ref === true, 'reference sanity: fixed layout must be connected'); + assert(st.connected === ref, `after rotate connected must be ${ref}, got ${st.connected}`); + // rotating it again breaks it back -> false + st = await run(() => window.__game.rotate(0, 1)); + const broken2 = JSON.parse(JSON.stringify(B)); + broken2.cells[1].rotation = 180; // {N,S} again + const ref2 = refConnected(broken2); + assert(ref2 === false, 'reference sanity: rotated-again layout must be disconnected'); + assert(st.connected === ref2, `after second rotate connected must be ${ref2}, got ${st.connected}`); + // A larger cycle checks nonlocal paths, untouched cells and repeated recomputation. + const cycle = {rows:3,cols:3,source:[0,0],sink:[2,2],cells:[ + {type:'elbow',rotation:90},{type:'straight',rotation:90},{type:'elbow',rotation:180}, + {type:'straight',rotation:0},{type:'empty',rotation:0},{type:'straight',rotation:0}, + {type:'elbow',rotation:0},{type:'straight',rotation:90},{type:'elbow',rotation:270}]}; + await run(level => window.__game.init(level), cycle); + for (const [r,c] of [[0,1],[1,0],[0,1],[1,0],[0,2],[2,0],[0,2],[2,0]]) { + cycle.cells[r*3+c].rotation = (cycle.cells[r*3+c].rotation+90)%360; + const actual = await run(([r,c]) => window.__game.rotate(r,c), [r,c]); + assert(actual.connected === refConnected(cycle), 'cycle connectivity must follow both available routes'); + cycle.cells.forEach((cell,i) => assert(actual.cells[i].rotation === cell.rotation && eqSides(actual.cells[i].sides,refSides(cell.type,cell.rotation)), 'cycle cell '+i)); + } + }], + + ['T5 render-reflection: a cell DOM data-sides matches its state sides', async () => { + const st = await run((L) => window.__game.init(L), L); + const dom = await run(() => { + const cells = Array.from(document.querySelectorAll('#board .cell')); + return cells.map(c => ({ + sides: c.getAttribute('data-sides') || '', + pipes: c.querySelectorAll('.pipe').length, + })); + }); + assert(dom.length === st.cells.length, `DOM must render ${st.cells.length} cells, got ${dom.length}`); + for (let i = 0; i < st.cells.length; i++) { + const domSides = dom[i].sides.split('').filter(Boolean); + assert(eqSides(domSides, st.cells[i].sides), + `cell ${i} DOM data-sides [${dom[i].sides}] must match state [${st.cells[i].sides}]`); + assert(dom[i].pipes === st.cells[i].sides.length, + `cell ${i} DOM pipe count ${dom[i].pipes} must equal sides ${st.cells[i].sides.length}`); + } + // after a rotate the DOM must update too + await run(() => window.__game.rotate(0, 0)); + const st2 = await run(() => window.__game.getState()); + const dom2 = await run(() => (document.querySelectorAll('#board .cell')[0].getAttribute('data-sides') || '')); + assert(eqSides(dom2.split('').filter(Boolean), st2.cells[0].sides), + 'DOM data-sides must track state after a rotate'); + await require('./assert_visible.js')(page,'#board .cell, #board .pipe'); + await page.screenshot({path:'/logs/verifier/pipe-rotated.png',fullPage:true}); + }], + ]; + + let passed = 0; + for (const [name, fn] of tiers) { + try { await fn(); if(name.startsWith('T5'))await require('./validate_render_mirror.js')(page,111); passed++; console.log('PASS ' + name); } + catch (e) { console.log('FAIL ' + name + ': ' + (e && e.message || e)); } + } + console.log('TIERS ' + passed + '/' + tiers.length); + console.log('SCORE=' + (passed / tiers.length).toFixed(3)); + await browser.close(); +})().catch(e => { console.log('FATAL ' + (e && e.stack || e)); console.log('SCORE=0'); }); diff --git a/task_065/acceptance_checklist.json b/task_065/acceptance_checklist.json new file mode 100644 index 0000000000000000000000000000000000000000..8df1674ebbb15fc30155c3eb0bb620c0c135435b --- /dev/null +++ b/task_065/acceptance_checklist.json @@ -0,0 +1,23 @@ +{ + "task_id": 115, + "category": "frontend_development", + "language": "javascript", + "acceptance_items": [ + "init parses grid and givens mask; a valid partial puzzle has zero conflicts.", + "set writes/clears a non-given cell; editing a given cell is a no-op.", + "A duplicate in a row/col/box flags both cells in conflicts (independent recompute).", + "Completed valid grid -> solved true; full but invalid grid -> solved false.", + "DOM board mirrors state (.given == givens count, .conflict == conflicts length, 81 cells).", + "All contract board elements are visible; all historical rows/cells mirror state after updates and reset." + ], + "expected_outputs": [ + "index.html" + ], + "verifier_style": "deterministic runtime behavior and published artifact/protocol checks", + "risk_notes": [ + "Render-reflection tier defeats no-render in-memory engines.", + "Given-cell no-op tier discriminates engines that allow overwriting givens.", + "Full-but-invalid grid case discriminates engines that equate 'full' with 'solved'." + ], + "repair_revision": "2026-10-07" +} diff --git a/task_065/environment/Dockerfile b/task_065/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2f855b3d12b4e80dd6cd135513202206e95ccdba --- /dev/null +++ b/task_065/environment/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1.7-labs +FROM mcr.microsoft.com/playwright:v1.52.0-noble@sha256:a021500a801bab0611049217ffad6b9697d827205c15babb86a53bc1a61c02d5 +WORKDIR /app +COPY ./code /app + +# The mcr/playwright base ships browsers but NOT the `playwright` npm package, +# which the verifier's require('playwright') needs. +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 +RUN npm install -g playwright@1.52.0 +ENV NODE_PATH=/usr/lib/node_modules diff --git a/task_065/environment/code/README.md b/task_065/environment/code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0c9b790ce3246a367540cd5549d65a0cb093ac6a --- /dev/null +++ b/task_065/environment/code/README.md @@ -0,0 +1,6 @@ +# sudoku — starter + +Implement the game in a single self-contained `index.html` (inline CSS/JS, no +external network). Expose a deterministic `window.__game` API as described in the +task instruction so the verifier can drive it with explicit scenarios. The +rendered DOM must mirror the in-memory game state. diff --git a/task_065/environment/docker-compose.yaml b/task_065/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..641e765f247233a6ea65a602a803cb846aa82e47 --- /dev/null +++ b/task_065/environment/docker-compose.yaml @@ -0,0 +1,4 @@ +services: + main: + build: + network: host diff --git a/task_065/instruction.md b/task_065/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a4aacd8b318af2f36ee4ffaea60164de545f89eb --- /dev/null +++ b/task_065/instruction.md @@ -0,0 +1,20 @@ +# Build a Sudoku board with live conflict detection + +Create a single self-contained offline `index.html` with inline CSS and JavaScript. Show a visible 9×9 board, immutable givens and current conflicts. + +## State interface + +Expose `window.__game.init({puzzle})`, `.getState()` and `.set(index,value)`. The puzzle is an 81-element row-major array of integers from 0 to 9, with 0 blank. Index a cell by `row * 9 + column`. Init and set return the resulting state: + +``` +{ grid, givens, conflicts, solved } +``` + +`grid` has the current 81 values; `givens` is an 81-element boolean array fixed from the nonzero cells at initialization. `conflicts` contains unique sorted cell indices, and `solved` is a boolean. + +## Acceptance Checklist + +- Initialize the exact puzzle and givens. Set editable cells to integers 1 through 9, or clear with integer 0. Reject edits to givens and any index/value that is noninteger, nonfinite, out of range or a different type; do not coerce. +- Mark every nonzero cell that belongs to a repeated digit in its row, column or 3×3 box. Include all involved cells exactly once in ascending order. Correcting or clearing digits removes conflicts that no longer exist. +- A board is solved exactly when every cell is filled and no conflicts exist. A fully filled but invalid board is not solved. +- Inside `#board`, display all 81 visible `.cell` positions in row-major order. Show the current digit or blank, apply `.given` and `.conflict` exactly where applicable, and clear stale markers on changes. diff --git a/task_065/quality_notes.md b/task_065/quality_notes.md new file mode 100644 index 0000000000000000000000000000000000000000..f432fd59d00ad24225a9285c501d7abbfaaf6dd3 --- /dev/null +++ b/task_065/quality_notes.md @@ -0,0 +1,16 @@ +# Quality notes — task_115 + +- Deterministic: a valid completed SOLUTION and a derived legal PUZZLE are baked + into both the instruction and the verifier as fixtures; all edits are explicit; + no RNG. +- Discrimination via 5 tiers (init/givens/no-conflict / set + given no-op / + duplicate->conflict / solved detection / render-reflection), fractional reward + = tiers passed. An engine that lets you overwrite givens fails T2; one with a + buggy box/row/col conflict scan fails T3; one that calls a full-but-invalid + grid solved fails T4; a no-render engine fails T5. +- Verifier uses an independent conflict/solved recompute over rows, columns and + 3x3 boxes; the page is never trusted against its own claims. + +## 2026-10-07 review + +The historical five-tier description above describes only the base suite. The active contract has eight equal-weight tiers (five base plus three enhanced). Additional cases strengthen each existing tier without changing its weight. Current checks include visible DOM, multi-step state changes, and independently recomputed contract facts. Specific tested incorrect implementations lose credit; this is not empirical proof of model discrimination or a target model ordering. diff --git a/task_065/solution/README.md b/task_065/solution/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f0314d71480426b5c77f921974e1a3d837c3e7ce --- /dev/null +++ b/task_065/solution/README.md @@ -0,0 +1,10 @@ +# Reference solution — task_115 (Sudoku) + +Self-contained `index.html`. `window.__game.init({puzzle})` loads an 81-int +row-major grid and derives the `givens` mask (true where the puzzle is non-zero). +`set(index, value)` writes a value 1-9 (or 0 to clear) into a non-given cell; +editing a given cell, or an out-of-range index/value, is a no-op. `getState()` +recomputes `conflicts` (ascending indices of filled cells duplicated within a +row/column/3x3 box) and `solved` (grid full and zero conflicts). The DOM mirrors +state: `#board` renders 81 `.cell`s, givens carry `.given`, conflicting cells +carry `.conflict`, and each cell shows its digit. diff --git a/task_065/solution/code/index.html b/task_065/solution/code/index.html new file mode 100644 index 0000000000000000000000000000000000000000..e37113f520a7f862fcda943ec3702df1ac89691f --- /dev/null +++ b/task_065/solution/code/index.html @@ -0,0 +1,206 @@ + + + + +Sudoku + + + +

      Sudoku

      +

      Select an empty cell, then enter 1–9. Press 0 or Backspace to clear it, or use the number pad below. +Bold cells are fixed clues. Complete the puzzle without duplicates in any row, column, or 3×3 box.

      +
      Solved: false — Conflicts: 0
      + +
      +
      + + + + +
      +
      + + + + diff --git a/task_065/solution/solve.sh b/task_065/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ea7d2d30d0b77a65cb741efb73effa08b27a5f3 --- /dev/null +++ b/task_065/solution/solve.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TARGET="${1:-$(pwd)}" +cp -R "$SCRIPT_DIR/code/." "$TARGET/" diff --git a/task_065/task.toml b/task_065/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9cd83c379ce8ba3bc41c0cf733279a8bdfcca5c1 --- /dev/null +++ b/task_065/task.toml @@ -0,0 +1,21 @@ +version = "1.0" + +[metadata] + +[verifier] +timeout_sec = 300.0 + +[agent] +timeout_sec = 3600.0 + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 2048 +storage_mb = 10240 +gpus = 0 +allow_internet = true + +[verifier.env] + +[solution.env] diff --git a/task_065/task_meta.json b/task_065/task_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..d708167f1806f0affd541a9062f97a17d44ec8ab --- /dev/null +++ b/task_065/task_meta.json @@ -0,0 +1,15 @@ +{ + "task_id": 115, + "task_category": "frontend_development", + "origin_model": "authored", + "sample_count": 0, + "user_turns": 0, + "language": "javascript", + "input_assets": [], + "expected_outputs": [ + "index.html" + ], + "source_row_id": null, + "repair_revision": "2026-10-07", + "instruction_sha256": "0b061f11ab3c464c48f5f8141a5e8c6130872afd47985855b51f941e4bcd7666" +} diff --git a/task_065/tests/_shared/contract_checker.js b/task_065/tests/_shared/contract_checker.js new file mode 100644 index 0000000000000000000000000000000000000000..1901642f3ba488b2af0d7a9be5900525add3e679 --- /dev/null +++ b/task_065/tests/_shared/contract_checker.js @@ -0,0 +1,497 @@ +const fs = require('fs'); +const path = require('path'); +const { chromium } = require('playwright'); + +const DEFAULT_TIMEOUT_MS = 12000; + +function walk(dir) { + let out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue; + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out = out.concat(walk(p)); + else out.push(p); + } + return out; +} + +function stripNoisyComments(text) { + return text + .replace(//g, ' ') + .replace(/\/\*([\s\S]*?)\*\//g, ' ') + .replace(/(^|[^:])\/\/.*$/gm, '$1 ') + .toLowerCase(); +} + +function readSourceText(taskDir) { + const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']); + const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase())); + if (files.length === 0) { + throw new Error('no source files found for semantic validation'); + } + return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n'); +} + +function hasAnyIn(text, list) { + return list.some((t) => text.includes(String(t).toLowerCase())); +} + +function hasAll(text, list) { + return list.every((t) => text.includes(String(t).toLowerCase())); +} + +function escapedRegExp(token) { + return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function readContract(taskDir) { + const contractPath = path.join(taskDir, 'tests', 'task_contract.json'); + if (!fs.existsSync(contractPath)) { + throw new Error(`missing task_contract.json: ${contractPath}`); + } + return JSON.parse(fs.readFileSync(contractPath, 'utf8')); +} + +function checkSemantics(contract, taskDir) { + const text = stripNoisyComments(readSourceText(taskDir)); + const rules = contract.semantics || {}; + const errors = []; + const warnings = []; + + if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) { + errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`); + } + if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) { + errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`); + } + if (Array.isArray(rules.all_groups)) { + for (const group of rules.all_groups) { + if (!hasAnyIn(text, group)) { + errors.push(`missing required semantic group: ${group.join(' | ')}`); + } + } + } + if (rules.min_tokens && typeof rules.min_tokens === 'object') { + for (const [token, minCount] of Object.entries(rules.min_tokens)) { + const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length; + if (count < minCount) { + errors.push(`token "${token}" count ${count} < ${minCount}`); + } + } + } + if (contract.compat && contract.compat.minSourceBytes) { + // reserve compatibility pass for extremely small outputs + const files = walk(taskDir); + let total = 0; + for (const f of files) { + const stat = fs.statSync(f); + if (stat.isFile()) total += stat.size; + } + if (total < Number(contract.compat.minSourceBytes)) { + warnings.push(`source footprint small: ${total} bytes`); + } + } + + return { strictOk: errors.length === 0, warnings, errors }; +} + +function pick(selectorList) { + return selectorList.filter(Boolean).join(', '); +} + +async function gatherEntry(taskDir) { + const files = walk(taskDir); + const html = files.find((f) => f.toLowerCase().endsWith('.html')); + if (!html) throw new Error('no html entrypoint found'); + return html; +} + +async function startBrowser(taskDir) { + const entry = await gatherEntry(taskDir); + const browser = await chromium.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); + const page = await browser.newPage({ viewport: { width: 1100, height: 760 } }); + const errors = []; + page.on('pageerror', (err) => errors.push(err.message || String(err))); + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()); + }); + await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + if (errors.length) { + await browser.close(); + throw new Error('browser load errors: ' + errors.join(' | ')); + } + return { browser, page, errors }; +} + +function pathToFileUrl(filePath) { + const abs = path.resolve(filePath); + return new URL('file://' + abs.replace(/\\/g, '/')).href; +} + +function assertStateDiff(before, after, message) { + if (before === after) { + throw new Error(message); + } +} + +function toNumberText(v) { + return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0; +} + +async function checkGomoku(taskDir, config) { + const sel = config.selectors || {}; + const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']); + const statusSel = sel.status; + const resetSel = sel.reset; + + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cellsSel).count(); + if (count < 40) { + throw new Error('board-like grid should have at least 40 cells'); + } + const before = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count }; + }, { cellsSel, statusSel }); + const first = page.locator(cellsSel).nth(0); + const second = page.locator(cellsSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(200); + const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) { + throw new Error('clicking board cells does not alter board state'); + } + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount === 0) { + throw new Error('reset control not found'); + } + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + const afterReset = await page.evaluate(({ cellsSel, statusSel }) => { + const cells = Array.from(document.querySelectorAll(cellsSel)); + const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : ''; + const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length; + const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||'); + return { occupied, marker, status, count: cells.length }; + }, { cellsSel, statusSel }); + if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) { + throw new Error('reset does not restore board state'); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkMemoryMatch(taskDir, config) { + const sel = config.selectors || {}; + const cardSel = pick([sel.card, '.card', '[data-card]']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const count = await page.locator(cardSel).count(); + if (count < 8) { + throw new Error('not enough cards rendered'); + } + const before = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + const first = page.locator(cardSel).nth(0); + const second = page.locator(cardSel).nth(1); + await first.click({ force: true }); + await page.waitForTimeout(120); + await second.click({ force: true }); + await page.waitForTimeout(700); + const after = await page.evaluate((cardSel) => { + const cards = Array.from(document.querySelectorAll(cardSel)); + return { + flipCount: cards.filter((c) => c.classList.contains('flip')).length, + matchedCount: cards.filter((c) => c.classList.contains('matched')).length, + moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText, + }; + }, cardSel); + if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) { + throw new Error('card interaction is not reflected in UI state'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkTowerDefense(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#game']); + const spawnSel = pick([sel.spawn, '#spawn']); + const resetSel = pick([sel.reset, '#reset']); + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 120); + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (!before) throw new Error('canvas not found'); + const spawnCount = await page.locator(spawnSel).count(); + if (spawnCount === 0) throw new Error('spawn control not found'); + await page.locator(spawnSel).first().click({ force: true }); + await page.waitForTimeout(900); + const afterSpawn = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) { + throw new Error('spawn action has no observable effect'); + } + + const canvas = page.locator(canvasSel); + const box = await canvas.boundingBox(); + if (box) { + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForTimeout(500); + } + const afterPlace = await page.evaluate((canvasSel) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 120) || ''; + } catch { + canvasSample = ''; + } + return { + canvasSample, + hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, canvasSel); + if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) { + throw new Error('placing tower on canvas has no observable effect'); + } + + if (resetSel) { + const resetCount = await page.locator(resetSel).count(); + if (resetCount > 0) { + await page.locator(resetSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkLudo(taskDir, config) { + const sel = config.selectors || {}; + const rollSel = pick([sel.roll, '#roll, button']); + const statusSel = sel.status || '#status'; + const diceSel = sel.dice || '#dice'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + + const rollCount = await page.locator(rollSel).count(); + if (rollCount === 0) throw new Error('roll control not found'); + for (let i = 0; i < 4; i++) { + await page.locator(rollSel).first().click({ force: true }); + await page.waitForTimeout(220); + } + const after = await page.evaluate(({ statusSel, diceSel }) => { + return { + status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '', + dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '', + boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '', + }; + }, { statusSel, diceSel }); + if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) { + throw new Error('turn + dice workflow has no state change'); + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +async function checkSpaceShooter(taskDir, config) { + const sel = config.selectors || {}; + const canvasSel = pick([sel.canvas, 'canvas', '#space']); + const restartSel = pick([sel.restart, '#restart']); + const scoreSel = sel.score || '#score'; + const hpSel = sel.hp || '#hp'; + const task = async () => { + const { browser, page } = await startBrowser(taskDir); + try { + const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + if (!canvas) return null; + let canvasSample = ''; + try { + canvasSample = canvas.toDataURL().slice(0, 140); + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (!before) throw new Error('canvas not found'); + const canvas = page.locator(canvasSel).first(); + await canvas.click({ force: true }); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.keyboard.press('Space'); + await page.waitForTimeout(500); + const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => { + const canvas = document.querySelector(canvasSel); + let canvasSample = ''; + try { + canvasSample = canvas?.toDataURL().slice(0, 140) || ''; + } catch { + canvasSample = ''; + } + const scoreEl = document.querySelector(scoreSel); + const hpEl = document.querySelector(hpSel); + return { + canvasSample, + scoreText: scoreEl ? scoreEl.innerText : '', + hpText: hpEl ? hpEl.innerText : '', + }; + }, { canvasSel, scoreSel, hpSel }); + if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) { + throw new Error('shooting key interaction has no observable effect'); + } + if (restartSel) { + const restartCount = await page.locator(restartSel).count(); + if (restartCount > 0) { + await page.locator(restartSel).first().click({ force: true }); + await page.waitForTimeout(250); + } + } + await browser.close(); + } catch (err) { + await browser.close(); + throw err; + } + }; + return task(); +} + +const behaviorRunners = { + gomoku: checkGomoku, + memory_match: checkMemoryMatch, + tower_defense: checkTowerDefense, + ludo: checkLudo, + space_shooter: checkSpaceShooter, +}; + +async function runContractChecks({ taskDir, mode }) { + const contract = readContract(taskDir); + if (mode === 'semantics' || mode === 'full') { + const semantic = checkSemantics(contract, taskDir); + if (semantic.warnings.length) { + console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings })); + } + if (!semantic.strictOk) { + throw new Error('semantic checks failed: ' + semantic.errors.join(' | ')); + } + } + + if (mode === 'browser' || mode === 'full') { + const browserType = (contract.browser || {}).type; + const runner = behaviorRunners[browserType]; + if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`); + await runner(taskDir, contract.browser || {}); + } + + console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true })); +} + +if (require.main === module) { + (async () => { + const args = Object.fromEntries( + process.argv.slice(2).map((arg, idx, all) => { + if (!arg.startsWith('--')) return null; + const key = arg.slice(2); + const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true'; + return [key, value]; + }).filter(Boolean) + ); + const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd(); + const mode = args.mode || 'full'; + await runContractChecks({ taskDir, mode }); + })().catch((err) => { + console.error(err && err.stack ? err.stack : String(err)); + process.exit(1); + }); +} + +module.exports = { runContractChecks }; diff --git a/task_065/tests/_shared/static_enhancer.sh b/task_065/tests/_shared/static_enhancer.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a56e973028e92019dcd3039964fa42098774ae1 --- /dev/null +++ b/task_065/tests/_shared/static_enhancer.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Behavioral validators own scoring; no source-length or lexical proxy gates. +static_enhance_check() { return 0; } diff --git a/task_065/tests/assert_visible.js b/task_065/tests/assert_visible.js new file mode 100644 index 0000000000000000000000000000000000000000..9fbe4fb579ae0e76c915813a8d47d4a1ba67d38f --- /dev/null +++ b/task_065/tests/assert_visible.js @@ -0,0 +1,13 @@ +// Visible contract elements must not be a hidden DOM-only scoring facade. +module.exports = async function assertVisibleBoard(page, selector) { + const failures = await page.locator(selector).evaluateAll(elements => elements.flatMap((element,index) => { + const box = element.getBoundingClientRect(); + let hidden = box.width <= 0 || box.height <= 0; + for(let node=element; node instanceof Element; node=node.parentElement) { + const style = getComputedStyle(node); + hidden ||= style.display==='none' || style.visibility==='hidden' || style.visibility==='collapse' || Number(style.opacity)===0; + } + return hidden ? [index] : []; + })); + if(failures.length) throw new Error('Board elements are not visible: '+failures.join(',')); +}; diff --git a/task_065/tests/enhancement_cases.json b/task_065/tests/enhancement_cases.json new file mode 100644 index 0000000000000000000000000000000000000000..7534d6bebca4d42bbc10e2fca019dc5bbbf98eef --- /dev/null +++ b/task_065/tests/enhancement_cases.json @@ -0,0 +1,5 @@ +[ + {"case_id":"ENHANCED_CASE_1","instruction_evidence":"index 越界……为无操作。","validator":"validate_enhanced_cases.js","behavior":"分别验证 -1 与 81 两端越界索引不改变任何状态。"}, + {"case_id":"ENHANCED_CASE_2","instruction_evidence":"value 越界(不在 0..9)为无操作。","validator":"validate_enhanced_cases.js","behavior":"分别验证 -1 与 10 两端越界值不改变任何状态。"}, + {"case_id":"ENHANCED_CASE_3","instruction_evidence":"conflicts:升序的索引数组——所有已填且与同行/列/3×3 宫内另一已填格重复的格子索引。","validator":"validate_enhanced_cases.js","behavior":"一次构造横行、纵列和宫内重复,验证冲突索引升序且去重。"} +] diff --git a/task_065/tests/test.sh b/task_065/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d550948c62e3205779de94410435fe363acddc8 --- /dev/null +++ b/task_065/tests/test.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +set -uo pipefail +TEST_DIR="$(cd "$(dirname "$0")" && pwd)" +LOG_DIR=/logs/verifier +mkdir -p "$LOG_DIR" 2>/dev/null || { LOG_DIR="$PWD/logs/verifier"; mkdir -p "$LOG_DIR"; } +REWARD_FILE="$LOG_DIR/reward.txt" +echo 0 > "$REWARD_FILE" +run() { timeout 90s node "$TEST_DIR/$1"; } +[ -f index.html ] || exit 0 +OUT=$(run validate_ui_behavior.js 2>&1); RC=$?; printf '%s +' "$OUT" +CORE=$(printf '%s +' "$OUT" | sed -n 's/^SCORE=//p' | tail -1) +if [ "$RC" -ne 0 ] || [ -z "$CORE" ]; then CORE=0; fi +OUT=$(run validate_enhanced_cases.js 2>&1); RC=$?; printf '%s +' "$OUT" +ENH=$(printf '%s +' "$OUT" | sed -n 's/^ENHANCED_SCORE=//p' | tail -1) +if [ "$RC" -ne 0 ] || [ -z "$ENH" ]; then ENH=0; fi +node -e 'const [a,b]=process.argv.slice(1).map(Number);if(![a,b].every(x=>Number.isFinite(x)&&x>=0&&x<=1))process.exit(1);console.log((5*a+3*b)/8)' "$CORE" "$ENH" > "$REWARD_FILE" +cat "$REWARD_FILE" diff --git a/task_065/tests/validate_aaav_dynamic.js b/task_065/tests/validate_aaav_dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..ab49f7269e4cb71d2d6273535bbffbcbe94f9772 --- /dev/null +++ b/task_065/tests/validate_aaav_dynamic.js @@ -0,0 +1,17 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +const TASK_ID = 115; +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage(); + const errs = []; + page.on('pageerror', e => errs.push(e.message)); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(250); + const ok = await page.evaluate(() => !!(window.__game && typeof window.__game.getState === 'function')); + await browser.close(); + if (errs.length) throw new Error('page errors: ' + errs.join(' | ')); + if (!ok) throw new Error('window.__game.getState missing'); + console.log('AAAV dynamic gate passed for task ' + TASK_ID); +})().catch(e => { console.error('AAAV FAIL: ' + e.message); process.exit(1); }); diff --git a/task_065/tests/validate_browser_smoke.js b/task_065/tests/validate_browser_smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e650eff67e93970efd0352fb6f8b2ae41091c4 --- /dev/null +++ b/task_065/tests/validate_browser_smoke.js @@ -0,0 +1,6 @@ +const fs=require('fs'),path=require('path'),{pathToFileURL}=require('url'),{chromium}=require('playwright'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +(async()=>{const entry=walk(process.cwd()).find(f=>/\.(html|svg)$/i.test(f));if(!entry)throw Error('missing browser entry'); +const b=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage']});try{const p=await b.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route(/^https?:/,r=>r.abort());await p.goto(pathToFileURL(entry).href,{waitUntil:'load'}); +if(!await p.evaluate(()=>[...document.querySelectorAll('body *,svg')].some(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'})))throw Error('entry does not render'); +if(errors.length)throw Error(errors.join(' | '));console.log('render smoke passed');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/task_065/tests/validate_enhanced_cases.js b/task_065/tests/validate_enhanced_cases.js new file mode 100644 index 0000000000000000000000000000000000000000..19e5d4b97ddfc50c17fe51ac4adc33f6fbc9b248 --- /dev/null +++ b/task_065/tests/validate_enhanced_cases.js @@ -0,0 +1,39 @@ +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); +function assert(x, m) { if (!x) throw new Error(m); } +(async () => { + const browser = await chromium.launch({ headless: true, args: ['--no-sandbox', '--disable-dev-shm-usage'] }); + const page = await browser.newPage({ viewport: { width: 520, height: 640 } }); + await page.route(/^https?:\/\//, route => route.abort()); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded', timeout: 10000 }); + const empty = Array(81).fill(0); + const cases = [ + // ENHANCED_CASE_1: both ends of the invalid index range are no-ops. + ['ENHANCED_CASE_1', async () => { + const before = await page.evaluate(P => window.__game.init({ puzzle:P }), empty); + for (const index of [-1, 81, 0.5, NaN, Infinity, '2']) { + const after = await page.evaluate(i => window.__game.set(i, 5), index); + assert(require("node:util").isDeepStrictEqual(after,before), `set index ${index} must be ignored`); + } + }], + // ENHANCED_CASE_2: values below 0 and above 9 are complete no-ops. + ['ENHANCED_CASE_2', async () => { + const before = await page.evaluate(P => window.__game.init({ puzzle:P }), empty); + for (const value of [-1, 10, 1.5, NaN, Infinity, '5']) { + const after = await page.evaluate(v => window.__game.set(40, v), value); + assert(require("node:util").isDeepStrictEqual(after,before), `set value ${value} must be ignored`); + } + }], + // ENHANCED_CASE_3: conflicts combine row, column, and 3x3-box duplicates, sorted and unique. + ['ENHANCED_CASE_3', async () => { + const st = await page.evaluate(P => { window.__game.init({ puzzle:P }); for (const i of [0,4,10,36,40]) window.__game.set(i,5); return window.__game.getState(); }, empty); + const expected = [0,4,10,36,40]; + assert(require("node:util").isDeepStrictEqual(st.conflicts,expected), `combined conflicts must be sorted unique ${expected}, got ${st.conflicts}`); + assert(st.solved === false, 'partial conflicting board cannot be solved'); + }], + ]; + let passed=0; for (const [id, fn] of cases) { try { await fn(); passed++; console.log('PASS '+id); } catch(e) { console.error('FAIL '+id+': '+e.message); } } console.log('ENHANCED_SCORE='+(passed/cases.length)); + await browser.close(); +})().catch(e => { console.error(e.stack || e); process.exit(1); }); + diff --git a/task_065/tests/validate_render_mirror.js b/task_065/tests/validate_render_mirror.js new file mode 100644 index 0000000000000000000000000000000000000000..42ace31655042be1cda18fa5bf9a74ec13b8600c --- /dev/null +++ b/task_065/tests/validate_render_mirror.js @@ -0,0 +1,20 @@ +const {isDeepStrictEqual:eq}=require('node:util'); +module.exports=async function mirror(page,id){ + const x=await page.evaluate(id=>{const s=window.__game.getState();const sel=id===109?'.row':id===108?'.tile':'.cell'; + let cells=[...document.querySelectorAll('#board '+sel)]; + if(id!==109)cells.sort((a,b)=>{const x=a.getBoundingClientRect(),y=b.getBoundingClientRect();return Math.abs(x.top-y.top)>2?x.top-y.top:x.left-y.left}); + return {s,dom:cells.map(e=>({classes:[...e.classList],text:e.textContent.trim(),sides:e.dataset.sides,v:e.dataset.v,tiles:[...e.querySelectorAll('.tile')].map(t=>({text:t.textContent.trim(),mark:['g','y','b'].find(c=>t.classList.contains(c))}))}))}},id); + const {s,dom}=x;const a=(ok,msg)=>{if(!ok)throw Error('render mirror: '+msg)}; + const at=(p,r,c)=>p.some(q=>q[0]===r&&q[1]===c); + if(id===109){const filled=dom.filter(r=>r.tiles.some(t=>t.mark));a(filled.length===s.rows.length,'guessed rows');s.rows.forEach((r,i)=>{a(eq(filled[i].tiles.map(t=>t.text.toLowerCase()),r.word.toLowerCase().split('')),'letters row '+i);a(eq(filled[i].tiles.map(t=>t.mark),r.marks),'marks row '+i)});return} + if(id===108){a(eq(dom.map(e=>+e.v),s.tiles),'tile positions');a(eq(dom.map(e=>e.text),s.tiles.map(v=>v?String(v):'')),'tile numbers');return} + dom.forEach((e,i)=>{const has=c=>e.classes.includes(c); + if(id===106){const r=Math.floor(i/s.width),c=i%s.width;a(has('box')===at(s.boxes,r,c),'box '+i);a(has('target')===at(s.targets,r,c),'target '+i);a(has('wall')===at(s.walls,r,c),'wall '+i);a(has('player')===(s.player.r===r&&s.player.c===c),'player '+i)} + if(id===107)a(has('on')===s.grid[i],'light '+i); + if(id===111){const r=Math.floor(i/s.cols),c=i%s.cols;a(has('source')===(s.source[0]===r&&s.source[1]===c),'source '+i);a(has('sink')===(s.sink[0]===r&&s.sink[1]===c),'sink '+i);a(e.sides===s.cells[i].sides.join(''),'pipe sides '+i)} + if(id===112){const r=Math.floor(i/s.cols),c=i%s.cols;a(has('beam')===at(s.path,r,c),'beam '+i);a(has('source')===(s.source.r===r&&s.source.c===c),'source '+i);a(has('target')===(s.target.r===r&&s.target.c===c),'target '+i)} + if(id===113){a(has('r')===(s.board[i]===1),'red '+i);a(has('y')===(s.board[i]===2),'yellow '+i)} + if(id===114)a(has('alive')===s.grid[i],'life '+i); + if(id===115){a(e.text===(s.grid[i]?String(s.grid[i]):''),'number '+i);a(has('given')===s.givens[i],'given '+i);a(has('conflict')===s.conflicts.includes(i),'conflict '+i)} + }); +}; diff --git a/task_065/tests/validate_semantics.js b/task_065/tests/validate_semantics.js new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9b66f737d9a937623b74dc07f918591f5bd --- /dev/null +++ b/task_065/tests/validate_semantics.js @@ -0,0 +1,4 @@ +const fs=require('fs'),path=require('path'); +function walk(d){return fs.readdirSync(d,{withFileTypes:true}).filter(e=>!['tests','logs','node_modules','.git'].includes(e.name)).flatMap(e=>e.isDirectory()?walk(path.join(d,e.name)):[path.join(d,e.name)])} +if(!walk(process.cwd()).some(f=>/\.(html|svg|js|ts|tsx|jsx|md)$/i.test(f)))throw Error('missing candidate output'); +console.log('candidate output present; requirements checked by runtime cases'); diff --git a/task_065/tests/validate_ui_behavior.js b/task_065/tests/validate_ui_behavior.js new file mode 100644 index 0000000000000000000000000000000000000000..ef6619754eaece357e177af98387b17d5e270ab0 --- /dev/null +++ b/task_065/tests/validate_ui_behavior.js @@ -0,0 +1,166 @@ +// Tiered deterministic correctness verifier for the Sudoku task. +// Drives window.__game with EXPLICIT puzzles/edits (no RNG) and asserts exact +// state against an INDEPENDENT conflict/solved recompute. Prints PASS/FAIL per +// tier and a final SCORE= used by test.sh as the (partial) reward. +const path = require('path'); +const { pathToFileURL } = require('url'); +const { chromium } = require('playwright'); + +function assert(cond, msg) { if (!cond) throw new Error(msg); } + +// --- fixtures (a valid completed solution + a derived puzzle) -------------- +const SOLUTION = [ + 5,3,4, 6,7,8, 9,1,2, + 6,7,2, 1,9,5, 3,4,8, + 1,9,8, 3,4,2, 5,6,7, + 8,5,9, 7,6,1, 4,2,3, + 4,2,6, 8,5,3, 7,9,1, + 7,1,3, 9,2,4, 8,5,6, + 9,6,1, 5,3,7, 2,8,4, + 2,8,7, 4,1,9, 6,3,5, + 3,4,5, 2,8,6, 1,7,9, +]; +// A valid partial puzzle (subset of SOLUTION cells blanked) -> no conflicts. +const PUZZLE = [ + 5,3,0, 6,7,0, 9,1,0, + 6,7,2, 0,9,5, 3,4,0, + 1,9,0, 3,4,2, 0,6,7, + 8,5,9, 0,6,1, 0,2,3, + 4,2,0, 8,5,3, 0,9,1, + 7,1,3, 0,2,4, 0,5,6, + 9,6,0, 5,3,7, 0,8,4, + 0,8,7, 4,1,0, 6,3,5, + 0,4,5, 0,8,6, 0,7,9, +]; + +// --- independent reference: conflicts + solved ---------------------------- +function refConflicts(grid) { + const bad = new Set(); + const groups = []; + for (let r = 0; r < 9; r++) { const g = []; for (let c = 0; c < 9; c++) g.push(r * 9 + c); groups.push(g); } + for (let c = 0; c < 9; c++) { const g = []; for (let r = 0; r < 9; r++) g.push(r * 9 + c); groups.push(g); } + for (let br = 0; br < 3; br++) for (let bc = 0; bc < 3; bc++) { + const g = []; for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) g.push((br * 3 + r) * 9 + (bc * 3 + c)); groups.push(g); + } + for (const grp of groups) { + const seen = {}; + for (const i of grp) { const v = grid[i]; if (v === 0) continue; (seen[v] = seen[v] || []).push(i); } + for (const v in seen) if (seen[v].length > 1) seen[v].forEach(i => bad.add(i)); + } + return Array.from(bad).sort((a, b) => a - b); +} +function refSolved(grid) { + const full = grid.every(v => v >= 1 && v <= 9); + return full && refConflicts(grid).length === 0; +} +function eqArr(a, b) { return a.length === b.length && a.every((x, i) => x === b[i]); } + +(async () => { + const browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 420, height: 500 } }); + const errs = []; + page.on('pageerror', e => errs.push(e.message)); + await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(300); + const run = (fn, arg) => page.evaluate(fn, arg); + + const hasApi = await page.evaluate(() => !!(window.__game + && typeof window.__game.init === 'function' + && typeof window.__game.getState === 'function' + && typeof window.__game.set === 'function')); + + const tiers = [ + ['T1 init: givens mask + no conflicts on a valid partial puzzle', async () => { + assert(hasApi, 'window.__game with init/getState/set is required'); + assert(errs.length === 0, 'no page errors allowed: ' + errs.join(' | ')); + const st = await run((P) => window.__game.init({ puzzle: P }), PUZZLE); + assert(st.grid.length === 81, 'grid must be 81 ints, got ' + st.grid.length); + assert(eqArr(st.grid, PUZZLE), 'grid must equal the puzzle on init'); + const givens = PUZZLE.map(v => v !== 0); + assert(st.givens.length === 81 && st.givens.every((g, i) => !!g === givens[i]), + 'givens mask must be true exactly where the puzzle is non-zero'); + assert(eqArr(st.conflicts, refConflicts(PUZZLE)), 'a valid partial puzzle must have no conflicts'); + assert(st.conflicts.length === 0, 'valid partial puzzle should report zero conflicts, got ' + st.conflicts.length); + assert(st.solved === false, 'partial puzzle is not solved'); + }], + + ['T2 set a non-given cell; setting a given is a no-op', async () => { + let st = await run((P) => window.__game.init({ puzzle: P }), PUZZLE); + // find a blank (non-given) index, set it to its correct solution value + const blank = PUZZLE.findIndex(v => v === 0); + assert(blank >= 0, 'fixture must contain a blank'); + st = await run((b) => window.__game.set(b, 4), blank); // 4 is not necessarily correct; just must reflect + assert(st.grid[blank] === 4, 'set must place the value into a non-given cell'); + // clear it again with 0 + st = await run((b) => window.__game.set(b, 0), blank); + assert(st.grid[blank] === 0, 'set with 0 must clear a non-given cell'); + // attempt to overwrite a GIVEN cell -> no-op + const given = PUZZLE.findIndex(v => v !== 0); + const before = st.grid[given]; + st = await run((g) => window.__game.set(g, ((window.__game.getState().grid[g] % 9) + 1)), given); + assert(st.grid[given] === before, 'editing a given cell must be a no-op (value unchanged)'); + }], + + ['T3 introduce a duplicate -> that pair appears in conflicts (independent recompute)', async () => { + // Put a duplicate in a row: row 0 of PUZZLE is 5,3,_,6,7,_,9,1,_ (blanks at idx 2,5,8). + // Setting idx 2 = 5 duplicates the 5 at idx 0 -> both should be conflicts. + await run((P) => window.__game.init({ puzzle: P }), PUZZLE); + let st = await run(() => window.__game.set(2, 5)); + const grid = st.grid; + const ref = refConflicts(grid); + assert(eqArr(st.conflicts, ref), 'conflicts must match independent recompute: got ' + JSON.stringify(st.conflicts) + ' want ' + JSON.stringify(ref)); + assert(st.conflicts.includes(0) && st.conflicts.includes(2), 'the duplicated pair (idx 0 and 2) must both be flagged'); + // a column duplicate too: blank at idx 8 (row0,col8). col8 already has 7,7? recompute via ref. + st = await run(() => window.__game.set(8, 7)); // col8: row0=7? check via ref + const ref2 = refConflicts(st.grid); + assert(eqArr(st.conflicts, ref2), 'conflicts after second edit must match independent recompute'); + st = await run(() => { window.__game.set(2,0); return window.__game.set(8,0); }); + assert(eqArr(st.conflicts, refConflicts(st.grid)) && st.conflicts.length === 0, 'clearing edits must remove stale conflicts'); + await require('./validate_render_mirror.js')(page,115); + }], + + ['T4 completing a valid puzzle -> solved true; an invalid full grid -> solved false', async () => { + // Near-solved: full solution with exactly one blank at index 80. + const near = SOLUTION.slice(); near[80] = 0; + await run((P) => window.__game.init({ puzzle: P }), near); + let st = await run(() => window.__game.set(80, 9)); // 9 is the correct value + assert(st.solved === refSolved(st.grid) && st.solved === true, 'a correctly completed grid must be solved=true'); + // now an invalid full grid: set the last cell wrong (but first must re-init since 80 is non-given here) + await run((P) => window.__game.init({ puzzle: P }), near); + st = await run(() => window.__game.set(80, 1)); // 1 duplicates within row/col/box -> invalid full grid + assert(st.grid.every(v => v >= 1 && v <= 9), 'grid is full'); + assert(st.solved === refSolved(st.grid) && st.solved === false, 'a full but invalid grid must be solved=false'); + assert(st.conflicts.length > 0, 'invalid full grid must report conflicts'); + }], + + ['T5 render-reflection: DOM .given count == givens; .conflict count == conflicts length', async () => { + await run((P) => window.__game.init({ puzzle: P }), PUZZLE); + // introduce a conflict so .conflict is non-empty + const st = await run(() => window.__game.set(2, 5)); + const dom = await run(() => ({ + cells: document.querySelectorAll('#board .cell').length, + given: document.querySelectorAll('#board .cell.given').length, + conflict: document.querySelectorAll('#board .cell.conflict').length, + })); + const givensCount = st.givens.filter(Boolean).length; + assert(dom.cells === 81, 'DOM must render 81 cells, got ' + dom.cells); + assert(dom.given === givensCount, `DOM .given count ${dom.given} must equal givens ${givensCount}`); + assert(dom.conflict === st.conflicts.length, `DOM .conflict count ${dom.conflict} must equal conflicts length ${st.conflicts.length}`); + await require('./assert_visible.js')(page,'#board .cell'); + await page.screenshot({path:'/logs/verifier/sudoku-conflict.png',fullPage:true}); + await require('./validate_render_mirror.js')(page,115); + await run(() => window.__game.set(2,0)); + await require('./validate_render_mirror.js')(page,115); + await page.screenshot({path:'/logs/verifier/sudoku-cleared.png',fullPage:true}); + }], + ]; + + let passed = 0; + for (const [name, fn] of tiers) { + try { await fn(); if(name.startsWith('T5'))await require('./validate_render_mirror.js')(page,115); passed++; console.log('PASS ' + name); } + catch (e) { console.log('FAIL ' + name + ': ' + (e && e.message || e)); } + } + console.log('TIERS ' + passed + '/' + tiers.length); + console.log('SCORE=' + (passed / tiers.length).toFixed(3)); + await browser.close(); +})().catch(e => { console.log('FATAL ' + (e && e.stack || e)); console.log('SCORE=0'); }); diff --git a/task_066/admission.json b/task_066/admission.json new file mode 100644 index 0000000000000000000000000000000000000000..58b19247a916d67077c6d38e91309941cfa26b5f --- /dev/null +++ b/task_066/admission.json @@ -0,0 +1,14 @@ +{ + "task": "task_003", + "teacher_model": "gpt-5.5", + "teacher_reasoning_effort": "high", + "evaluation_model": "gpt-5.6-sol", + "evaluation_reasoning_effort": "medium", + "round_rewards": [ + "1", + "1" + ], + "admission_rule": "at least one of two rounds passes", + "admitted": true, + "destination_collision": false +} diff --git a/task_066/audit.json b/task_066/audit.json new file mode 100644 index 0000000000000000000000000000000000000000..22114b93a2adaad2e8f94a4ce1cdda1092d7a677 --- /dev/null +++ b/task_066/audit.json @@ -0,0 +1,88 @@ +{ + "admitted_base_request": "Terragrunt supports `--auth-provider-cmd` so a command can provide environment variables before Terragrunt parses and runs units. That command must be evaluated in the Terragrunt unit context that needs credentials, not in generated Terraform working directories.\n\nFix Terragrunt so dependency output retrieval keeps the credentials that were already obtained while parsing the dependency unit. When Terragrunt later uses a bare Terraform command to read that dependency's outputs from an already-initialized working directory or from generated remote-state backend files, it must not execute `--auth-provider-cmd` again from `.terragrunt-cache` or another generated temporary backend directory.\n\nThe corrected behavior must satisfy these requirements:\n\n- `terragrunt run --all apply --non-interactive --auth-provider-cmd diff --git a/task_078/environment/code/web/src/main.jsx b/task_078/environment/code/web/src/main.jsx new file mode 100644 index 0000000000000000000000000000000000000000..6b289cd34435a9db1ad4ead1b1577b8dd82eab99 --- /dev/null +++ b/task_078/environment/code/web/src/main.jsx @@ -0,0 +1,7 @@ +import React,{useEffect,useState} from 'react';import{createRoot}from'react-dom/client';import{marked}from'marked';import'./style.css'; +const api=(p,o)=>fetch(p,{headers:{'Content-Type':'application/json'},...o}).then(async r=>{let x=await r.json().catch(()=>({}));if(!r.ok)throw Error(x.error||'request failed');return x}); +function Modal({item,onClose}){if(!item)return null;return

      {item.title}

      } +function Header({onAnnouncements}){const[open,setOpen]=useState(false);return
      Campus
      {open&&
      账号设置
      }
      } +function Dashboard(){const[items,setItems]=useState([]);const[modal,setModal]=useState(null);const auth=new URLSearchParams(location.search).get('auth')==='1';useEffect(()=>{api('/dashboard?auth='+(auth?'1':'0')).then(x=>{setItems(x.announcements);let urgent=x.announcements.find(a=>a.force_modal);if(urgent)setModal(urgent)});},[]);return <>
      setModal(items[0]||null)}/>

      Dashboard

      公告

      {items.length?
        {items.map(x=>
      • {x.title}{x.important&&重要}
      • )}
      :

      暂无公告

      }
      setModal(null)}/>} +function Admin(){const[form,setForm]=useState({title:'',content:'',visibility:'guest',published:true,pinned:false,important:false});const[msg,setMsg]=useState('');const set=(k,v)=>setForm({...form,[k]:v});async function submit(e){e.preventDefault();try{await api('/admin/announcements',{method:'POST',body:JSON.stringify(form)});setMsg('公告已创建');setForm({...form,title:'',content:''})}catch(e){setMsg(e.message)}}return <>
      {}}/>

      公告管理