diff --git a/LICENSES/README.txt b/LICENSES/README.txt deleted file mode 100644 index e0e8b4e789e20c521a4db63ca7955660751a9724..0000000000000000000000000000000000000000 --- a/LICENSES/README.txt +++ /dev/null @@ -1 +0,0 @@ -Terminal Desk declares Apache-2.0. The standard license text was added by this distribution; see components/dnakhla/LICENSE and NOTICE for attribution. diff --git a/MANIFEST.json b/MANIFEST.json index 94d90b551da0804760aaa45bd999d04253946fc4..40c4dd5667912225fdc57dbc1f10758dcf2d53a8 100644 --- a/MANIFEST.json +++ b/MANIFEST.json @@ -1,284 +1,196 @@ { "files": { - "LICENSES/README.txt": { - "bytes": 152, - "sha256": "73b6e48016e027d623e5b6e03c4a6eae26ea366447f10cc09d6a7f06bfef8913" - }, "README.md": { - "bytes": 791, - "sha256": "1e23d241e1da2922af95a043de8cea2d71fb5a67c95da8780c5e406223d22d13" + "bytes": 966, + "sha256": "bd0d465f995e6e88f99a624901bbf6577b31c7230a4ff959ca48516be0339af7" }, "SOURCE_LOCK.json": { - "bytes": 322, - "sha256": "77d0d1993cb7e5b2e68e90850e0a4e7ce89a9236e175204fb86b6c7df43f07a3" + "bytes": 328, + "sha256": "df3acef0a949edac8c6ec87a15e4d7c5a87534a83d49186549699a59bdf22f98" }, - "components/dnakhla/.dockerignore": { - "bytes": 49, - "sha256": "c04a2771c0665225047882b2da49d452e20d7cc9bc0ea024a48f1cd31411c504" + "components/skillsdesk/.dockerignore": { + "bytes": 29, + "sha256": "60c9bdd905fcf45ac485c680d32e9773962cf061b6f041dcddd033911558a672" }, - "components/dnakhla/Dockerfile": { - "bytes": 409, - "sha256": "a2464ca6190e49c967ccb0b521c8190dba35d94b9b2208e31562161f20f535b8" + "components/skillsdesk/ADAPTER_NOTICE": { + "bytes": 167, + "sha256": "843b71a3a9f9de899cbb9d260d55c9bd082f3df2b7771a1c31100ce5767a0a53" }, - "components/dnakhla/LICENSE": { + "components/skillsdesk/Dockerfile": { + "bytes": 1010, + "sha256": "4f047d60bc07987131be2c9cf0662c6e6feef91125adda81eda04d4b88882f6b" + }, + "components/skillsdesk/LICENSE": { "bytes": 11358, "sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30" }, - "components/dnakhla/NOTICE": { - "bytes": 351, - "sha256": "a3e807759b2b290d9c6af290af392f2ac87d7951a99b13fd62ee5cb431c86c68" + "components/skillsdesk/NOTICE": { + "bytes": 676, + "sha256": "dca813e02ab76d4bc5afdcd2a2de3480d3fc0a7a710edea24c395adf23a99883" + }, + "components/skillsdesk/README.md": { + "bytes": 303, + "sha256": "11775067d2cfb4c254084dd741f0b13a1a5058081c171712bdb9923d430a9cd4" }, - "components/dnakhla/README.md": { - "bytes": 268, - "sha256": "e868fbee82b3288b177de089ff6d0e4acab807772d422828c3e81d4580fa350e" + "components/skillsdesk/SOURCE_MANIFEST.json": { + "bytes": 3982, + "sha256": "789ef47ecb391dfe876f65207ba8f477b064c1d9cded1becaf177ae7112a3d99" }, - "components/dnakhla/SOURCE_MANIFEST.json": { - "bytes": 6263, - "sha256": "2fc003f012c04e9897d8a629e9b9d6b937154f0646f083ca1cc7493445892d74" + "components/skillsdesk/UPSTREAM_DOCKERFILE": { + "bytes": 1899, + "sha256": "2c07033febd78777deeff04350ae6887c9bb170b152d38c26cf148efa1b75d1e" }, - "components/dnakhla/runtime/common/__init__.py": { + "components/skillsdesk/UPSTREAM_TRAINING_TASKS.txt": { + "bytes": 666, + "sha256": "90e6e08d4269b5bb8308b5f2f05c61aa0cb9b71643b6abe6e47b34795828dd1e" + }, + "components/skillsdesk/runtime/common/__init__.py": { "bytes": 1, "sha256": "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b" }, - "components/dnakhla/runtime/common/contracts.py": { + "components/skillsdesk/runtime/common/contracts.py": { "bytes": 1015, "sha256": "b1e1429208e84aefc2422ee1d2400ad793c43cd5c0e8db213a3b669fe0947ce1" }, - "components/dnakhla/runtime/common/models.py": { + "components/skillsdesk/runtime/common/models.py": { "bytes": 1941, "sha256": "6a1ac8e55af6168d3fdd6b17c700a15cf0546b6154773aa3c59c97d6bffa2ffd" }, - "components/dnakhla/runtime/dnakhla_compat/__init__.py": { - "bytes": 80, - "sha256": "adb5e5e6b8d1c5f4d2ff5bbfd4b66038c3d52e4ae50b0d3430c56a196d5ae5c3" + "components/skillsdesk/runtime/skillsdesk_compat/__init__.py": { + "bytes": 0, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" }, - "components/dnakhla/runtime/dnakhla_compat/environment.py": { - "bytes": 6952, - "sha256": "eaa4d0c0f293f3d53630eda1ad71921a8c1308b1ae375be3041bd3d0afc41369" + "components/skillsdesk/runtime/skillsdesk_compat/environment.py": { + "bytes": 8142, + "sha256": "22a0011808344bdeeb635082afbacac2810bdf14e617ac72011e211dfa14c176" }, - "components/dnakhla/runtime/dnakhla_compat/server.py": { - "bytes": 460, - "sha256": "d64b7539b8cc9f5dcc170dcd0c4c48e6673da923ce0f22b754c7859770032bd8" + "components/skillsdesk/runtime/skillsdesk_compat/server.py": { + "bytes": 457, + "sha256": "634fd3bd58cb4ade2c5d959ae7fb09dfb24b102830170c00a140a3ff949e590c" }, - "components/dnakhla/upstream/openenv.yaml": { - "bytes": 626, - "sha256": "8c68fdfde651ec70155ec1a8d4b15f5c14cdd1f9d98197fc5037b49d6dc74524" + "components/skillsdesk/upstream/openenv.yaml": { + "bytes": 403, + "sha256": "88e8863954ec9a9d34d07cdde0d5d4688f1fc85a2c595f13c7b9d4d10be6218e" }, - "components/dnakhla/upstream/terminal_desk/__init__.py": { + "components/skillsdesk/upstream/terminal_desk/__init__.py": { "bytes": 0, "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" }, - "components/dnakhla/upstream/terminal_desk/core/__init__.py": { + "components/skillsdesk/upstream/terminal_desk/core/__init__.py": { "bytes": 0, "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" }, - "components/dnakhla/upstream/terminal_desk/core/grading.py": { - "bytes": 16512, - "sha256": "8606129c5aa3f99cc540a7c8269b65e9bb6c42e81bca36085c16963a0cccd2bd" - }, - "components/dnakhla/upstream/terminal_desk/core/shell.py": { - "bytes": 5014, - "sha256": "59b4b07b0d59e01792c8dbbf7877555e2da2346ddf5d2c17df3bbd4e17cb847f" + "components/skillsdesk/upstream/terminal_desk/core/grading.py": { + "bytes": 10754, + "sha256": "d61652f92fc3691f55e71b76c9ef17ccabb4502ff7038f7626b69f52918907c9" }, - "components/dnakhla/upstream/terminal_desk/families/__init__.py": { - "bytes": 966, - "sha256": "2ca3d4eda1fb04a84a236fbb43b71d13d46ea68109f545e036842211be3e3958" - }, - "components/dnakhla/upstream/terminal_desk/families/base.py": { - "bytes": 2632, - "sha256": "d76cab459096d3748d2c4198753853d85418de61f64436cf4772b89345fdcf17" - }, - "components/dnakhla/upstream/terminal_desk/families/finance.py": { - "bytes": 9887, - "sha256": "312a26e2d48ac10a07716384d3059a697f75f16e5b37fcabb8c07fcac3397f6f" - }, - "components/dnakhla/upstream/terminal_desk/families/finance3.py": { - "bytes": 23433, - "sha256": "a4839540c7a54198ea8e480248428e9ca65bdaf45adea5ae9f81cad71cbb1311" + "components/skillsdesk/upstream/terminal_desk/core/shell.py": { + "bytes": 4743, + "sha256": "e6af14ad4263f3067f47dc841f28fc6d24de64c8400df91facce1fdd71dced5d" }, - "components/dnakhla/upstream/terminal_desk/families/industrial.py": { - "bytes": 8865, - "sha256": "9140985ca44b1bcfc78b853f44496b7a9b77288284675f3656898de5be70d6aa" + "components/skillsdesk/upstream/terminal_desk/families/__init__.py": { + "bytes": 2614, + "sha256": "3d04bdea30395f1e8fa03d804a5728777633bf319f4e00575ef047f2011fa411" }, - "components/dnakhla/upstream/terminal_desk/families/industrial3.py": { - "bytes": 23945, - "sha256": "48e914996b67accb09350a6714a5cea4a6191c0a05ac12a8f3045309f961c49c" + "components/skillsdesk/upstream/terminal_desk/families/base.py": { + "bytes": 1915, + "sha256": "a0ef4dec6a2932ead3331d0cea6e5bb3b91fa91075508560aa9cf08495b0ad6f" }, - "components/dnakhla/upstream/terminal_desk/families/mathematics.py": { - "bytes": 6946, - "sha256": "552855819cbe4983529b864279c915bc56f8d68d850a3f221d84864066c0e2a5" + "components/skillsdesk/upstream/terminal_desk/families/compute.py": { + "bytes": 10755, + "sha256": "60c1e5c80f42479d79c86e222c3a101182955822b5b555b25cf0cff40d7bc7c3" }, - "components/dnakhla/upstream/terminal_desk/families/mathematics3.py": { - "bytes": 24030, - "sha256": "9dc54710cd826aadbe5de55d9093959e38c59dc59ae080e40d379cc4db1987c1" + "components/skillsdesk/upstream/terminal_desk/families/compute2.py": { + "bytes": 12743, + "sha256": "91cdb191a4af146bc8901e585f213d7377584ea6c493c60839a4aeddd7e63d33" }, - "components/dnakhla/upstream/terminal_desk/families/media.py": { - "bytes": 7444, - "sha256": "52523502e6c679e34bd2dbeb46c3f539ba53ae2d4e1033adafca7ce859bc4de8" + "components/skillsdesk/upstream/terminal_desk/families/constraints.py": { + "bytes": 9807, + "sha256": "25494ac58d4fa7196b5e702dfc9cc55e9635dbaa1603de160a80d39fb09d3ea0" }, - "components/dnakhla/upstream/terminal_desk/families/media3.py": { - "bytes": 27612, - "sha256": "9c91cfbde8ad60da034c15ba3418e21ae5891a12ce3932ecaf8035fcd6eef4bd" + "components/skillsdesk/upstream/terminal_desk/families/constraints2.py": { + "bytes": 14665, + "sha256": "411991bca80cbbdfb08eacc5192a07ba45442e41a3e600780b2efdac1b072cc4" }, - "components/dnakhla/upstream/terminal_desk/families/office.py": { - "bytes": 10356, - "sha256": "11f76ce7d62e18b535278b487f798703fd6f2bef04dd7ffaefae2c95bcba1102" + "components/skillsdesk/upstream/terminal_desk/families/evidence.py": { + "bytes": 10896, + "sha256": "c2ff755246cc006d04f36acf9f8787efad0ca22a6e2c0c9b2dc14bb4d3fb7045" }, - "components/dnakhla/upstream/terminal_desk/families/office3.py": { - "bytes": 25496, - "sha256": "1926c4a6e600cabb4cd35fab9528b4e4d55ef4adc1623b7229ac356ef28c987b" + "components/skillsdesk/upstream/terminal_desk/families/evidence2.py": { + "bytes": 14514, + "sha256": "d32eedf32ee8e385bd123501b33c2d15c75a7604cc9a029e97d8dabf6de97e60" }, - "components/dnakhla/upstream/terminal_desk/families/science.py": { - "bytes": 10159, - "sha256": "836ab819a2231700a4bff2929a4579034c45a637992e883ddfbdb0c1f711446a" + "components/skillsdesk/upstream/terminal_desk/families/repair.py": { + "bytes": 17806, + "sha256": "a3392b6cf21d6cdb562862fb9f0999ec8a57a4116162e3b58d1c00f9fb19b781" }, - "components/dnakhla/upstream/terminal_desk/families/science3.py": { - "bytes": 23969, - "sha256": "59477a1f9d38dbe5607f6432b4f8538342eec93faeed09bb6c9cb1402980c9a1" + "components/skillsdesk/upstream/terminal_desk/families/repair2.py": { + "bytes": 20016, + "sha256": "1d22338235ffb0e25786a45ddb0c28be00081f89df1bee94052d57f6ac01ace6" }, - "components/dnakhla/upstream/terminal_desk/families/security.py": { - "bytes": 10341, - "sha256": "1228db896b6ce796ccf1f133e2f2ba9aaa9d54b745d5ffaf4b584a63a6aab2bd" + "components/skillsdesk/upstream/terminal_desk/families/transform.py": { + "bytes": 6815, + "sha256": "d478ea588230f6394fdad03fef1d377399086015f7a33d1f892e78c268808df1" }, - "components/dnakhla/upstream/terminal_desk/families/security3.py": { - "bytes": 27080, - "sha256": "6f5ec9c2dfe9aad81ba382d4f6ffdb7f64493d92cd7fe5d653134ef0dac107af" + "components/skillsdesk/upstream/terminal_desk/families/transform2.py": { + "bytes": 13415, + "sha256": "2c176531664ffcbfb998283b1b6cc145ddac976c7b2137b5535a2a9e1b422af2" }, - "components/dnakhla/upstream/terminal_desk/families/software.py": { - "bytes": 16430, - "sha256": "4bca03797d701fe33f567729baa9a4fb2cef59cf220d0b79a941cc3817f8ba3a" + "components/skillsdesk/upstream/terminal_desk/families/util.py": { + "bytes": 3899, + "sha256": "0e3b71ebcd82ccce47ea3bcbcc98efafb23b297f9831b2e37afd399d44eb5832" }, - "components/dnakhla/upstream/terminal_desk/families/software3.py": { - "bytes": 31784, - "sha256": "d526ae88ca53ef22dbc1e578055fc27ebb491c184474e662736b8be9523086a7" - }, - "components/dnakhla/upstream/terminal_desk/models.py": { + "components/skillsdesk/upstream/terminal_desk/models.py": { "bytes": 1750, "sha256": "f31264b0909878c6f2d4d18a270c7d92bc895052150c56e5ac3e6b38d4ceebb4" }, - "components/dnakhla/upstream/terminal_desk/oracles/__init__.py": { - "bytes": 1728, - "sha256": "04e4b102444b5db19507a46814820d78ad1e9782f963e5764f8f4adfe4d366a3" - }, - "components/dnakhla/upstream/terminal_desk/oracles/fin3_invoice_fraud.py": { - "bytes": 1162, - "sha256": "975ff8045d42b2f483924e368e304c451bca894ddb4ba593d9dd3aea1c505329" - }, - "components/dnakhla/upstream/terminal_desk/oracles/fin3_loan_schedule.py": { - "bytes": 1752, - "sha256": "b0a32266ec725f5a4f76d8b40a27fc52759f679d74e4dfe5c7885a1b19a36711" - }, - "components/dnakhla/upstream/terminal_desk/oracles/fin3_portfolio_value.py": { - "bytes": 1729, - "sha256": "152a3516b9ec6811121747ea875fc1a73cb768ba6a98e05c2bee91325e4f7247" - }, - "components/dnakhla/upstream/terminal_desk/oracles/ind3_service_due.py": { - "bytes": 1819, - "sha256": "47914a6e1a5bde126ce301bc11d4dc95b11cb0910ac0208a4c78596d7e65e30e" - }, - "components/dnakhla/upstream/terminal_desk/oracles/ind3_stl_mass.py": { - "bytes": 1562, - "sha256": "53e6adc26768256ce6665bda20c4b04ad87602e24eb31b074c25dc8fbbc00653" - }, - "components/dnakhla/upstream/terminal_desk/oracles/ind3_tank_balance.py": { - "bytes": 1573, - "sha256": "c1049fdb6b4f11f0b5e0194b41e84b525d5a340213c2c94f5f99ffd6c2b75a42" - }, - "components/dnakhla/upstream/terminal_desk/oracles/math3_count_items.py": { - "bytes": 1005, - "sha256": "0fd62812cd9ef1d5be6d6ae9fa2fa047eb6bb0a4508ccb5a5369373aefbf8dd3" - }, - "components/dnakhla/upstream/terminal_desk/oracles/math3_exam_slots.py": { - "bytes": 1770, - "sha256": "03908ec43159f4a66678f37fb0366389608eeeba41361758d966c96eea50dc3f" - }, - "components/dnakhla/upstream/terminal_desk/oracles/math3_route_plan.py": { - "bytes": 1686, - "sha256": "c2bb32b08a3705a4be56ff8c4e3af94d64441c9a7432f5dcec4dce0b378ee465" - }, - "components/dnakhla/upstream/terminal_desk/oracles/med3_silence_report.py": { - "bytes": 1602, - "sha256": "554e36455da66fd258e6ad2c39e80acbc3856237fee4608ce57b494f23c3d16d" - }, - "components/dnakhla/upstream/terminal_desk/oracles/med3_sprite_count.py": { - "bytes": 1517, - "sha256": "8f0a1169d6e5b10c4981b53a22e957c4befad44d95e5d250cf53734105a40256" - }, - "components/dnakhla/upstream/terminal_desk/oracles/med3_subtitle_retime.py": { - "bytes": 1494, - "sha256": "72f448ba58ac9ee6082692dec88ddb6f279ae69bdb99d39b30d1acce12c19bfe" - }, - "components/dnakhla/upstream/terminal_desk/oracles/off3_ar_recon.py": { - "bytes": 1454, - "sha256": "b5320a71696443f1b04c0c5e02e35d0baee67a175a912bff86e32df7c2acb357" - }, - "components/dnakhla/upstream/terminal_desk/oracles/off3_meeting_slot.py": { - "bytes": 1711, - "sha256": "6eef5e15337e5029c8e0b3353adee791ea9ebe73c6d79e47d84d6b7294cb5a38" - }, - "components/dnakhla/upstream/terminal_desk/oracles/off3_pdf_xlsx_diff.py": { - "bytes": 1301, - "sha256": "82b5c15f02a03615699429a2342dbad4b8985aab76d82fa8a8b96f7fbebc544f" - }, - "components/dnakhla/upstream/terminal_desk/oracles/sci3_kinetics_fit.py": { - "bytes": 1527, - "sha256": "1ebc19667bf1963c83a47bd4905e99e0c32c3ce249b63ae2d7b39fcffa1b1bb7" - }, - "components/dnakhla/upstream/terminal_desk/oracles/sci3_lightcurve_period.py": { - "bytes": 1540, - "sha256": "a983fb3c03ba15bc0591ab32ce41ddb99f2f38329e273f3f5da20f775d6bd8ab" - }, - "components/dnakhla/upstream/terminal_desk/oracles/sci3_stoich_batch.py": { - "bytes": 1747, - "sha256": "56a84763e746f034571dc50a71f3716f340e4f8d9dee823eb3c9b209f471f48a" - }, - "components/dnakhla/upstream/terminal_desk/oracles/sec3_auth_triage.py": { - "bytes": 1443, - "sha256": "c5fb5f697e8cfdb6008fcd59d6c3095a509d9a488dc28d7b99da4f4fe128b8a6" + "components/skillsdesk/upstream/terminal_desk/reserved/__init__.py": { + "bytes": 647, + "sha256": "012f259f4fd2aad8af71accaf7686f8e76235491d9ad200bfbec9f3641afa330" }, - "components/dnakhla/upstream/terminal_desk/oracles/sec3_exfil_flows.py": { - "bytes": 1425, - "sha256": "5a4cc8a38f0554be4b287e2592bd26553db2f3ee6b5c10339d641246a7a6af90" + "components/skillsdesk/upstream/terminal_desk/reserved/compute.py": { + "bytes": 12349, + "sha256": "e87cfd26e155b8c0a830cfd6809274c930ee45d31f2ac44398f35385b2dbe083" }, - "components/dnakhla/upstream/terminal_desk/oracles/sec3_fw_verdicts.py": { - "bytes": 1668, - "sha256": "b91c7389813445d55edbdaadec60aa4c5d0b6c5ead6fdfca5268e425f512820f" + "components/skillsdesk/upstream/terminal_desk/reserved/constraints.py": { + "bytes": 15358, + "sha256": "ca168704db89a1da64fd0262c44280e0461d2a58d4f9191a6c9747d19cb0bee0" }, - "components/dnakhla/upstream/terminal_desk/oracles/sw3_dep_lock.py": { - "bytes": 1715, - "sha256": "6b46601bc7e4bdc42c62242344aa431a34e7a6d1a8c7201e77315c66c6a4ae09" + "components/skillsdesk/upstream/terminal_desk/reserved/evidence.py": { + "bytes": 12524, + "sha256": "e3c5f779c29f730fd2844018150078640c17425bfe6ddb922103a661a86c5ee0" }, - "components/dnakhla/upstream/terminal_desk/oracles/sw3_fix_module.py": { - "bytes": 1831, - "sha256": "43eee7f24a02ca3f0d3b12db5a44c132a931fc8dba10f9c1d4028d7fa5775bf4" + "components/skillsdesk/upstream/terminal_desk/reserved/repair.py": { + "bytes": 16541, + "sha256": "121c2be70cd21ca16c254153eebbce895f2bb86c37aedcaaaa237662917e18e5" }, - "components/dnakhla/upstream/terminal_desk/oracles/sw3_rate_limit.py": { - "bytes": 1553, - "sha256": "4f1f187ae42f47faecc85d84e1f0341c848b03eb2bba1bf538927e2e62758314" + "components/skillsdesk/upstream/terminal_desk/reserved/transform.py": { + "bytes": 11909, + "sha256": "bd97f765a7e468bd2e4b4a6e1e959177df999a123d712c5c2b4f93e4359c99cf" }, - "components/dnakhla/upstream/terminal_desk/server/__init__.py": { + "components/skillsdesk/upstream/terminal_desk/server/__init__.py": { "bytes": 0, "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" }, - "components/dnakhla/upstream/terminal_desk/server/app.py": { + "components/skillsdesk/upstream/terminal_desk/server/app.py": { "bytes": 802, "sha256": "6bf7658ec8ad07dda230a01fd893091a9b87df18ebf6af25af6c35965ed01fd8" }, - "components/dnakhla/upstream/terminal_desk/server/environment.py": { - "bytes": 8350, - "sha256": "8e92f991e14098a0858490fe5beb43ca9b0ee2cfbddb36e73ecf987ba3922902" + "components/skillsdesk/upstream/terminal_desk/server/environment.py": { + "bytes": 6820, + "sha256": "82aa929676d76fe2f8d81a5122598986ac2950339dbfc4366de03a3604cd7319" }, "schema.json": { "bytes": 1911, "sha256": "10993deaaa8553929fa0b3b6bf3c1ad100baaaf9ff10ae8ed139a8ec4279a3c4" }, "tasks.jsonl": { - "bytes": 3402, - "sha256": "d86495b21e4322e5265bff6a2f920b7237278522f0a5c076bf279ba63d9d3d82" + "bytes": 17061, + "sha256": "2a3fe43c4b55a123f5a80f0c2d60c15f86d94470cd2a4fc86adbaec85c12054b" }, "validate_dataset.py": { - "bytes": 4483, - "sha256": "e62ac01d70ca2c5682089a0713a127a8bcccb5fdf9c5ca53e81ddd8b6f94aaba" + "bytes": 8206, + "sha256": "db3704682eefb03f47a6c951865e9fb2113851f8bdf0266f6c4f517961f2973b" } } } diff --git a/README.md b/README.md index 34f9c1fec24086faabd7258ca879216b8c718002..f36accc432c6ce086d46ca2e6f32d9a9199c7a70 100644 --- a/README.md +++ b/README.md @@ -11,10 +11,10 @@ configs: path: tasks.jsonl --- -Four original Terminal Desk tasks served by one OpenEnv image. +Twenty original Skills Desk tasks covering evidence matching, computation, data transformation, code repair and constrained planning. -The tasks cover exam scheduling, meeting availability, subtitle retiming and audio silence reports. Original generators, tools and graders are retained. Reset generates a fresh instance. Reward is one when all required artifact checks pass, otherwise zero. +Each task ID identifies a fixed original instance. Use the tools shown at reset and `op=finish` to grade the artifact. Reward is one when all original checks pass, otherwise zero. Code repair tasks also run hidden-input checks. -Use the tools shown at reset and `op=finish` to grade the output. Each episode requires a fresh sandbox. Task IDs and pinned source references are in `tasks.jsonl`. Licenses and provenance are retained in the component directory. +Run one episode per fresh sandbox, with one active session. Each episode allows 32 actions, 8192 completion tokens and 16384 context tokens; later observations count toward completion tokens. Commands have the original 20-second limit. -Run `python3 -B validate_dataset.py` to verify the file inventory. +Task IDs and pinned source references are in `tasks.jsonl`. Original licenses and attribution are in `components/skillsdesk/`. Run `python3 -B validate_dataset.py` to verify the file inventory. diff --git a/SHA256SUMS b/SHA256SUMS index ad701f6d88f9defa7a127d744f00439fa5dc39e7..a9e84d01c4ffab17e81bec6cbd73659b4b7e74cf 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -1,70 +1,48 @@ -73b6e48016e027d623e5b6e03c4a6eae26ea366447f10cc09d6a7f06bfef8913 LICENSES/README.txt -1e23d241e1da2922af95a043de8cea2d71fb5a67c95da8780c5e406223d22d13 README.md -77d0d1993cb7e5b2e68e90850e0a4e7ce89a9236e175204fb86b6c7df43f07a3 SOURCE_LOCK.json -c04a2771c0665225047882b2da49d452e20d7cc9bc0ea024a48f1cd31411c504 components/dnakhla/.dockerignore -a2464ca6190e49c967ccb0b521c8190dba35d94b9b2208e31562161f20f535b8 components/dnakhla/Dockerfile -cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 components/dnakhla/LICENSE -a3e807759b2b290d9c6af290af392f2ac87d7951a99b13fd62ee5cb431c86c68 components/dnakhla/NOTICE -e868fbee82b3288b177de089ff6d0e4acab807772d422828c3e81d4580fa350e components/dnakhla/README.md -2fc003f012c04e9897d8a629e9b9d6b937154f0646f083ca1cc7493445892d74 components/dnakhla/SOURCE_MANIFEST.json -01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b components/dnakhla/runtime/common/__init__.py -b1e1429208e84aefc2422ee1d2400ad793c43cd5c0e8db213a3b669fe0947ce1 components/dnakhla/runtime/common/contracts.py -6a1ac8e55af6168d3fdd6b17c700a15cf0546b6154773aa3c59c97d6bffa2ffd components/dnakhla/runtime/common/models.py -adb5e5e6b8d1c5f4d2ff5bbfd4b66038c3d52e4ae50b0d3430c56a196d5ae5c3 components/dnakhla/runtime/dnakhla_compat/__init__.py -eaa4d0c0f293f3d53630eda1ad71921a8c1308b1ae375be3041bd3d0afc41369 components/dnakhla/runtime/dnakhla_compat/environment.py -d64b7539b8cc9f5dcc170dcd0c4c48e6673da923ce0f22b754c7859770032bd8 components/dnakhla/runtime/dnakhla_compat/server.py -8c68fdfde651ec70155ec1a8d4b15f5c14cdd1f9d98197fc5037b49d6dc74524 components/dnakhla/upstream/openenv.yaml -e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 components/dnakhla/upstream/terminal_desk/__init__.py -e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 components/dnakhla/upstream/terminal_desk/core/__init__.py -8606129c5aa3f99cc540a7c8269b65e9bb6c42e81bca36085c16963a0cccd2bd components/dnakhla/upstream/terminal_desk/core/grading.py -59b4b07b0d59e01792c8dbbf7877555e2da2346ddf5d2c17df3bbd4e17cb847f components/dnakhla/upstream/terminal_desk/core/shell.py -2ca3d4eda1fb04a84a236fbb43b71d13d46ea68109f545e036842211be3e3958 components/dnakhla/upstream/terminal_desk/families/__init__.py -d76cab459096d3748d2c4198753853d85418de61f64436cf4772b89345fdcf17 components/dnakhla/upstream/terminal_desk/families/base.py -312a26e2d48ac10a07716384d3059a697f75f16e5b37fcabb8c07fcac3397f6f components/dnakhla/upstream/terminal_desk/families/finance.py -a4839540c7a54198ea8e480248428e9ca65bdaf45adea5ae9f81cad71cbb1311 components/dnakhla/upstream/terminal_desk/families/finance3.py -9140985ca44b1bcfc78b853f44496b7a9b77288284675f3656898de5be70d6aa components/dnakhla/upstream/terminal_desk/families/industrial.py -48e914996b67accb09350a6714a5cea4a6191c0a05ac12a8f3045309f961c49c components/dnakhla/upstream/terminal_desk/families/industrial3.py -552855819cbe4983529b864279c915bc56f8d68d850a3f221d84864066c0e2a5 components/dnakhla/upstream/terminal_desk/families/mathematics.py -9dc54710cd826aadbe5de55d9093959e38c59dc59ae080e40d379cc4db1987c1 components/dnakhla/upstream/terminal_desk/families/mathematics3.py -52523502e6c679e34bd2dbeb46c3f539ba53ae2d4e1033adafca7ce859bc4de8 components/dnakhla/upstream/terminal_desk/families/media.py -9c91cfbde8ad60da034c15ba3418e21ae5891a12ce3932ecaf8035fcd6eef4bd components/dnakhla/upstream/terminal_desk/families/media3.py -11f76ce7d62e18b535278b487f798703fd6f2bef04dd7ffaefae2c95bcba1102 components/dnakhla/upstream/terminal_desk/families/office.py -1926c4a6e600cabb4cd35fab9528b4e4d55ef4adc1623b7229ac356ef28c987b components/dnakhla/upstream/terminal_desk/families/office3.py -836ab819a2231700a4bff2929a4579034c45a637992e883ddfbdb0c1f711446a components/dnakhla/upstream/terminal_desk/families/science.py -59477a1f9d38dbe5607f6432b4f8538342eec93faeed09bb6c9cb1402980c9a1 components/dnakhla/upstream/terminal_desk/families/science3.py -1228db896b6ce796ccf1f133e2f2ba9aaa9d54b745d5ffaf4b584a63a6aab2bd components/dnakhla/upstream/terminal_desk/families/security.py -6f5ec9c2dfe9aad81ba382d4f6ffdb7f64493d92cd7fe5d653134ef0dac107af components/dnakhla/upstream/terminal_desk/families/security3.py -4bca03797d701fe33f567729baa9a4fb2cef59cf220d0b79a941cc3817f8ba3a components/dnakhla/upstream/terminal_desk/families/software.py -d526ae88ca53ef22dbc1e578055fc27ebb491c184474e662736b8be9523086a7 components/dnakhla/upstream/terminal_desk/families/software3.py -f31264b0909878c6f2d4d18a270c7d92bc895052150c56e5ac3e6b38d4ceebb4 components/dnakhla/upstream/terminal_desk/models.py -04e4b102444b5db19507a46814820d78ad1e9782f963e5764f8f4adfe4d366a3 components/dnakhla/upstream/terminal_desk/oracles/__init__.py -975ff8045d42b2f483924e368e304c451bca894ddb4ba593d9dd3aea1c505329 components/dnakhla/upstream/terminal_desk/oracles/fin3_invoice_fraud.py -b0a32266ec725f5a4f76d8b40a27fc52759f679d74e4dfe5c7885a1b19a36711 components/dnakhla/upstream/terminal_desk/oracles/fin3_loan_schedule.py -152a3516b9ec6811121747ea875fc1a73cb768ba6a98e05c2bee91325e4f7247 components/dnakhla/upstream/terminal_desk/oracles/fin3_portfolio_value.py -47914a6e1a5bde126ce301bc11d4dc95b11cb0910ac0208a4c78596d7e65e30e components/dnakhla/upstream/terminal_desk/oracles/ind3_service_due.py -53e6adc26768256ce6665bda20c4b04ad87602e24eb31b074c25dc8fbbc00653 components/dnakhla/upstream/terminal_desk/oracles/ind3_stl_mass.py -c1049fdb6b4f11f0b5e0194b41e84b525d5a340213c2c94f5f99ffd6c2b75a42 components/dnakhla/upstream/terminal_desk/oracles/ind3_tank_balance.py -0fd62812cd9ef1d5be6d6ae9fa2fa047eb6bb0a4508ccb5a5369373aefbf8dd3 components/dnakhla/upstream/terminal_desk/oracles/math3_count_items.py -03908ec43159f4a66678f37fb0366389608eeeba41361758d966c96eea50dc3f components/dnakhla/upstream/terminal_desk/oracles/math3_exam_slots.py -c2bb32b08a3705a4be56ff8c4e3af94d64441c9a7432f5dcec4dce0b378ee465 components/dnakhla/upstream/terminal_desk/oracles/math3_route_plan.py -554e36455da66fd258e6ad2c39e80acbc3856237fee4608ce57b494f23c3d16d components/dnakhla/upstream/terminal_desk/oracles/med3_silence_report.py -8f0a1169d6e5b10c4981b53a22e957c4befad44d95e5d250cf53734105a40256 components/dnakhla/upstream/terminal_desk/oracles/med3_sprite_count.py -72f448ba58ac9ee6082692dec88ddb6f279ae69bdb99d39b30d1acce12c19bfe components/dnakhla/upstream/terminal_desk/oracles/med3_subtitle_retime.py -b5320a71696443f1b04c0c5e02e35d0baee67a175a912bff86e32df7c2acb357 components/dnakhla/upstream/terminal_desk/oracles/off3_ar_recon.py -6eef5e15337e5029c8e0b3353adee791ea9ebe73c6d79e47d84d6b7294cb5a38 components/dnakhla/upstream/terminal_desk/oracles/off3_meeting_slot.py -82b5c15f02a03615699429a2342dbad4b8985aab76d82fa8a8b96f7fbebc544f components/dnakhla/upstream/terminal_desk/oracles/off3_pdf_xlsx_diff.py -1ebc19667bf1963c83a47bd4905e99e0c32c3ce249b63ae2d7b39fcffa1b1bb7 components/dnakhla/upstream/terminal_desk/oracles/sci3_kinetics_fit.py -a983fb3c03ba15bc0591ab32ce41ddb99f2f38329e273f3f5da20f775d6bd8ab components/dnakhla/upstream/terminal_desk/oracles/sci3_lightcurve_period.py -56a84763e746f034571dc50a71f3716f340e4f8d9dee823eb3c9b209f471f48a components/dnakhla/upstream/terminal_desk/oracles/sci3_stoich_batch.py -c5fb5f697e8cfdb6008fcd59d6c3095a509d9a488dc28d7b99da4f4fe128b8a6 components/dnakhla/upstream/terminal_desk/oracles/sec3_auth_triage.py -5a4cc8a38f0554be4b287e2592bd26553db2f3ee6b5c10339d641246a7a6af90 components/dnakhla/upstream/terminal_desk/oracles/sec3_exfil_flows.py -b91c7389813445d55edbdaadec60aa4c5d0b6c5ead6fdfca5268e425f512820f components/dnakhla/upstream/terminal_desk/oracles/sec3_fw_verdicts.py -6b46601bc7e4bdc42c62242344aa431a34e7a6d1a8c7201e77315c66c6a4ae09 components/dnakhla/upstream/terminal_desk/oracles/sw3_dep_lock.py -43eee7f24a02ca3f0d3b12db5a44c132a931fc8dba10f9c1d4028d7fa5775bf4 components/dnakhla/upstream/terminal_desk/oracles/sw3_fix_module.py -4f1f187ae42f47faecc85d84e1f0341c848b03eb2bba1bf538927e2e62758314 components/dnakhla/upstream/terminal_desk/oracles/sw3_rate_limit.py -e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 components/dnakhla/upstream/terminal_desk/server/__init__.py -6bf7658ec8ad07dda230a01fd893091a9b87df18ebf6af25af6c35965ed01fd8 components/dnakhla/upstream/terminal_desk/server/app.py -8e92f991e14098a0858490fe5beb43ca9b0ee2cfbddb36e73ecf987ba3922902 components/dnakhla/upstream/terminal_desk/server/environment.py +bd0d465f995e6e88f99a624901bbf6577b31c7230a4ff959ca48516be0339af7 README.md +df3acef0a949edac8c6ec87a15e4d7c5a87534a83d49186549699a59bdf22f98 SOURCE_LOCK.json +60c9bdd905fcf45ac485c680d32e9773962cf061b6f041dcddd033911558a672 components/skillsdesk/.dockerignore +843b71a3a9f9de899cbb9d260d55c9bd082f3df2b7771a1c31100ce5767a0a53 components/skillsdesk/ADAPTER_NOTICE +4f047d60bc07987131be2c9cf0662c6e6feef91125adda81eda04d4b88882f6b components/skillsdesk/Dockerfile +cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 components/skillsdesk/LICENSE +dca813e02ab76d4bc5afdcd2a2de3480d3fc0a7a710edea24c395adf23a99883 components/skillsdesk/NOTICE +11775067d2cfb4c254084dd741f0b13a1a5058081c171712bdb9923d430a9cd4 components/skillsdesk/README.md +789ef47ecb391dfe876f65207ba8f477b064c1d9cded1becaf177ae7112a3d99 components/skillsdesk/SOURCE_MANIFEST.json +2c07033febd78777deeff04350ae6887c9bb170b152d38c26cf148efa1b75d1e components/skillsdesk/UPSTREAM_DOCKERFILE +90e6e08d4269b5bb8308b5f2f05c61aa0cb9b71643b6abe6e47b34795828dd1e components/skillsdesk/UPSTREAM_TRAINING_TASKS.txt +01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b components/skillsdesk/runtime/common/__init__.py +b1e1429208e84aefc2422ee1d2400ad793c43cd5c0e8db213a3b669fe0947ce1 components/skillsdesk/runtime/common/contracts.py +6a1ac8e55af6168d3fdd6b17c700a15cf0546b6154773aa3c59c97d6bffa2ffd components/skillsdesk/runtime/common/models.py +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 components/skillsdesk/runtime/skillsdesk_compat/__init__.py +22a0011808344bdeeb635082afbacac2810bdf14e617ac72011e211dfa14c176 components/skillsdesk/runtime/skillsdesk_compat/environment.py +634fd3bd58cb4ade2c5d959ae7fb09dfb24b102830170c00a140a3ff949e590c components/skillsdesk/runtime/skillsdesk_compat/server.py +88e8863954ec9a9d34d07cdde0d5d4688f1fc85a2c595f13c7b9d4d10be6218e components/skillsdesk/upstream/openenv.yaml +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 components/skillsdesk/upstream/terminal_desk/__init__.py +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 components/skillsdesk/upstream/terminal_desk/core/__init__.py +d61652f92fc3691f55e71b76c9ef17ccabb4502ff7038f7626b69f52918907c9 components/skillsdesk/upstream/terminal_desk/core/grading.py +e6af14ad4263f3067f47dc841f28fc6d24de64c8400df91facce1fdd71dced5d components/skillsdesk/upstream/terminal_desk/core/shell.py +3d04bdea30395f1e8fa03d804a5728777633bf319f4e00575ef047f2011fa411 components/skillsdesk/upstream/terminal_desk/families/__init__.py +a0ef4dec6a2932ead3331d0cea6e5bb3b91fa91075508560aa9cf08495b0ad6f components/skillsdesk/upstream/terminal_desk/families/base.py +60c1e5c80f42479d79c86e222c3a101182955822b5b555b25cf0cff40d7bc7c3 components/skillsdesk/upstream/terminal_desk/families/compute.py +91cdb191a4af146bc8901e585f213d7377584ea6c493c60839a4aeddd7e63d33 components/skillsdesk/upstream/terminal_desk/families/compute2.py +25494ac58d4fa7196b5e702dfc9cc55e9635dbaa1603de160a80d39fb09d3ea0 components/skillsdesk/upstream/terminal_desk/families/constraints.py +411991bca80cbbdfb08eacc5192a07ba45442e41a3e600780b2efdac1b072cc4 components/skillsdesk/upstream/terminal_desk/families/constraints2.py +c2ff755246cc006d04f36acf9f8787efad0ca22a6e2c0c9b2dc14bb4d3fb7045 components/skillsdesk/upstream/terminal_desk/families/evidence.py +d32eedf32ee8e385bd123501b33c2d15c75a7604cc9a029e97d8dabf6de97e60 components/skillsdesk/upstream/terminal_desk/families/evidence2.py +a3392b6cf21d6cdb562862fb9f0999ec8a57a4116162e3b58d1c00f9fb19b781 components/skillsdesk/upstream/terminal_desk/families/repair.py +1d22338235ffb0e25786a45ddb0c28be00081f89df1bee94052d57f6ac01ace6 components/skillsdesk/upstream/terminal_desk/families/repair2.py +d478ea588230f6394fdad03fef1d377399086015f7a33d1f892e78c268808df1 components/skillsdesk/upstream/terminal_desk/families/transform.py +2c176531664ffcbfb998283b1b6cc145ddac976c7b2137b5535a2a9e1b422af2 components/skillsdesk/upstream/terminal_desk/families/transform2.py +0e3b71ebcd82ccce47ea3bcbcc98efafb23b297f9831b2e37afd399d44eb5832 components/skillsdesk/upstream/terminal_desk/families/util.py +f31264b0909878c6f2d4d18a270c7d92bc895052150c56e5ac3e6b38d4ceebb4 components/skillsdesk/upstream/terminal_desk/models.py +012f259f4fd2aad8af71accaf7686f8e76235491d9ad200bfbec9f3641afa330 components/skillsdesk/upstream/terminal_desk/reserved/__init__.py +e87cfd26e155b8c0a830cfd6809274c930ee45d31f2ac44398f35385b2dbe083 components/skillsdesk/upstream/terminal_desk/reserved/compute.py +ca168704db89a1da64fd0262c44280e0461d2a58d4f9191a6c9747d19cb0bee0 components/skillsdesk/upstream/terminal_desk/reserved/constraints.py +e3c5f779c29f730fd2844018150078640c17425bfe6ddb922103a661a86c5ee0 components/skillsdesk/upstream/terminal_desk/reserved/evidence.py +121c2be70cd21ca16c254153eebbce895f2bb86c37aedcaaaa237662917e18e5 components/skillsdesk/upstream/terminal_desk/reserved/repair.py +bd97f765a7e468bd2e4b4a6e1e959177df999a123d712c5c2b4f93e4359c99cf components/skillsdesk/upstream/terminal_desk/reserved/transform.py +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 components/skillsdesk/upstream/terminal_desk/server/__init__.py +6bf7658ec8ad07dda230a01fd893091a9b87df18ebf6af25af6c35965ed01fd8 components/skillsdesk/upstream/terminal_desk/server/app.py +82aa929676d76fe2f8d81a5122598986ac2950339dbfc4366de03a3604cd7319 components/skillsdesk/upstream/terminal_desk/server/environment.py 10993deaaa8553929fa0b3b6bf3c1ad100baaaf9ff10ae8ed139a8ec4279a3c4 schema.json -d86495b21e4322e5265bff6a2f920b7237278522f0a5c076bf279ba63d9d3d82 tasks.jsonl -e62ac01d70ca2c5682089a0713a127a8bcccb5fdf9c5ca53e81ddd8b6f94aaba validate_dataset.py +2a3fe43c4b55a123f5a80f0c2d60c15f86d94470cd2a4fc86adbaec85c12054b tasks.jsonl +db3704682eefb03f47a6c951865e9fb2113851f8bdf0266f6c4f517961f2973b validate_dataset.py diff --git a/SOURCE_LOCK.json b/SOURCE_LOCK.json index 6e27aacbf063e3c2425e0b0cde453ab6aa20d2d2..f9da22f89b66a4f4ea7c8a46e89a6f86f908def1 100644 --- a/SOURCE_LOCK.json +++ b/SOURCE_LOCK.json @@ -1,11 +1,11 @@ { "components": { - "dnakhla": { - "repository": "dnakhla/terminal-desk", - "revision": "08fab0beb50b665b42f0ac73840f03140f4ad1c9", + "skillsdesk": { + "repository": "Syndicate604/skills-desk", + "revision": "a785ccdc9784ed863d0ffecec826d72176c0a785", "license": "Apache-2.0", "source_file": "SOURCE_MANIFEST.json", - "record_sha256": "2fc003f012c04e9897d8a629e9b9d6b937154f0646f083ca1cc7493445892d74" + "record_sha256": "789ef47ecb391dfe876f65207ba8f477b064c1d9cded1becaf177ae7112a3d99" } } } diff --git a/components/dnakhla/.dockerignore b/components/dnakhla/.dockerignore deleted file mode 100644 index fffd596308c730148310386c92d13f850328dfe4..0000000000000000000000000000000000000000 --- a/components/dnakhla/.dockerignore +++ /dev/null @@ -1,5 +0,0 @@ -upstream -README.md -LICENSE -NOTICE -**/__pycache__ diff --git a/components/dnakhla/Dockerfile b/components/dnakhla/Dockerfile deleted file mode 100644 index a9a6f99b09766961e887b2eea0faaf5fc3e9023a..0000000000000000000000000000000000000000 --- a/components/dnakhla/Dockerfile +++ /dev/null @@ -1,8 +0,0 @@ -FROM ghcr.io/dnakhla/terminal-desk@sha256:de59e5f70a416641a5cc39cd3510a0a91c57808841448e44dc7f4eaf10376c5e -USER root -COPY runtime /opt/dnakhla_compat -COPY SOURCE_MANIFEST.json /opt/dnakhla_compat/SOURCE_MANIFEST.json -RUN chmod -R go-rwx /opt/dnakhla_compat -ENV PYTHONPATH=/opt/dnakhla_compat:/opt/terminal_desk OPENENV_MODE=production -WORKDIR /opt/dnakhla_compat -CMD ["python", "-m", "dnakhla_compat.server"] diff --git a/components/dnakhla/NOTICE b/components/dnakhla/NOTICE deleted file mode 100644 index 03cdb6656549b3454ca28755abe62ea1d5eba101..0000000000000000000000000000000000000000 --- a/components/dnakhla/NOTICE +++ /dev/null @@ -1,4 +0,0 @@ -Terminal Desk by dnakhla -Source: https://huggingface.co/datasets/dnakhla/terminal-desk/tree/08fab0beb50b665b42f0ac73840f03140f4ad1c9 -License declaration: Apache-2.0. The accompanying standard license text was added by this distribution. -This distribution adds a shared Arena interface and a four-task registry. Original task source remains unchanged. diff --git a/components/dnakhla/README.md b/components/dnakhla/README.md deleted file mode 100644 index 5a1c5ba6b0f0f8301962a9a63d7d07b55325abdf..0000000000000000000000000000000000000000 --- a/components/dnakhla/README.md +++ /dev/null @@ -1,5 +0,0 @@ -Original Terminal Desk tasks by dnakhla. The shared adapter preserves original tools, random resets and artifact grading. Registered IDs are listed in SOURCE_MANIFEST.json. - -Run: `python -m dnakhla_compat.server` - -Run one episode per sandbox, with one active session. diff --git a/components/dnakhla/SOURCE_MANIFEST.json b/components/dnakhla/SOURCE_MANIFEST.json deleted file mode 100644 index 9a0313d334d54f2d3167fdcf95bf36014a036ffd..0000000000000000000000000000000000000000 --- a/components/dnakhla/SOURCE_MANIFEST.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "base_image": "ghcr.io/dnakhla/terminal-desk@sha256:de59e5f70a416641a5cc39cd3510a0a91c57808841448e44dc7f4eaf10376c5e", - "dataset": "dnakhla/terminal-desk", - "revision": "08fab0beb50b665b42f0ac73840f03140f4ad1c9", - "license_declaration": "Apache-2.0", - "original_files": { - "openenv.yaml": "8c68fdfde651ec70155ec1a8d4b15f5c14cdd1f9d98197fc5037b49d6dc74524", - "terminal_desk/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "terminal_desk/core/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "terminal_desk/core/grading.py": "8606129c5aa3f99cc540a7c8269b65e9bb6c42e81bca36085c16963a0cccd2bd", - "terminal_desk/core/shell.py": "59b4b07b0d59e01792c8dbbf7877555e2da2346ddf5d2c17df3bbd4e17cb847f", - "terminal_desk/families/__init__.py": "2ca3d4eda1fb04a84a236fbb43b71d13d46ea68109f545e036842211be3e3958", - "terminal_desk/families/base.py": "d76cab459096d3748d2c4198753853d85418de61f64436cf4772b89345fdcf17", - "terminal_desk/families/finance.py": "312a26e2d48ac10a07716384d3059a697f75f16e5b37fcabb8c07fcac3397f6f", - "terminal_desk/families/finance3.py": "a4839540c7a54198ea8e480248428e9ca65bdaf45adea5ae9f81cad71cbb1311", - "terminal_desk/families/industrial.py": "9140985ca44b1bcfc78b853f44496b7a9b77288284675f3656898de5be70d6aa", - "terminal_desk/families/industrial3.py": "48e914996b67accb09350a6714a5cea4a6191c0a05ac12a8f3045309f961c49c", - "terminal_desk/families/mathematics.py": "552855819cbe4983529b864279c915bc56f8d68d850a3f221d84864066c0e2a5", - "terminal_desk/families/mathematics3.py": "9dc54710cd826aadbe5de55d9093959e38c59dc59ae080e40d379cc4db1987c1", - "terminal_desk/families/media.py": "52523502e6c679e34bd2dbeb46c3f539ba53ae2d4e1033adafca7ce859bc4de8", - "terminal_desk/families/media3.py": "9c91cfbde8ad60da034c15ba3418e21ae5891a12ce3932ecaf8035fcd6eef4bd", - "terminal_desk/families/office.py": "11f76ce7d62e18b535278b487f798703fd6f2bef04dd7ffaefae2c95bcba1102", - "terminal_desk/families/office3.py": "1926c4a6e600cabb4cd35fab9528b4e4d55ef4adc1623b7229ac356ef28c987b", - "terminal_desk/families/science.py": "836ab819a2231700a4bff2929a4579034c45a637992e883ddfbdb0c1f711446a", - "terminal_desk/families/science3.py": "59477a1f9d38dbe5607f6432b4f8538342eec93faeed09bb6c9cb1402980c9a1", - "terminal_desk/families/security.py": "1228db896b6ce796ccf1f133e2f2ba9aaa9d54b745d5ffaf4b584a63a6aab2bd", - "terminal_desk/families/security3.py": "6f5ec9c2dfe9aad81ba382d4f6ffdb7f64493d92cd7fe5d653134ef0dac107af", - "terminal_desk/families/software.py": "4bca03797d701fe33f567729baa9a4fb2cef59cf220d0b79a941cc3817f8ba3a", - "terminal_desk/families/software3.py": "d526ae88ca53ef22dbc1e578055fc27ebb491c184474e662736b8be9523086a7", - "terminal_desk/models.py": "f31264b0909878c6f2d4d18a270c7d92bc895052150c56e5ac3e6b38d4ceebb4", - "terminal_desk/oracles/__init__.py": "04e4b102444b5db19507a46814820d78ad1e9782f963e5764f8f4adfe4d366a3", - "terminal_desk/oracles/fin3_invoice_fraud.py": "975ff8045d42b2f483924e368e304c451bca894ddb4ba593d9dd3aea1c505329", - "terminal_desk/oracles/fin3_loan_schedule.py": "b0a32266ec725f5a4f76d8b40a27fc52759f679d74e4dfe5c7885a1b19a36711", - "terminal_desk/oracles/fin3_portfolio_value.py": "152a3516b9ec6811121747ea875fc1a73cb768ba6a98e05c2bee91325e4f7247", - "terminal_desk/oracles/ind3_service_due.py": "47914a6e1a5bde126ce301bc11d4dc95b11cb0910ac0208a4c78596d7e65e30e", - "terminal_desk/oracles/ind3_stl_mass.py": "53e6adc26768256ce6665bda20c4b04ad87602e24eb31b074c25dc8fbbc00653", - "terminal_desk/oracles/ind3_tank_balance.py": "c1049fdb6b4f11f0b5e0194b41e84b525d5a340213c2c94f5f99ffd6c2b75a42", - "terminal_desk/oracles/math3_count_items.py": "0fd62812cd9ef1d5be6d6ae9fa2fa047eb6bb0a4508ccb5a5369373aefbf8dd3", - "terminal_desk/oracles/math3_exam_slots.py": "03908ec43159f4a66678f37fb0366389608eeeba41361758d966c96eea50dc3f", - "terminal_desk/oracles/math3_route_plan.py": "c2bb32b08a3705a4be56ff8c4e3af94d64441c9a7432f5dcec4dce0b378ee465", - "terminal_desk/oracles/med3_silence_report.py": "554e36455da66fd258e6ad2c39e80acbc3856237fee4608ce57b494f23c3d16d", - "terminal_desk/oracles/med3_sprite_count.py": "8f0a1169d6e5b10c4981b53a22e957c4befad44d95e5d250cf53734105a40256", - "terminal_desk/oracles/med3_subtitle_retime.py": "72f448ba58ac9ee6082692dec88ddb6f279ae69bdb99d39b30d1acce12c19bfe", - "terminal_desk/oracles/off3_ar_recon.py": "b5320a71696443f1b04c0c5e02e35d0baee67a175a912bff86e32df7c2acb357", - "terminal_desk/oracles/off3_meeting_slot.py": "6eef5e15337e5029c8e0b3353adee791ea9ebe73c6d79e47d84d6b7294cb5a38", - "terminal_desk/oracles/off3_pdf_xlsx_diff.py": "82b5c15f02a03615699429a2342dbad4b8985aab76d82fa8a8b96f7fbebc544f", - "terminal_desk/oracles/sci3_kinetics_fit.py": "1ebc19667bf1963c83a47bd4905e99e0c32c3ce249b63ae2d7b39fcffa1b1bb7", - "terminal_desk/oracles/sci3_lightcurve_period.py": "a983fb3c03ba15bc0591ab32ce41ddb99f2f38329e273f3f5da20f775d6bd8ab", - "terminal_desk/oracles/sci3_stoich_batch.py": "56a84763e746f034571dc50a71f3716f340e4f8d9dee823eb3c9b209f471f48a", - "terminal_desk/oracles/sec3_auth_triage.py": "c5fb5f697e8cfdb6008fcd59d6c3095a509d9a488dc28d7b99da4f4fe128b8a6", - "terminal_desk/oracles/sec3_exfil_flows.py": "5a4cc8a38f0554be4b287e2592bd26553db2f3ee6b5c10339d641246a7a6af90", - "terminal_desk/oracles/sec3_fw_verdicts.py": "b91c7389813445d55edbdaadec60aa4c5d0b6c5ead6fdfca5268e425f512820f", - "terminal_desk/oracles/sw3_dep_lock.py": "6b46601bc7e4bdc42c62242344aa431a34e7a6d1a8c7201e77315c66c6a4ae09", - "terminal_desk/oracles/sw3_fix_module.py": "43eee7f24a02ca3f0d3b12db5a44c132a931fc8dba10f9c1d4028d7fa5775bf4", - "terminal_desk/oracles/sw3_rate_limit.py": "4f1f187ae42f47faecc85d84e1f0341c848b03eb2bba1bf538927e2e62758314", - "terminal_desk/server/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "terminal_desk/server/app.py": "6bf7658ec8ad07dda230a01fd893091a9b87df18ebf6af25af6c35965ed01fd8", - "terminal_desk/server/environment.py": "8e92f991e14098a0858490fe5beb43ca9b0ee2cfbddb36e73ecf987ba3922902" - }, - "selected_tasks": [ - "math3_exam_slots-L2", - "off3_meeting_slot-L2", - "med3_subtitle_retime-L2", - "med3_silence_report-L2" - ] -} diff --git a/components/dnakhla/runtime/dnakhla_compat/__init__.py b/components/dnakhla/runtime/dnakhla_compat/__init__.py deleted file mode 100644 index 8e9428f06894be913aed5bbd7c797ca3158b4423..0000000000000000000000000000000000000000 --- a/components/dnakhla/runtime/dnakhla_compat/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Local compatibility prototype for the original Terminal Desk environment.""" diff --git a/components/dnakhla/upstream/terminal_desk/families/__init__.py b/components/dnakhla/upstream/terminal_desk/families/__init__.py deleted file mode 100644 index fe4f214ba9137a17d8a6bdc9b1502efb3bf18c8d..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/families/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -"""Registry of task families. A task id is '-L', e.g. 'ind_tank-L2'.""" - -from . import finance, finance3, industrial, industrial3, mathematics, mathematics3, media, media3, office, office3, science, science3, security, security3, software, software3 -from .base import Family - -FAMILIES: dict[str, Family] = { - f.id: f - for module in (software, industrial, industrial3, science, office, finance, mathematics, security, media, office3, security3, mathematics3, science3, media3, software3, finance3) - for f in module.FAMILIES -} - - -def parse_task_id(task_id: str) -> tuple[str, int]: - family_id, _, level = task_id.rpartition("-L") - if family_id not in FAMILIES or not level.isdigit() or int(level) not in FAMILIES[family_id].levels: - raise ValueError(f"unknown task_id {task_id!r}") - return family_id, int(level) - - -def all_task_ids() -> list[str]: - return [f"{fid}-L{lv}" for fid, fam in FAMILIES.items() for lv in fam.levels] diff --git a/components/dnakhla/upstream/terminal_desk/families/finance.py b/components/dnakhla/upstream/terminal_desk/families/finance.py deleted file mode 100644 index db88a0d592978734dba321c834b3fbdc46353d4b..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/families/finance.py +++ /dev/null @@ -1,228 +0,0 @@ -"""Finance: amortize a loan with extras and a rate reset; value a portfolio through corporate actions.""" - -import datetime as dt -import random -from decimal import ROUND_HALF_UP, Decimal, getcontext - -from .base import Artifact, Built, Family, Field - -getcontext().prec = 40 -CENT = Decimal("0.01") - -# ---------------------------------------------------------------- fin_loan - - -def _r(x: Decimal) -> Decimal: - return x.quantize(CENT, rounding=ROUND_HALF_UP) - - -def _payment(balance: Decimal, annual_pct: Decimal, months: int) -> Decimal: - i = annual_pct / 1200 - return _r(balance * i / (1 - (1 + i) ** -months)) - - -def build_loan(level: int, rng: random.Random) -> Built: - while True: - principal = Decimal(rng.randrange(100, 4000) * 100) - rate = Decimal(f"{rng.uniform(3, 9):.3f}") - months = rng.choice([60, 120, 180, 240, 360]) - extras = {} - if level >= 2: - for m in rng.sample(range(6, months // 2), rng.randint(2, 4)): - extras[m] = Decimal(rng.randrange(5, 60) * 100) - reset_month, new_rate = None, None - if level == 3: - reset_month = rng.randint(13, min(60, months - 12)) - new_rate = Decimal(f"{float(rate) + rng.uniform(-1.5, 2.5):.3f}") - pay = _payment(principal, rate, months) - bal, cur_rate, month, new_pay = principal, rate, 0, None - rows = [] - while bal > 0: - month += 1 - if reset_month and month == reset_month: - cur_rate = new_rate - pay = new_pay = _payment(bal, new_rate, months - month + 1) - interest = _r(bal * cur_rate / 1200) - if bal + interest <= pay or month == months: - rows.append({"month": month, "payment": float(bal + interest), "interest": float(interest), - "principal": float(bal), "balance": 0.0}) - bal = Decimal(0) - break - bal -= pay - interest - row = {"month": month, "payment": float(pay), "interest": float(interest), "principal": float(pay - interest)} - if month in extras: - bal -= min(extras[month], bal) - row["balance"] = float(bal) - rows.append(row) - if level < 3 or new_pay is not None: - break - lines = [ - f"Principal: {principal}", - f"Annual interest rate: {rate}% (monthly rate = annual rate / 12)", - f"Term: {months} months", - "Monthly payment: the standard annuity payment for the term, rounded to the cent.", - ] - if extras: - lines.append("Extra principal payments (made right after that month's regular payment):") - lines += [f" month {m}: {v}" for m, v in sorted(extras.items())] - if reset_month: - lines.append( - f"Rate reset: from month {reset_month} the annual rate is {new_rate}%. At that point the payment is " - f"recomputed as the annuity payment on the balance then owed over the {months - reset_month + 1} " - "months left, rounded to the cent." - ) - files = {"loan.txt": "\n".join(lines) + "\n"} - instruction = ( - "loan.txt in /app describes a loan. Write its amortization schedule to /app/schedule.csv with the header " - "month,payment,interest,principal,balance and one row per month until the loan is paid off, for example " - "1,1932.56,500.00,1432.56,98567.44. Interest = balance x monthly rate, rounded half up to the cent; " - "principal = payment - interest; balance is what remains after the row, after any extra payment that " - "month. If balance plus interest is no more than the payment (or in the last month of the term), that row " - "pays exactly balance plus interest and the balance is 0." - ) - artifact = Artifact( - path="schedule.csv", - kind="csv", - key=("month",), - ordered=True, - fields=[ - Field("month", "int"), - Field("payment", "number", tol=0.005), - Field("interest", "number", tol=0.005), - Field("principal", "number", tol=0.005), - Field("balance", "number", tol=0.005), - ], - expected=rows, - ) - return Built(instruction=instruction, files=files, artifact=artifact, notes={"payoff_month": month}) - - -# ---------------------------------------------------------------- fin_portfolio - -TICKERS = ["ALDR", "BRKS", "CNDL", "DRFT", "EMBR", "FJRD"] - - -def _trading_days(start: dt.date, n: int) -> list[dt.date]: - out, d = [], start - while len(out) < n: - if d.weekday() < 5: - out.append(d) - d += dt.timedelta(days=1) - return out - - -def build_portfolio(level: int, rng: random.Random) -> Built: - n_tick, n_days, n_trades = {1: (3, 20, 5), 2: (4, 40, 9), 3: (5, 60, 13)}[level] - while True: - tickers = rng.sample(TICKERS, n_tick) - days = _trading_days(dt.date(2026, 6, 1), n_days) - split = None - if level >= 2: - split = (rng.choice(tickers), days[rng.randint(n_days // 3, 2 * n_days // 3)], rng.choice([2, 3])) - closes = {} - for t in tickers: - p = rng.uniform(20, 300) - for d in days: - p *= 1 + rng.gauss(0.0005, 0.018) - adj = p / split[2] if split and t == split[0] and d >= split[1] else p - closes[(d, t)] = Decimal(f"{adj:.2f}") - divs = [] - if level == 3: - for t in rng.sample(tickers, 2): - d = rng.choice(days[3:-1]) - if split and d == split[1]: - continue - divs.append((d, t, Decimal(f"{rng.uniform(0.2, 1.5):.2f}"))) - cash = Decimal(100000) - hold = {t: 0 for t in tickers} - trade_days = sorted(rng.sample(days[:-2], n_trades)) - trades, div_income = [], Decimal(0) - events = sorted( - ([(split[1], 0, "split", None)] if split else []) - + [(d, 1, "div", (t, v)) for d, t, v in divs] - + [(d, 2, "trade", None) for d in trade_days], - key=lambda e: (e[0], e[1]), - ) - ok = True - for d, _, kind, info in events: - if kind == "split": - hold[split[0]] *= split[2] - elif kind == "div": - t, v = info - div_income += v * hold[t] # holdings at the end of the previous trading day - cash += v * hold[t] - else: - t = rng.choice(tickers) - price = closes[(d, t)] + Decimal(f"{rng.uniform(-0.5, 0.5):.2f}") - if hold[t] > 0 and rng.random() < 0.35: - qty, side = rng.randint(1, hold[t]), "SELL" - cash += qty * price - hold[t] -= qty - else: - qty, side = rng.randint(5, 200), "BUY" - if qty * price > cash: - ok = False - break - cash -= qty * price - hold[t] += qty - trades.append((d, t, side, qty, price)) - if not ok: - continue - last = days[-1] - values = {t: hold[t] * closes[(last, t)] for t in tickers} - ranked = sorted(values.items(), key=lambda kv: -kv[1]) - if ranked[0][1] > 0 and (len(ranked) < 2 or ranked[0][1] - ranked[1][1] > 50): - break - files = { - "prices.csv": "date,ticker,close\n" - + "".join(f"{d.isoformat()},{t},{closes[(d, t)]}\n" for d in days for t in tickers), - "trades.csv": "date,ticker,side,shares,price\n" - + "".join(f"{d.isoformat()},{t},{s},{q},{p}\n" for d, t, s, q, p in trades), - } - notes = [] - if split or divs: - lines = [] - if split: - lines.append( - f"{split[1].isoformat()} {split[0]} {split[2]}-for-1 stock split before the open: every share held " - "becomes " + str(split[2]) + " shares. Closes and trades from that date on are post-split." - ) - for d, t, v in sorted(divs): - lines.append( - f"{d.isoformat()} {t} cash dividend of {v} per share, paid on shares held at the end of the " - "previous trading day." - ) - files["corporate_actions.txt"] = "\n".join(lines) + "\n" - notes.append("Apply corporate_actions.txt.") - instruction = ( - "prices.csv and trades.csv in /app are a brokerage account's daily closes and trades. The account starts " - "with 100000.00 in cash and no shares; trades execute at their listed price (BUY spends cash, SELL adds " - "it; no fees). " + " ".join(notes) + f" Write /app/positions.csv with the header ticker,shares,close," - f"market_value: one row per ticker still held after the last date in prices.csv ({last.isoformat()}), " - "with its shares, that day's close and shares x close, plus a row CASH,0,0,. " - "Example: ALDR,120,45.10,5412.00" - ) - rows = [ - {"ticker": t, "shares": float(hold[t]), "close": float(closes[(last, t)]), "market_value": float(values[t])} - for t in tickers - if hold[t] > 0 - ] + [{"ticker": "CASH", "shares": 0.0, "close": 0.0, "market_value": float(cash)}] - artifact = Artifact( - path="positions.csv", - kind="csv", - key=("ticker",), - fields=[ - Field("ticker", "text"), - Field("shares", "number", tol=1e-6), - Field("close", "number", tol=0.005), - Field("market_value", "number", tol=0.01), - ], - expected=rows, - ) - return Built(instruction=instruction, files=files, artifact=artifact, notes={"dividend_income": float(div_income)}) - - -FAMILIES = [ - Family("fin_loan", "finance and economics", "Amortize a loan", build_loan), - Family("fin_portfolio", "finance and economics", "Value a portfolio", build_portfolio), -] diff --git a/components/dnakhla/upstream/terminal_desk/families/finance3.py b/components/dnakhla/upstream/terminal_desk/families/finance3.py deleted file mode 100644 index 04d96ba670a605f51f261f6c8eced93145c7bb02..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/families/finance3.py +++ /dev/null @@ -1,428 +0,0 @@ -"""Finance v3: amortize one loan from a loan book, value a brokerage account, screen invoices for fraud. - -All three are stdlib csv/json tasks rooted at /root. Each generator computes its expected answer itself; -the oracle scripts in terminal_desk/oracles/ only prove the files carry everything the answer needs. -""" - -import datetime as dt -import json -import random -from decimal import Decimal - -from .base import Artifact, Built, Family -from .finance import TICKERS, _payment, _r, _trading_days - -TOL = 0.005 + 1e-9 # "to the cent": a value two-decimal rounded the same way passes, one cent off fails - - -def _num(s) -> float: - return float(str(s).strip()) - - -def _col_close(rows: list[dict], want: list[dict], col: str, tol: float = TOL) -> bool: - return len(rows) == len(want) and all(abs(_num(r[col]) - w[col]) <= tol for r, w in zip(rows, want)) - - -# ---------------------------------------------------------------- fin3_loan_schedule - -LOAN_TERMS = (36, 48, 60) - - -class Overpaid(Exception): - """An extra would clear the loan; the instruction does not cover that case, so the generator resamples.""" - - -def _loan_id(rng: random.Random, used: set) -> str: - while True: - lid = f"LN-{rng.randrange(1000, 10000)}" - if lid not in used: - used.add(lid) - return lid - - -def _amortize(principal: Decimal, rate: Decimal, term: int, extras: dict, reset) -> list[dict]: - """The schedule, in Decimal: v2 build_loan arithmetic plus an extra column. reset = (month, new_rate) or None.""" - pay, bal, cur, month, rows = _payment(principal, rate, term), principal, rate, 0, [] - while bal > 0: - month += 1 - if reset and month == reset[0]: - cur = reset[1] - pay = _payment(bal, cur, term - month + 1) - interest = _r(bal * cur / 1200) - if bal + interest <= pay or month == term: - rows.append({"month": month, "payment": bal + interest, "interest": interest, "principal": bal, - "extra": Decimal(0), "balance": Decimal(0)}) - break - bal -= pay - interest - extra = extras.get(month, Decimal(0)) - if extra >= bal: - raise Overpaid(f"month {month}: extra {extra} >= balance {bal}") - bal -= extra - rows.append({"month": month, "payment": pay, "interest": interest, "principal": pay - interest, - "extra": extra, "balance": bal}) - return rows - - -def build_loan_schedule(level: int, rng: random.Random) -> Built: - n_book = {1: 130, 2: 140, 3: 150}[level] - while True: - used: set = set() - book = [(_loan_id(rng, used), Decimal(rng.randrange(100, 900) * 100), Decimal(f"{rng.uniform(4, 8):.3f}"), - rng.choice(LOAN_TERMS)) for _ in range(n_book)] - target = rng.randrange(n_book) - lid, principal, rate, term = book[target] - extras, ledger, reset, resets, reversed_m = {}, [], None, [], 0 - if level >= 2: - months = rng.sample(range(3, term // 2), rng.randint(3, 4)) - months.append(rng.choice(months)) # two extras on one payment add up - for m in months: - amt = Decimal(rng.randrange(5, 40) * 100) - extras[m] = extras.get(m, Decimal(0)) + amt - ledger.append((lid, m, amt, "POSTED")) - if level == 3: # a reversed extra that would change the answer if applied - reversed_m = rng.choice([m for m in range(3, term // 2) if m not in extras]) - ledger.append((lid, reversed_m, Decimal(rng.randrange(5, 40) * 100), "REVERSED")) - for other, _, _, oterm in rng.sample(book[:target] + book[target + 1:], 30): - for m in rng.sample(range(2, oterm // 2), rng.randint(1, 3)): - status = "REVERSED" if level == 3 and rng.random() < 0.15 else "POSTED" - ledger.append((other, m, Decimal(rng.randrange(5, 40) * 100), status)) - rng.shuffle(ledger) - if level == 3: - reset = (rng.randint(max(extras) + 1, term - 12), Decimal(f"{float(rate) + rng.uniform(-1.5, 2.5):.3f}")) - resets = [(lid,) + reset] + [(o, rng.randint(13, t - 12), Decimal(f"{float(r) + rng.uniform(-1, 2):.3f}")) - for o, _, r, t in rng.sample(book[:target] + book[target + 1:], 14)] - rng.shuffle(resets) - try: - rows = _amortize(principal, rate, term, extras, reset) - except Overpaid: - continue - payoff = rows[-1]["month"] - if max([0, reversed_m, *extras]) >= payoff or reset and reset[0] >= payoff: - continue - break - files = { - "data/loans.csv": "loan_id,principal,annual_rate_pct,term_months\n" - + "".join(f"{i},{p},{r},{t}\n" for i, p, r, t in book), - "data/ticket.txt": f"Ticket: SRV-{rng.randrange(10000, 99999)}\nLoan: {lid}\n" - "Request: rebuild the repayment schedule; the borrower disputes the balance on the statement.\n", - } - cols = ["month", "payment", "interest", "principal"] + (["extra"] if level >= 2 else []) + ["balance"] - inputs = f"ticket /root/data/ticket.txt names loan {lid}." + ( - " Its terms are in the loan book /root/data/loans.csv (loan_id, principal, annual_rate_pct, term_months)" - if level < 3 else " The loan book /root/data/loans.csv") - steps = [ - "Payment = annuity payment on the principal over the term at monthly rate annual rate / 1200.", - "Each month: interest = balance x monthly rate; principal = payment - interest. Round every payment and " - "interest half up to the cent.", - ] - if level >= 2: - files["data/extra_payments.csv"] = "loan_id,payment_no,amount" + (",status" if level == 3 else "") + "\n" + ( - "".join(f"{a},{m},{v:.2f}" + (f",{s}" if level == 3 else "") + "\n" for a, m, v, s in ledger)) - inputs += (". /root/data/extra_payments.csv (loan_id, payment_no, amount) covers every loan" if level == 2 else - ", /root/data/extra_payments.csv and /root/data/rate_resets.csv cover every loan") - steps.append("Extras are paid right after the regular payment with that payment_no and add up" - + ("; REVERSED rows were never paid." if level == 3 else ".")) - if level == 3: - files["data/rate_resets.csv"] = "loan_id,from_payment,new_rate_pct\n" + "".join( - f"{a},{m},{r}\n" for a, m, r in resets) - steps.append("From a reset's from_payment on, use new_rate_pct and re-amortize the balance then owed over the " - "payments left, this one included.") - steps.append("If balance + interest <= payment, or in the term's last month, pay balance + interest, set " - "balance to 0 and stop.") - ex_p, ex_r = Decimal(rng.randrange(100, 900) * 100), Decimal(f"{rng.uniform(4, 8):.3f}") # another loan - ex_i = _r(ex_p * ex_r / 1200) - ex_pay = _payment(ex_p, ex_r, rng.choice(LOAN_TERMS)) - ex_vals = {"payment": ex_pay, "interest": ex_i, "principal": ex_pay - ex_i, "extra": Decimal(0), - "balance": ex_p - ex_pay + ex_i} - example = ",".join("1" if c == "month" else f"{ex_vals[c]:.2f}" for c in cols) - opener = rng.choice(["A borrower disputes a statement:", "Servicing needs a fixed schedule:"]) - instruction = ( - f"{opener} {inputs}.\n\n" + "\n".join(f"{i}. {s}" for i, s in enumerate(steps, 1)) - + f"\n\nWrite /root/schedule.csv with header {','.join(cols)}, one row per month from 1, two decimals, " - f"e.g.\n{example}\nValues must match to the cent." - ) - want = [{c: float(r[c]) for c in cols} for r in rows] - - def render() -> str: - return ",".join(cols) + "\n" + "".join( - ",".join(str(r["month"]) if c == "month" else f"{r[c]:.2f}" for c in cols) + "\n" for r in rows) - - checks = [ - ("test_header", lambda p: p["header"] == cols), - ("test_row_count", lambda p: len(p["rows"]) == len(want)), - ("test_months_in_order", lambda p: [r["month"] for r in p["rows"]] == [str(i) for i in range(1, payoff + 1)]), - ] + [(f"test_{c}", lambda p, c=c: _col_close(p["rows"], want, c)) for c in cols[1:]] - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="schedule.csv", kind="checks", parse="csv", checks=checks, render=render), - notes={"payoff_month": payoff, "loan_id": lid}, - root="/root", - ) - - -# ---------------------------------------------------------------- fin3_portfolio_value - - -def build_portfolio_value(level: int, rng: random.Random) -> Built: - n_tick, n_days, n_trades = {1: (4, 30, 6), 2: (5, 36, 10), 3: (6, 40, 14)}[level] - while True: - tickers = sorted(rng.sample(TICKERS, n_tick)) - days = _trading_days(dt.date(2026, 6, 1) + dt.timedelta(days=rng.randrange(0, 60)), n_days) - split = None - if level >= 2: - split = (rng.choice(tickers), days[rng.randint(n_days // 3, 2 * n_days // 3)], rng.choice([2, 3])) - closes = {} - for t in tickers: - p = rng.uniform(20, 300) - for d in days: - p *= 1 + rng.gauss(0.0005, 0.018) - adj = p / split[2] if split and t == split[0] and d >= split[1] else p - closes[(d, t)] = Decimal(f"{adj:.2f}") - divs = [] - if level == 3: - for t in rng.sample(tickers, 2): - d = rng.choice(days[3:-1]) - if not (split and d == split[1]): - divs.append((d, t, Decimal(f"{rng.uniform(0.2, 1.5):.2f}"))) - cash, hold = Decimal(100000), {t: 0 for t in tickers} - trades = [] - events = sorted(([(split[1], 0, "split", None)] if split else []) - + [(d, 1, "div", (t, v)) for d, t, v in divs] - + [(d, 2, "trade", None) for d in sorted(rng.sample(days[:-2], n_trades))], - key=lambda e: (e[0], e[1])) - ok, paid, split_shares = True, Decimal(0), 0 - for d, _, kind, info in events: - if kind == "split": - split_shares = hold[split[0]] - hold[split[0]] *= split[2] - elif kind == "div": - paid += info[1] * hold[info[0]] # shares held at the end of the previous trading day - cash += info[1] * hold[info[0]] - else: - t = rng.choice(tickers) - price = closes[(d, t)] + Decimal(f"{rng.uniform(-0.5, 0.5):.2f}") - if hold[t] > 0 and rng.random() < 0.35: - qty, side = rng.randint(1, hold[t]), "SELL" - cash += qty * price - hold[t] -= qty - else: - qty, side = rng.randint(5, 200), "BUY" - if qty * price > cash: - ok = False - break - cash -= qty * price - hold[t] += qty - trades.append((d, t, side, qty, price)) - if not ok or sum(1 for t in tickers if hold[t]) < 2: - continue - if split and not (split_shares and hold[split[0]]) or divs and paid == 0: # the caveat changes the answer - continue - break - last = days[-1] - want = {t: (hold[t], closes[(last, t)], hold[t] * closes[(last, t)]) for t in tickers if hold[t] > 0} - want["CASH"] = (0, Decimal(0), cash) - files = { - "data/prices.csv": "date,ticker,close\n" + "".join(f"{d.isoformat()},{t},{closes[(d, t)]}\n" - for d in days for t in tickers), - "data/trades.csv": "date,ticker,side,shares,price\n" + "".join(f"{d.isoformat()},{t},{s},{q},{p}\n" - for d, t, s, q, p in trades), - } - caveat = "" - if level >= 2: - lines = [f"{split[1].isoformat()} {split[0]} {split[2]}-for-1 stock split before the open: every share held " - f"becomes {split[2]} shares. Closes and trades from that date on are post-split."] - lines += [f"{d.isoformat()} {t} cash dividend of {v} per share, paid on shares held at the end of the previous " - "trading day." for d, t, v in sorted(divs)] - files["data/corporate_actions.txt"] = "\n".join(lines) + "\n" - caveat = " Apply every event in /root/data/corporate_actions.txt on its date, before that day's trades." - ex_t = rng.choice(("GLNT", "HRBR", "KSTL")) # not a ticker in any instance - ex_q, ex_c = rng.randint(5, 300), Decimal(rng.randrange(2000, 30000)) / 100 - opener = rng.choice([ - "You are reconciling a brokerage account for the month-end report.", - "The operations team needs a month-end valuation of a brokerage account.", - ]) - instruction = ( - f"{opener} /root/data/prices.csv holds daily closes (date, ticker, close) and /root/data/trades.csv the " - "account's trades (date, ticker, side, shares, price).\n\n" - "The account starts with 100000.00 in cash and no shares. Replay the trades in date order: a BUY spends " - "shares x price in cash, a SELL adds it, with no fees." + caveat + "\n\n" - f"Write /root/positions.csv with the header ticker,shares,close,market_value: one row per ticker still held " - f"after the last date in prices.csv ({last.isoformat()}), with its shares, that day's close and shares x " - "close; leave out tickers with zero shares. Add a final row CASH,0,0,. Money has two " - f"decimals, for example:\n{ex_t},{ex_q},{ex_c:.2f},{ex_q * ex_c:.2f}\n" - "Shares must match exactly and money to the cent." - ) - - def render() -> str: - return "ticker,shares,close,market_value\n" + "".join( - f"{t},{s},{c:.2f},{v:.2f}\n" for t, (s, c, v) in want.items()) - - def by_ticker(p): - return {r["ticker"]: r for r in p["rows"]} - - checks = [ - ("test_header", lambda p: p["header"] == ["ticker", "shares", "close", "market_value"]), - ("test_tickers", lambda p: len(p["rows"]) == len(want) and set(by_ticker(p)) == set(want)), - ("test_shares", lambda p: all(_num(by_ticker(p)[t]["shares"]) == s for t, (s, _, _) in want.items())), - ("test_close", lambda p: all(abs(_num(by_ticker(p)[t]["close"]) - float(c)) <= TOL - for t, (_, c, _) in want.items() if t != "CASH")), - ("test_market_value", lambda p: all(abs(_num(by_ticker(p)[t]["market_value"]) - float(v)) <= 0.01 + 1e-9 - for t, (_, _, v) in want.items() if t != "CASH")), - ("test_cash", lambda p: abs(_num(by_ticker(p)["CASH"]["market_value"]) - float(cash)) <= 0.01 + 1e-9), - ] - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="positions.csv", kind="checks", parse="csv", checks=checks, render=render), - notes={"dividend_income": float(paid), "split_shares": split_shares}, - root="/root", - ) - - -# ---------------------------------------------------------------- fin3_invoice_fraud - -TOLERANCE_PCT = 2 # an amount more than 2% away from its PO amount is out of tolerance -REASONS = ("Unknown Vendor", "Missing PO", "Amount Mismatch", "Duplicate Invoice") - - -def _screen(invoices: list[tuple], vendors: dict | None, pos: dict, level: int) -> list[dict]: - """The rules in order, first match wins. invoices: (invoice_no, vendor_id, po_number, amount).""" - report, seen = [], set() - for row, (no, vid, po, amt) in enumerate(invoices, 1): - reason = None - if vendors is not None and vendors.get(vid) != "ACTIVE": - reason = "Unknown Vendor" - elif level >= 2 and po not in pos: - reason = "Missing PO" - elif abs(amt - pos[po]) * 100 > TOLERANCE_PCT * pos[po]: - reason = "Amount Mismatch" - elif level == 3 and (vid, no) in seen: - reason = "Duplicate Invoice" - seen.add((vid, no)) - if reason: - report.append({"row": row, "invoice_no": no, "amount": float(amt), "reason": reason}) - return report - - -def build_invoice_fraud(level: int, rng: random.Random) -> Built: - n_inv, n_spare = {1: (70, 30), 2: (80, 30), 3: (90, 25)}[level] - live = REASONS[2:3] if level == 1 else REASONS[:3] if level == 2 else REASONS - while True: - vendor_ids = rng.sample(range(101, 200), 18) - listed = vendor_ids[:14] # in vendors.csv; the last four are not - inactive = set(rng.sample(listed, 2)) - vendors = {f"V{v}": ("INACTIVE" if v in inactive else "ACTIVE") for v in listed} - good = [f"V{v}" for v in listed if v not in inactive] - bad = [f"V{v}" for v in inactive] + [f"V{v}" for v in vendor_ids[14:]] - po_nums = [f"PO-{n}" for n in rng.sample(range(1000, 10000), n_inv + n_spare + 10)] - pos = {n: Decimal(rng.randrange(10000, 2000000)) / 100 for n in po_nums[:n_inv + n_spare]} - po_vendor = {n: rng.choice(good) for n in pos} - ghost_pos = po_nums[n_inv + n_spare:] # never issued - inv_nos = iter(rng.sample(range(10000, 100000), n_inv + 5)) - free = list(pos)[:n_inv] - invoices = [] - for i in range(n_inv): - po = free[i] - vid, amt = po_vendor[po], pos[po] - roll = rng.random() - if roll < 0.35: # clean but not exact: inside the tolerance - amt = _r(amt * (1 + Decimal(rng.uniform(-1.5, 1.5)) / 100)) - elif roll < 0.55: - amt = _r(amt * (1 + Decimal(rng.choice((-1, 1)) * rng.uniform(3, 25)) / 100)) - elif level >= 2 and roll < 0.67: - vid = rng.choice(bad) - if rng.random() < 0.5: # also out of tolerance: the order decides the reason - amt = _r(amt * Decimal("1.1")) - elif level >= 2 and roll < 0.79: - po = rng.choice(["", rng.choice(ghost_pos)]) - invoices.append((f"INV-{next(inv_nos)}", vid, po, amt)) - if level == 3: - for k in rng.sample(range(n_inv // 3), 3): # resubmissions of earlier invoices, appended later - no, vid, po, amt = invoices[k] - if rng.random() < 0.3: - amt = _r(amt * Decimal("1.08")) # resubmitted and inflated: Amount Mismatch outranks Duplicate - invoices.insert(rng.randrange(k + 5, len(invoices)), (no, vid, po, amt)) - k = rng.randrange(len(invoices)) # same number, another vendor: not a duplicate - no = invoices[k][0] - spare = next(n for n in list(pos)[n_inv:] if po_vendor[n] != invoices[k][1]) - invoices.insert(rng.randrange(k + 1, len(invoices) + 1), (no, po_vendor[spare], spare, pos[spare])) - report = _screen(invoices, vendors if level >= 2 else None, pos, level) - reasons = [r["reason"] for r in report] - if not all(reasons.count(x) >= 2 for x in live): - continue - if not 0.15 <= len(report) / len(invoices) <= 0.4: - continue - if level >= 2: # the status caveat, the unlisted vendor and the rule order each change the answer - used = {vid for _, vid, _, _ in invoices} - unknown_over = [r for r in report if r["reason"] == "Unknown Vendor" - and invoices[r["row"] - 1][2] in pos - and abs(invoices[r["row"] - 1][3] - pos[invoices[r["row"] - 1][2]]) * 100 - > TOLERANCE_PCT * pos[invoices[r["row"] - 1][2]]] - if not (used & {f"V{v}" for v in inactive} and used - set(vendors) and unknown_over): - continue - break - files = { - "data/invoices.csv": "invoice_no,vendor_id,po_number,amount\n" - + "".join(f"{no},{vid},{po},{amt:.2f}\n" for no, vid, po, amt in invoices), - "data/purchase_orders.csv": "po_number,vendor_id,amount\n" - + "".join(f"{n},{po_vendor[n]},{a:.2f}\n" for n, a in pos.items()), - } - rule_amount = (f"the invoice amount differs from its PO's amount by more than {TOLERANCE_PCT}% of the PO amount") - if level == 1: - rules = f"Flag an invoice as Amount Mismatch when {rule_amount}. Every invoice cites a valid PO." - else: - files["data/vendors.csv"] = "vendor_id,status\n" + "".join(f"{v},{s}\n" for v, s in vendors.items()) - rules = ("Check each invoice against these rules in order and report only the first that applies:\n" - "1. Unknown Vendor: vendor_id is not in /root/data/vendors.csv with status ACTIVE.\n" - "2. Missing PO: po_number is empty or not in the PO list.\n" - f"3. Amount Mismatch: {rule_amount}.") - if level == 3: - rules += "\n4. Duplicate Invoice: an earlier row has the same vendor_id and invoice_no." - ex = {"row": rng.randint(2, 60), "invoice_no": f"INV-{rng.randrange(10000, 100000)}", - "amount": float(Decimal(rng.randrange(10000, 2000000)) / 100), "reason": rng.choice(live)} - opener = rng.choice([ - "Accounts payable must screen this month's invoices before they are paid.", - "You are screening supplier invoices for fraud before the payment run.", - ]) - instruction = ( - f"{opener} /root/data/invoices.csv has one invoice per row (invoice_no, vendor_id, po_number, amount) and " - "/root/data/purchase_orders.csv lists the issued purchase orders (po_number, vendor_id, amount).\n\n" - f"{rules}\n\nWrite /root/fraud_report.json as a JSON array of the flagged invoices only, in file order. Each " - "item has row (the 1-based position in invoices.csv, header not counted), invoice_no, amount (a number) and " - f"reason, for example:\n{json.dumps(ex)}" - ) - - def render() -> str: - return json.dumps(report, indent=1) + "\n" - - def rows_of(p): - return [r["row"] for r in p] - - checks = [ - ("test_is_list", lambda p: isinstance(p, list) and all(isinstance(r, dict) for r in p)), - ("test_record_keys", lambda p: all(set(r) == {"row", "invoice_no", "amount", "reason"} for r in p)), - ("test_file_order", lambda p: rows_of(p) == sorted(set(rows_of(p)))), - ("test_flagged_rows", lambda p: rows_of(p) == [r["row"] for r in report]), - ("test_reasons", lambda p: [r["reason"] for r in p] == reasons), - ("test_invoice_numbers", lambda p: [r["invoice_no"] for r in p] == [r["invoice_no"] for r in report]), - ("test_amounts", lambda p: all(isinstance(r["amount"], (int, float)) and not isinstance(r["amount"], bool) - and abs(r["amount"] - w["amount"]) <= 0.01 + 1e-9 - for r, w in zip(p, report, strict=True))), - ] - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="fraud_report.json", kind="checks", parse="json", checks=checks, render=render), - notes={"flagged": len(report), "invoices": len(invoices)}, - root="/root", - ) - - -FAMILIES = [ - Family("fin3_loan_schedule", "finance and economics", "Amortize a loan from the loan book", build_loan_schedule, - v3=True), - Family("fin3_portfolio_value", "finance and economics", "Value a brokerage account", build_portfolio_value, - v3=True), - Family("fin3_invoice_fraud", "finance and economics", "Screen invoices for fraud", build_invoice_fraud, v3=True), -] diff --git a/components/dnakhla/upstream/terminal_desk/families/industrial.py b/components/dnakhla/upstream/terminal_desk/families/industrial.py deleted file mode 100644 index 1e11d39acba7b614f79023715874e48f03f0fec2..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/families/industrial.py +++ /dev/null @@ -1,194 +0,0 @@ -"""Industrial and physical systems: integrate a flow log; find overdue maintenance.""" - -import datetime as dt -import random - -from .base import Artifact, Built, Family, Field - -# ---------------------------------------------------------------- ind_tank - - -def build_tank(level: int, rng: random.Random) -> Built: - n_rows = {1: 120, 2: 240, 3: 360}[level] - t = dt.datetime(2026, 11, 3, 6, 0, 0) - flow, lvl = rng.uniform(30, 60), rng.uniform(120, 160) - rows = [] - for i in range(n_rows): - flow = min(max(flow + rng.gauss(0, 2.5), 5.0), 95.0) - lvl = min(max(lvl + rng.gauss(0, 1.8), 80.0), 220.0) - status = "OK" - if level >= 2 and i > 2 and rng.random() < 0.035: - status = "FAULT" - f_out = round(flow, 2) if status == "OK" else rng.choice([0.0, 999.99, round(flow * 3, 2)]) - l_out = round(lvl, 1) if status == "OK" else rng.choice([0.0, 999.9]) - rows.append((t, f_out, l_out, status)) - step = 30 if level < 3 else rng.choice([10, 20, 30, 30, 60]) - t += dt.timedelta(seconds=step) - good = [r for r in rows if r[3] == "OK"] - levels = sorted(r[2] for r in good) - threshold = round(levels[int(len(levels) * rng.uniform(0.6, 0.75))], 0) - cal_time = None - if level == 3: - cal_time = good[len(good) // 2 + rng.randint(-20, 20)][0] - - def corrected(r): - return r[1] / 1.04 if cal_time is not None and r[0] < cal_time else r[1] - - total = 0.0 - for a, b in zip(good, good[1:]): - total += (corrected(a) + corrected(b)) / 2 * (b[0] - a[0]).total_seconds() / 60 - longest, run_start = 0.0, None - for r in good: - if r[2] > threshold: - if run_start is None: - run_start = r[0] - longest = max(longest, (r[0] - run_start).total_seconds() / 60) - else: - run_start = None - csv = "time,flow_lpm,level_cm,status\n" + "".join( - f"{r[0]:%H:%M:%S},{r[1]:.2f},{r[2]:.1f},{r[3]}\n" for r in rows - ) - files = {"tank_log.csv": csv} - rules = [ - "flow_lpm is the inflow in litres per minute; level_cm is the tank level.", - ] - if level >= 2: - rules.append("Rows with status FAULT are sensor glitches: drop them before any calculation.") - if cal_time is not None: - files["maintenance_note.txt"] = ( - f"Flow meter recalibrated at {cal_time:%H:%M:%S}. Readings taken before that time read 4% high: " - "divide them by 1.04. Readings from that time on are correct.\n" - ) - rules.append("Read maintenance_note.txt.") - instruction = ( - "/app/tank_log.csv is one morning of a holding tank's sensor log. " + " ".join(rules) + " " - "Total inflow is the trapezoid-rule integral of flow over time between consecutive rows (after any " - "dropping). A high stretch is a maximal run of consecutive rows (after any dropping) with level_cm " - f"strictly above {threshold:.0f}; its length runs from its first to its last row. " - 'Write /app/tank_report.json with the keys total_liters (litres) and longest_high_minutes (minutes), ' - 'for example {"total_liters": 1234.5, "longest_high_minutes": 12.5}.' - ) - return Built( - instruction=instruction, - files=files, - artifact=Artifact( - path="tank_report.json", - kind="json", - expected={"total_liters": round(total, 3), "longest_high_minutes": round(longest, 4)}, - fields=[ - Field("total_liters", "number", "total inflow in litres", tol=0.5, rel=0.002), - Field("longest_high_minutes", "number", "length of the longest high stretch in minutes", tol=0.01), - ], - ), - ) - - -# ---------------------------------------------------------------- ind_maint - -TYPES = {"press": (250, 30), "lathe": (400, 45), "pump": (1000, 90), "conveyor": (600, 60)} - - -def build_maint(level: int, rng: random.Random) -> Built: - n_mach, n_days = {1: (6, 20), 2: (10, 45), 3: (12, 60)}[level] - while True: - asof = dt.date(2026, 10, 31) - start = asof - dt.timedelta(days=n_days - 1) - end = asof + (dt.timedelta(days=3) if level >= 2 else dt.timedelta(0)) - machines, readings, since = [], [], {} - swapped = None - swap_id = None - ids = [f"M{i:02d}" for i in range(1, n_mach + 1)] - if level == 3: - swap_id = rng.choice(ids) - for mid in ids: - mtype = rng.choice(sorted(TYPES)) - hours_cap, days_cap = TYPES[mtype] - meter = round(rng.uniform(500, 20000), 1) - daily = rng.uniform(2, 20) - service_day = start + dt.timedelta(days=rng.randint(0, n_days - 5)) - swap_day = None - if mid == swap_id: - swap_day = service_day + dt.timedelta(days=rng.randint(2, (asof - service_day).days)) - day, at_service, old_last, latest = start, None, None, None - while day <= end: - if day == swap_day: - old_last = meter - meter = 0.0 - meter = round(meter + max(0.0, rng.gauss(daily, daily * 0.3)), 1) - if day == service_day: - at_service = meter - protected = (service_day, swap_day, swap_day - dt.timedelta(days=1) if swap_day else None) - missing = level >= 2 and day not in protected and rng.random() < 0.1 - if not missing: - readings.append((day, mid, meter)) - if day <= asof: - latest = meter - day += dt.timedelta(days=1) - if swap_day is not None: - hours = old_last - at_service + latest - swapped = (mid, swap_day) - else: - hours = latest - at_service - days_since = (asof - service_day).days - overdue = hours >= hours_cap or days_since >= days_cap - since[mid] = (hours, overdue) - machines.append((mid, mtype, service_day, at_service)) - ranked = sorted(since.items(), key=lambda kv: -kv[1][0]) - if ranked[0][1][0] - ranked[1][1][0] < 1.0: - continue - overdue = sorted(m for m, (_, o) in since.items() if o) - if 0 < len(overdue) < n_mach: - break - rng.shuffle(readings) - readings.sort(key=lambda r: (r[0], rng.random())) - files = { - "machines.csv": "machine,type,last_service_date,meter_at_service\n" - + "".join(f"{m},{t},{d.isoformat()},{h:.1f}\n" for m, t, d, h in machines), - "meter_readings.csv": "date,machine,meter_hours\n" - + "".join(f"{d.isoformat()},{m},{h:.1f}\n" for d, m, h in readings), - "policy.txt": "Service interval by machine type (whichever limit comes first):\n" - + "".join(f" {t}: every {h} run-hours or {d} days\n" for t, (h, d) in sorted(TYPES.items())), - } - notes = [ - "meter_readings.csv holds end-of-day cumulative meter readings.", - "Use each machine's latest reading on or before the as-of date.", - ] - if swapped: - files["shift_log.txt"] = ( - f"{swapped[1].isoformat()}: {swapped[0]} hour meter failed and was replaced at the start of the day. " - "The new meter started from 0.0; its readings from that day on count up from zero. The old meter's " - "last reading is the one from the previous day.\n" - ) - notes.append("Check shift_log.txt.") - instruction = ( - "As of 2026-10-31, work out which machines in /app/machines.csv are due for service from " - "/app/meter_readings.csv and /app/policy.txt. Run-hours since service = meter now minus " - "meter_at_service. A machine is due when that reaches its type's hour limit or the days since its last " - "service (as-of date minus service date) reach its day limit. " + " ".join(notes) + " " - "Write /app/service_schedule.csv with the header machine,run_hours_since_service,due and one row per " - "machine, due being yes or no, e.g. M01,153.4,no" - ) - return Built( - instruction=instruction, - files=files, - artifact=Artifact( - path="service_schedule.csv", - kind="csv", - key=("machine",), - fields=[ - Field("machine", "text"), - Field("run_hours_since_service", "number", tol=0.15), - Field("due", "text"), - ], - expected=[ - {"machine": m, "run_hours_since_service": round(h, 1), "due": "yes" if o else "no"} - for m, (h, o) in sorted(since.items()) - ], - ), - ) - - -FAMILIES = [ - Family("ind_tank", "industrial and physical systems", "Integrate a tank flow log", build_tank), - Family("ind_maint", "industrial and physical systems", "Find machines due for service", build_maint), -] diff --git a/components/dnakhla/upstream/terminal_desk/families/industrial3.py b/components/dnakhla/upstream/terminal_desk/families/industrial3.py deleted file mode 100644 index a8016c0c2e22d1763e9e2e0415e30b2a91d2e14f..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/families/industrial3.py +++ /dev/null @@ -1,470 +0,0 @@ -"""Industrial and physical systems, v3: service-due report, tank balance, STL part mass. - -ind3_service_due reshapes industrial.build_maint (hour meters against service intervals) as a /root csv report. -ind3_tank_balance reshapes industrial.build_tank (trapezoid flow integral, high-level stretch) as a tank balance. -ind3_stl_mass is new, modeled on SkillsBench 3d-scan-calc: signed-tetrahedron volume of an ASCII STL. - -All three are stdlib-only. Everything an instance needs beyond the fixed rules lives in its files, because the -family's one oracle script (terminal_desk/oracles/.py) cannot read the instruction. -""" - -import datetime as dt -import json -import math -import random - -from .base import Artifact, Built, Family -from .industrial import TYPES # press (250 h, 30 d), lathe (400, 45), pump (1000, 90), conveyor (600, 60) - -DOMAIN = "industrial and physical systems" - - -def _close(got, want: float, tol: float) -> bool: - return not isinstance(got, bool) and abs(float(got) - want) <= tol + 1e-9 - - -def _rel(got, want: float, rel: float = 1e-3) -> bool: - return not isinstance(got, bool) and abs(float(got) - want) <= rel * abs(want) + 1e-12 - - -# ---------------------------------------------------------------- ind3_service_due - -ASOF = dt.date(2026, 10, 31) # fixed: the oracle script cannot read the instruction -SERVICE_HEADER = ["machine", "run_hours_since_service", "days_since_service", "due"] - - -def _service_instance(level: int, rng: random.Random): - """One draw; None when the draw misses a constraint (the caller redraws).""" - n_mach, n_days = {1: (6, 20), 2: (9, 30), 3: (12, 40)}[level] - start = ASOF - dt.timedelta(days=n_days - 1) - end = ASOF + dt.timedelta(days=3 if level >= 2 else 0) - ids = [f"M{i:02d}" for i in range(1, n_mach + 1)] - resvc = rng.choice(ids) if level >= 2 else None - swap_id = rng.choice([m for m in ids if m != resvc]) if level == 3 else None - exact = rng.choice([m for m in ids if m not in (resvc, swap_id)]) # its days land exactly on the limit - machines, readings, want, notes = [], [], {}, [] - for mid in ids: - mtype = rng.choice(sorted(TYPES)) - hcap, dcap = TYPES[mtype] - swap_day = ASOF - dt.timedelta(days=rng.randint(3, n_days - 3)) if mid == swap_id else None - if mid == exact: - last = ASOF - dt.timedelta(days=dcap) - elif swap_day is not None: - last = swap_day - dt.timedelta(days=rng.randint(2, 60)) - else: - last = ASOF - dt.timedelta(days=rng.randint(5, int(dcap * 1.3))) - listed = last - dt.timedelta(days=rng.randint(20, 120)) if mid == resvc else last - daily = rng.uniform(2, 20) - meter = round(rng.uniform(500, 20000), 1) - at, day, old_last, recs = {}, min(listed, start), None, [] - while day <= end: - if day == swap_day: - old_last = meter - meter = 0.0 - meter = round(meter + max(0.0, rng.gauss(daily, daily * 0.3)), 1) - if day in (listed, last): - at[day] = meter - protected = swap_day is not None and day == swap_day - dt.timedelta(days=1) - if day >= start and (protected or level == 1 or rng.random() >= 0.1): - recs.append((day, meter)) - day += dt.timedelta(days=1) - readings += [(d, mid, v) for d, v in recs] - upto = [(d, v) for d, v in recs if d <= ASOF] - if not upto or upto[-1][0] <= last: - return None - if swap_day is not None: - if upto[-1][0] < swap_day or old_last is None: - return None - hours = old_last - at[last] + upto[-1][1] - else: - hours = upto[-1][1] - at[last] - hours = round(hours, 1) - if abs(hours - hcap) < 0.05: - return None - days = (ASOF - last).days - want[mid] = (hours, days, hours >= hcap, days >= dcap) - machines.append((mid, mtype, listed, at[listed])) - if mid == resvc: - notes.append(f"- {last.isoformat()}: {mid} was serviced again; its hour meter read {at[last]:.1f} at " - "the end of that day. machines.csv still shows the previous service.") - if mid == swap_id: - swap = (mid, swap_day) - due = [m for m, (_, _, h, d) in want.items() if h or d] - by_hours = [m for m, (_, _, h, d) in want.items() if h and not d] - by_days = [m for m, (_, _, h, d) in want.items() if d and not h] - if not (2 <= len(due) <= n_mach - 2 and by_hours and by_days): - return None - readings.sort(key=lambda r: (r[0], rng.random())) - files = { - "data/machines.csv": "machine,type,last_service_date,meter_at_service\n" - + "".join(f"{m},{t},{d.isoformat()},{h:.1f}\n" for m, t, d, h in machines), - "data/meter_readings.csv": "date,machine,meter_hours\n" - + "".join(f"{d.isoformat()},{m},{v:.1f}\n" for d, m, v in readings), - "data/service_intervals.csv": "type,max_run_hours,max_days\n" - + "".join(f"{t},{h},{d}\n" for t, (h, d) in sorted(TYPES.items())), - } - if level >= 2: - other = rng.choice([m for m in ids if m != resvc]) - day = ASOF - dt.timedelta(days=rng.randint(1, 15)) - notes.append(f"- {day.isoformat()}: {other} coolant topped up and guards checked; no service performed.") - rng.shuffle(notes) - files["data/notes.md"] = "# Shop floor notes\n\n" + "\n".join(notes) + "\n" - if level == 3: - other = rng.choice([m for m in ids if m != swap[0]]) - day = ASOF - dt.timedelta(days=rng.randint(1, n_days - 1)) - log = [ - f"{swap[1].isoformat()}: {swap[0]} hour meter failed and was replaced at the start of the day. The new " - "meter started from 0.0; its readings from that day on count up from zero. The old meter's last " - "reading is the one from the previous day.", - f"{day.isoformat()}: {other} spindle noise reported on the night shift; inspected, no fault found, " - "meter unchanged.", - ] - rng.shuffle(log) - files["data/shift_log.txt"] = "\n".join(log) + "\n" - return files, want - - -def build_service_due(level: int, rng: random.Random) -> Built: - while True: - drawn = _service_instance(level, rng) - if drawn is not None: - break - files, want = drawn - opener = rng.choice([ - "You are preparing a machine shop's service report as of 2026-10-31.", - "Our machine shop needs its service-due report as of 2026-10-31.", - ]) - extra = {1: "", 2: " Apply /root/data/notes.md.", 3: " Apply /root/data/notes.md and /root/data/shift_log.txt."} - instruction = ( - f"{opener} /root/data/machines.csv lists each machine's type, last_service_date and meter_at_service " - "(the hour meter at that service). /root/data/meter_readings.csv holds end-of-day cumulative " - "hour-meter readings, and /root/data/service_intervals.csv gives each type's limits.\n\n" - "For every machine:\n" - "1. Take its latest reading dated on or before 2026-10-31; days can be missing.\n" - "2. run_hours_since_service = that reading minus meter_at_service.\n" - "3. days_since_service = 2026-10-31 minus the last service date.\n" - "4. It is due when run-hours reach max_run_hours or days reach max_days, whichever comes first; " - f"exactly reaching a limit counts.{extra[level]}\n\n" - "Write /root/service_report.csv with the header machine,run_hours_since_service,days_since_service,due, " - "one row per machine sorted by machine, run-hours to 1 decimal and due as yes or no, e.g. M01,153.4,40,no. " - "Run-hours are checked within 0.05." - ) - ids = sorted(want) - rows = {m: (f"{h:.1f}", d, "yes" if a or b else "no") for m, (h, d, a, b) in want.items()} - - def render() -> str: - return ",".join(SERVICE_HEADER) + "\n" + "".join(f"{m},{h},{d},{u}\n" for m, (h, d, u) in sorted(rows.items())) - - checks = [ - ("test_header", lambda p: p["header"] == SERVICE_HEADER), - ("test_row_count", lambda p: len(p["rows"]) == len(ids)), - ("test_machine_order", lambda p: [r["machine"] for r in p["rows"]] == ids), - ("test_run_hours", lambda p: all(_close(r["run_hours_since_service"], want[r["machine"]][0], 0.05) - for r in p["rows"])), - ("test_days_since_service", lambda p: all(float(r["days_since_service"]) == want[r["machine"]][1] - for r in p["rows"])), - ("test_due", lambda p: all(r["due"] == rows[r["machine"]][2] for r in p["rows"])), - ] - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="service_report.csv", kind="checks", parse="csv", checks=checks, render=render), - root="/root", - ) - - -# ---------------------------------------------------------------- ind3_tank_balance - - -def _tank_rows(level: int, rng: random.Random): - n_rows = {1: 120, 2: 240, 3: 360}[level] - t = dt.datetime(2026, 11, 3, rng.randint(5, 8), rng.choice((0, 15, 30, 45)), 0) - fin, fout, lvl = rng.uniform(35, 60), rng.uniform(30, 55), rng.uniform(120, 160) - rows = [] - for i in range(n_rows): - fin = min(max(fin + rng.gauss(0, 2.5), 5.0), 95.0) - fout = min(max(fout + rng.gauss(0, 2.5), 5.0), 95.0) - lvl = min(max(lvl + rng.gauss(0, 1.8), 80.0), 220.0) - if level >= 2 and 2 < i < n_rows - 1 and rng.random() < 0.04: - rows.append((t, rng.choice((0.0, 999.9)), rng.choice((0.0, 999.9)), rng.choice((0.0, 999.9)), "FAULT")) - else: - rows.append((t, round(fin, 1), round(fout, 1), round(lvl, 1), "OK")) - t += dt.timedelta(seconds=30 if level < 3 else rng.choice((10, 20, 30, 30, 60))) - return rows - - -def _trapezoid(pts) -> float: - """pts: [(datetime, flow_lpm)] -> litres.""" - return sum((a[1] + b[1]) / 2 * (b[0] - a[0]).total_seconds() / 60 for a, b in zip(pts, pts[1:])) - - -def build_tank_balance(level: int, rng: random.Random) -> Built: - while True: - rows = _tank_rows(level, rng) - good = [r for r in rows if r[4] == "OK"] - cal, pct = None, rng.choice((3, 4, 5, 6)) - if level == 3: - cal = good[len(good) // 2 + rng.randint(-20, 20)][0] - - def inflow(r): - return r[1] / (1 + pct / 100) if cal is not None and r[0] < cal else r[1] - - fin = [(r[0], inflow(r)) for r in good] - total_in, total_out = _trapezoid(fin), _trapezoid([(r[0], r[2]) for r in good]) - minutes = (good[-1][0] - good[0][0]).total_seconds() / 60 - left = sum(a[1] * (b[0] - a[0]).total_seconds() / 60 for a, b in zip(fin, fin[1:])) - right = sum(b[1] * (b[0] - a[0]).total_seconds() / 60 for a, b in zip(fin, fin[1:])) - mean = sum(f for _, f in fin) / len(fin) * minutes - if min(abs(total_in - x) for x in (left, right, mean)) < 0.5: - continue # a wrong integration rule must not land inside the tolerance - levels = sorted(r[3] for r in good) - alarm = int(levels[int(len(levels) * rng.uniform(0.6, 0.75))]) - longest, run_start = 0.0, None - for r in good: - if r[3] > alarm: - run_start = r[0] if run_start is None else run_start - longest = max(longest, (r[0] - run_start).total_seconds() / 60) - else: - run_start = None - if level == 1 or longest > 0: - break - want = {"inflow_liters": total_in, "outflow_liters": total_out, "net_liters": total_in - total_out} - if level >= 2: - want["longest_high_minutes"] = longest - status = level >= 2 - files = { - "data/tank_log.csv": "time,inflow_lpm,outflow_lpm,level_cm" + (",status" if status else "") + "\n" - + "".join(f"{r[0]:%H:%M:%S},{r[1]:.1f},{r[2]:.1f},{r[3]:.1f}" + (f",{r[4]}" if status else "") + "\n" - for r in rows), - } - if level >= 2: - files["data/README.md"] = ( - "# Tank T-4 log notes\n\n" - "- Rows with status FAULT are sensor glitches and their readings are meaningless. Drop them before any " - "calculation; the rows on either side of a dropped row then count as consecutive.\n" - f"- The high-level alarm setpoint is {alarm} cm.\n" - "- The outlet meter was replaced in spring and reads true.\n" - ) - if cal is not None: - files["data/maintenance_note.txt"] = ( - f"Inlet flow meter recalibrated at {cal:%H:%M:%S}. Inflow readings taken before that time read {pct}% " - f"high: divide them by 1.0{pct}. Readings from that time on, and all outflow readings, are correct.\n" - ) - cols = "time (HH:MM:SS), inflow_lpm and outflow_lpm (litres per minute) and level_cm" + ( - ", plus a status column" if status else "") - notes = {1: "", 2: " Read /root/data/README.md first.", - 3: " Read /root/data/README.md and /root/data/maintenance_note.txt first."}[level] - opener = rng.choice([ - "You are checking the water balance of a holding tank over one morning shift.", - "The plant team wants a flow balance for holding tank T-4 over this morning's shift.", - ]) - steps = ( - "1. inflow_liters and outflow_liters: the trapezoid-rule integral of each flow over time, i.e. for every " - "pair of consecutive rows add the average of their two flows times the minutes between them.\n" - "2. net_liters = inflow_liters minus outflow_liters.\n" - ) - example = '"inflow_liters": 2710.45, "outflow_liters": 2532.1, "net_liters": 178.35' - if level >= 2: - steps += ("3. longest_high_minutes: the longest run of consecutive rows with level_cm strictly above the " - "high-level alarm setpoint, from its first to its last row (0 if none).\n") - example += ', "longest_high_minutes": 12.5' - instruction = ( - f"{opener} /root/data/tank_log.csv has one row per sample: {cols}.{notes}\n\n{steps}\n" - f"Write /root/tank_report.json as one JSON object, for example {{{example}}}. Round to 2 decimals; " - "litres are checked within 0.05" + (" and minutes within 0.01." if level >= 2 else ".") - ) - - def render() -> str: - return json.dumps({k: round(v, 2) for k, v in want.items()}) + "\n" - - checks = [ - ("test_is_object", lambda p: isinstance(p, dict)), - ("test_keys", lambda p: set(p) == set(want)), - ("test_inflow_liters", lambda p: _close(p["inflow_liters"], want["inflow_liters"], 0.05)), - ("test_outflow_liters", lambda p: _close(p["outflow_liters"], want["outflow_liters"], 0.05)), - ("test_net_liters", lambda p: _close(p["net_liters"], want["net_liters"], 0.05)), - ] - if level >= 2: - checks.append(("test_longest_high_minutes", - lambda p: _close(p["longest_high_minutes"], want["longest_high_minutes"], 0.01))) - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="tank_report.json", kind="checks", parse="json", checks=checks, render=render), - root="/root", - ) - - -# ---------------------------------------------------------------- ind3_stl_mass - -MATERIALS = [ - ("PLA", "PLA filament", 1.24), ("PETG", "PETG filament", 1.27), ("ABS", "ABS filament", 1.04), - ("ASA", "ASA filament", 1.07), ("PA12", "nylon 12 powder", 1.01), ("PC", "polycarbonate", 1.20), - ("AL6061", "aluminium 6061", 2.70), ("SS316L", "stainless steel 316L", 7.98), ("TI64", "titanium Ti-6Al-4V", 4.43), - ("IN718", "Inconel 718", 8.19), ("CUCRZR", "copper CuCrZr", 8.89), ("MS1", "maraging steel MS1", 8.10), -] - - -def _cross(a, b): - return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]) - - -def _prism(rng: random.Random, n: int, bands: int, radius: float, height: float, center, scale: float, inward: bool): - """A closed star-shaped prism: fan-triangulated caps, side walls split into `bands` strips. - Vertices are rounded as written, so every expected value comes from the file's own numbers.""" - cx, cy, z0 = center - phase = rng.uniform(0, 2 * math.pi) - ring = [] - for i in range(n): - a, r = phase + 2 * math.pi * i / n, radius * rng.uniform(0.7, 1.0) - ring.append((cx + r * math.cos(a), cy + r * math.sin(a))) - - def q(x, y, z): - return (round(x / scale, 4), round(y / scale, 4), round(z / scale, 4)) - - zs = [z0 + height * j / bands for j in range(bands + 1)] - p = [[q(x, y, z) for z in zs] for x, y in ring] - top, bot = q(cx, cy, zs[-1]), q(cx, cy, zs[0]) - tris = [] - for i in range(n): - k = (i + 1) % n - tris.append((top, p[i][bands], p[k][bands])) - tris.append((bot, p[k][0], p[i][0])) - for j in range(bands): - tris.append((p[i][j], p[k][j], p[k][j + 1])) - tris.append((p[i][j], p[k][j + 1], p[i][j + 1])) - if inward: - tris = [(a, c, b) for a, b, c in tris] - return tris - - -def _measure(tris): - vol = sum(sum(x * y for x, y in zip(a, _cross(b, c))) for a, b, c in tris) / 6 - area = 0.0 - for a, b, c in tris: - n = _cross([j - i for i, j in zip(a, b)], [j - i for i, j in zip(a, c)]) - area += math.sqrt(sum(x * x for x in n)) / 2 - return vol, area - - -def _stl_solid(name: str, code: str, tris) -> str: - out = [f"solid {name} {code}"] - for a, b, c in tris: - n = _cross([j - i for i, j in zip(a, b)], [j - i for i, j in zip(a, c)]) - m = math.sqrt(sum(x * x for x in n)) - if m == 0: - raise ValueError(f"degenerate facet in solid {name}: {a} {b} {c}") - out.append(" facet normal " + " ".join(f"{x / m:.4f}" for x in n)) - out.append(" outer loop") - out += [f" vertex {v[0]:.4f} {v[1]:.4f} {v[2]:.4f}" for v in (a, b, c)] - out += [" endloop", " endfacet"] - out.append(f"endsolid {name}") - return "\n".join(out) + "\n" - - -def build_stl_mass(level: int, rng: random.Random) -> Built: - inches = level == 3 - scale = 25.4 if inches else 1.0 - # L1 draws in exactly the order the first merged version did, so L1 instances are unchanged. - while True: - count = {1: 1, 2: rng.randint(3, 4), 3: 5}[level] - names = [f"body{k}" for k in rng.sample(range(1, 10), count)] - roles = ["part", "offcut", "trap"][: {1: 1, 2: 2, 3: 3}[level]] - roles += ["debris"] * (count - len(roles)) - solids = [] # (name, code, tris) - for role, name in zip(roles, names): - code = rng.choice(MATERIALS)[0] - center = (rng.uniform(10, 90), rng.uniform(10, 90), rng.uniform(0, 20)) - if role in ("part", "offcut"): # the offcut draws its facet count like the part: more about half the time - n, bands = (rng.randint(10, 13), 2) if level < 3 else (rng.randint(10, 12), 2) - if level == 2: - n, bands = rng.randint(14, 18), rng.randint(2, 3) - if role == "part": - radius, height = rng.uniform(15, 40), rng.uniform(8, 40) - size = (radius, height) - else: - size = (radius * rng.uniform(0.6, 0.8), height * rng.uniform(0.6, 0.9)) - tris = _prism(rng, n, bands, *size, center, scale, rng.random() < 0.5) - elif role == "trap": # more facets than the part, far less volume - tris = _prism(rng, rng.randint(26, 32), rng.randint(3, 4), rng.uniform(4, 6), rng.uniform(3, 5), - center, scale, rng.random() < 0.5) - else: # fixture pieces and debris - tris = _prism(rng, rng.randint(4, 6), 1, rng.uniform(1.5, 4), rng.uniform(1, 4), center, scale, - rng.random() < 0.3) - solids.append((name, code, tris)) - vols = [abs(_measure(t)[0]) for _, _, t in solids] - small = all(vols[0] > 3 * v for r, v in zip(roles[1:], vols[1:]) if r != "offcut") - offcut = level == 1 or 0.3 <= vols[1] / vols[0] <= 0.6 - if small and offcut and len({s[1] for s in solids}) == len(solids): - break - if level == 3: - assert len(solids[2][2]) > len(solids[0][2]) - part_name, part_code, part_tris = solids[0] - vol, area = _measure(part_tris) - k = 2.54 if inches else 0.1 # file units -> cm - density = dict((c, d) for c, _, d in MATERIALS)[part_code] - volume_cm3, area_cm2 = abs(vol) * k ** 3, area * k ** 2 - want = {"solid": part_name, "material": part_code, "volume_cm3": volume_cm3, "area_cm2": area_cm2, - "mass_g": volume_cm3 * density} - order = solids[:] - rng.shuffle(order) - table = rng.sample(MATERIALS, 8) - for _, code, _ in solids: - if code not in {c for c, _, _ in table}: - table.append(next(m for m in MATERIALS if m[0] == code)) - rng.shuffle(table) - files = { - "data/scan.stl": "".join(_stl_solid(*s) for s in order), - "data/materials.csv": "code,name,density_g_cm3\n" + "".join(f"{c},{n},{d:.2f}\n" for c, n, d in table), - } - if level >= 2: - notes = ("# Scan notes\n\nThe scanner exported every closed surface it found as its own solid: the part, plus " - "an offcut from another job, fixture pieces and loose debris picked up on the bed. Only the part " - "matters. The part is the solid with the largest enclosed volume; ignore the other solids entirely.\n") - if inches: - notes += "\nThis scan was exported in inches, not millimetres (1 in = 2.54 cm). Convert before reporting.\n" - files["data/scan_notes.md"] = notes - opener = rng.choice([ - "You need to calculate the mass of a 3D printed part from its scan.", - "Our print shop needs the mass of a finished part, computed from its 3D scan.", - ]) - scope = ("The file holds one solid, the part." if level == 1 - else "Read /root/data/scan_notes.md and apply it; it overrides anything above.") - instruction = ( - f"{opener} /root/data/scan.stl is an ASCII STL: each solid opens with a line `solid ` " - "and lists triangular facets as three `vertex x y z` lines, coordinates in millimetres. " - f"/root/data/materials.csv gives each material code's density in g/cm3. {scope}\n\n" - "For the part:\n" - "1. volume: the sum of v1 . (v2 x v3) / 6 over its facets (signed tetrahedra), then the absolute value, " - "because some exports wind facets inward.\n" - "2. surface area: the sum of |(v2 - v1) x (v3 - v1)| / 2 over its facets.\n" - "3. mass = volume in cm3 times the density.\n\n" - 'Write /root/mass_report.json like {"solid": "body2", "material": "PA12", "volume_cm3": 41.268, ' - '"area_cm2": 98.41, "mass_g": 41.68}. Numbers are checked within 0.1% (relative); names exactly.' - ) - - def render() -> str: - return json.dumps(want) + "\n" - - checks = [ - ("test_is_object", lambda p: isinstance(p, dict)), - ("test_keys", lambda p: set(p) == set(want)), - ("test_solid", lambda p: p["solid"] == part_name), - ("test_material", lambda p: p["material"] == part_code), - ("test_volume_cm3", lambda p: _rel(p["volume_cm3"], volume_cm3)), - ("test_area_cm2", lambda p: _rel(p["area_cm2"], area_cm2)), - ("test_mass_g", lambda p: _rel(p["mass_g"], want["mass_g"])), - ] - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="mass_report.json", kind="checks", parse="json", checks=checks, render=render), - root="/root", - ) - - -FAMILIES = [ - Family("ind3_service_due", DOMAIN, "Report machines due for service", build_service_due, v3=True), - Family("ind3_tank_balance", DOMAIN, "Balance a tank's inflow and outflow", build_tank_balance, v3=True), - Family("ind3_stl_mass", DOMAIN, "Compute a scanned part's mass from an STL", build_stl_mass, v3=True), -] diff --git a/components/dnakhla/upstream/terminal_desk/families/mathematics.py b/components/dnakhla/upstream/terminal_desk/families/mathematics.py deleted file mode 100644 index 1aabf3275f834a56f767670694c6cd2482367ee3..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/families/mathematics.py +++ /dev/null @@ -1,177 +0,0 @@ -"""Math and formal reasoning: find a fastest route in a road graph; count integers under constraints.""" - -import heapq -import random - -from .base import Artifact, Built, Family, Field - -# ---------------------------------------------------------------- math_paths - - -def _dijkstra_count(nodes, edges, src, dst): - adj = {n: [] for n in nodes} - for u, v, w in edges: - adj[u].append((v, w)) - dist = {n: None for n in nodes} - ways = {n: 0 for n in nodes} - dist[src], ways[src] = 0, 1 - heap = [(0, src)] - done = set() - while heap: - d, u = heapq.heappop(heap) - if u in done: - continue - done.add(u) - for v, w in adj[u]: - nd = d + w - if dist[v] is None or nd < dist[v]: - dist[v], ways[v] = nd, ways[u] - heapq.heappush(heap, (nd, v)) - elif nd == dist[v]: - ways[v] += ways[u] - return dist[dst], ways[dst] - - -def _dijkstra_path(nodes, edges, src, dst): - adj = {n: [] for n in nodes} - for u, v, w in edges: - adj[u].append((v, w)) - dist, prev = {src: 0}, {} - heap = [(0, src)] - while heap: - d, u = heapq.heappop(heap) - if d > dist[u]: - continue - for v, w in adj[u]: - if v not in dist or d + w < dist[v]: - dist[v], prev[v] = d + w, u - heapq.heappush(heap, (d + w, v)) - path = [dst] - while path[-1] != src: - path.append(prev[path[-1]]) - return path[::-1] - - -def build_paths(level: int, rng: random.Random) -> Built: - n_nodes, out_deg = {1: (8, 2), 2: (15, 3), 3: (25, 3)}[level] - while True: - nodes = [f"N{i:02d}" for i in range(1, n_nodes + 1)] - src, dst = nodes[0], nodes[-1] - edges, seen = [], set() - for u in nodes: - for v in rng.sample([x for x in nodes if x != u], out_deg): - if (u, v) not in seen: - seen.add((u, v)) - edges.append((u, v, rng.randint(1, 6))) - closed_edges, closed_nodes = set(), set() - if level == 3: - closed_edges = set(rng.sample([(u, v) for u, v, _ in edges], 6)) - closed_nodes = set(rng.sample(nodes[1:-1], 2)) - live = [ - (u, v, w) - for u, v, w in edges - if (u, v) not in closed_edges and u not in closed_nodes and v not in closed_nodes - ] - cost, ways = _dijkstra_count(nodes, live, src, dst) - if cost is None or ways < (1 if level == 1 else 2) or cost < 4: - continue - if level == 3: - full_cost, full_ways = _dijkstra_count(nodes, edges, src, dst) - if (full_cost, full_ways) == (cost, ways): - continue - break - rng.shuffle(edges) - files = {"roads.csv": "from,to,minutes\n" + "".join(f"{u},{v},{w}\n" for u, v, w in edges)} - extra = "" - if level == 3: - files["closures.txt"] = ( - "Closed roads (one way, from -> to):\n" - + "".join(f" {u} -> {v}\n" for u, v in sorted(closed_edges)) - + "Closed junctions (no road into or out of them can be used):\n" - + "".join(f" {n}\n" for n in sorted(closed_nodes)) - ) - extra = ", avoiding the closed roads and junctions in closures.txt" - instruction = ( - f"roads.csv lists one-way roads between junctions with their travel time in minutes. Find a fastest route " - f"from {src} to {dst}{extra}. " - f"Write the junction ids of the route in order, space separated, on one line in /app/route.txt, " - f"starting with {src} and ending with {dst}. Any fastest route is accepted." - ) - best_path = _dijkstra_path(nodes, live, src, dst) - live_w = {} - for u, v, w in live: - live_w[(u, v)] = min(w, live_w.get((u, v), w)) - - def verify(app: str) -> bool: - from ..core.grading import read_artifact # grading imports the families package - - data = read_artifact(app, "route.txt") - if data is None: - return False - route = data.decode("utf-8", errors="replace").split() - if len(route) < 2 or route[0] != src or route[-1] != dst: - return False - total = 0 - for u, v in zip(route, route[1:]): - if (u, v) not in live_w: - return False - total += live_w[(u, v)] - return total == cost - - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="route.txt", kind="custom", verify=verify, render=lambda: " ".join(best_path) + "\n"), - notes={"min_minutes": cost, "num_fastest_routes": ways}, - ) - - -# ---------------------------------------------------------------- math_count - - -def build_count(level: int, rng: random.Random) -> Built: - while True: - n = {1: rng.randint(5000, 20000), 2: rng.randint(50000, 200000), 3: rng.randint(400000, 900000)}[level] - a, b = rng.sample(range(3, 14), 2) - c = rng.choice([x for x in range(2, 10) if a % x and b % x]) - d = rng.randint(3, 7) - conds = [f"is divisible by {a} or by {b} (or both)", f"is not divisible by {c}"] - tests = [lambda x: x % a == 0 or x % b == 0, lambda x: x % c != 0] - if level >= 2: - conds.append(f"has a digit sum divisible by {d}") - tests.append(lambda x: sum(map(int, str(x))) % d == 0) - if level >= 3: - conds.append("is not a palindrome (reads differently backwards)") - conds.append("has no two equal adjacent digits") - tests.append(lambda x: str(x) != str(x)[::-1]) - tests.append(lambda x: all(p != q for p, q in zip(str(x), str(x)[1:]))) - hits = [x for x in range(1, n + 1) if all(t(x) for t in tests)] - if len(hits) >= 50: - break - k = rng.randint(len(hits) // 3, len(hits) - 1) - text = f"Consider the integers from 1 to {n} inclusive. Keep a number when it:\n" + "".join( - f" - {c_}\n" for c_ in conds - ) - instruction = ( - "problem.txt defines a set of integers. Write /app/results.json with three integer keys: " - f'"count" (how many integers are in the set), "kth_smallest" (the integer at position {k} when the set is sorted ascending, counting from 1) ' - 'and "largest" (the largest integer in the set).' - ) - expected = {"count": len(hits), "kth_smallest": hits[k - 1], "largest": hits[-1]} - return Built( - instruction=instruction, - files={"problem.txt": text}, - artifact=Artifact( - path="results.json", - kind="json", - expected=expected, - fields=[Field("count", "int"), Field("kth_smallest", "int"), Field("largest", "int")], - ), - notes=expected, - ) - - -FAMILIES = [ - Family("math_paths", "math and formal reasoning", "Count fastest routes", build_paths), - Family("math_count", "math and formal reasoning", "Count integers under constraints", build_count), -] diff --git a/components/dnakhla/upstream/terminal_desk/families/mathematics3.py b/components/dnakhla/upstream/terminal_desk/families/mathematics3.py deleted file mode 100644 index 5b3c24c95add634d79c7b6d84d9a2aa14d9cf2bb..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/families/mathematics3.py +++ /dev/null @@ -1,471 +0,0 @@ -"""Math and formal reasoning, v3: a fastest route under closures, counting raffle winners, exam-slot sequencing. - -Each verifier accepts any optimal answer: it replays the submitted route or schedule and compares its value -with the optimum the generator computed itself (SkillsBench pddl-tpp-planning, exam-block-sequencing). -""" - -import heapq -import itertools -import json -import random - -from .base import Artifact, Built, Family - -INF = float("inf") - - -def _is_int(x) -> bool: - return isinstance(x, int) and not isinstance(x, bool) - - -# ---------------------------------------------------------------- math3_route_plan - -CITIES = ("Northgate", "Riverton", "Ashford", "Millbrook", "Eastvale", "Harbor Point", "Kingsbridge") -VEHICLES = ("delivery van", "parts truck", "courier van", "service truck") -OPENERS = ( - "You are planning a {vehicle}'s route across {city}.", - "Our {city} dispatcher needs the fastest route for a {vehicle}.", - "You need the quickest route across {city} for a {vehicle}.", -) - - -def _earliest(adj: dict, src: str, windows: dict) -> tuple[dict, dict]: - """Earliest-arrival Dijkstra. windows[(u, v)] = (a, b): the road cannot be entered at a <= t < b; waiting is - allowed, so arrival times are FIFO and the label-setting search is exact.""" - best, prev, heap = {src: 0}, {}, [(0, src)] - while heap: - t, u = heapq.heappop(heap) - if t > best[u]: - continue - for v, w in adj.get(u, ()): - a, b = windows.get((u, v), (0, 0)) - arrive = (b if a <= t < b else t) + w - if arrive < best.get(v, INF): - best[v], prev[v] = arrive, u - heapq.heappush(heap, (arrive, v)) - return best, prev - - -def _adj(roads: dict) -> dict: - adj = {} - for (u, v), w in roads.items(): - adj.setdefault(u, []).append((v, w)) - return adj - - -def _trace(prev: dict, src: str, dst: str) -> list[str]: - path = [dst] - while path[-1] != src: - path.append(prev[path[-1]]) - return path[::-1] - - -def _route_instance(level: int, rng: random.Random): - n, deg, n_closed_roads, n_closed_nodes, n_timed = {1: (30, 3, 0, 0, 0), 2: (45, 3, 6, 2, 0), - 3: (60, 3, 6, 2, 8)}[level] - prefix = rng.choice("JNX") - nodes = [f"{prefix}{i:02d}" for i in range(1, n + 1)] - src, dst = rng.sample(nodes, 2) - roads = {} - for u in nodes: - for v in rng.sample([x for x in nodes if x != u], deg): - roads[(u, v)] = rng.randint(2, 15) - full, full_prev = _earliest(_adj(roads), src, {}) - if full.get(dst, 0) < 15: - return None - if level == 1: # the one-way caveat must bite: driving roads both ways finds a faster route - both = dict(roads) - for (u, v), w in roads.items(): - both[(v, u)] = min(w, both.get((v, u), INF)) - if _earliest(_adj(both), src, {})[0][dst] >= full[dst]: - return None - return nodes, src, dst, roads, set(), set(), {}, full[dst], _trace(full_prev, src, dst) - # closures: one junction and one road on the open optimum, the rest at random - on_path = _trace(full_prev, src, dst) - closed_nodes = {rng.choice(on_path[1:-1])} if len(on_path) > 2 else set() - while len(closed_nodes) < n_closed_nodes: - closed_nodes.add(rng.choice([x for x in nodes if x not in (src, dst)])) - closed_roads = {rng.choice(list(zip(on_path, on_path[1:])))} - while len(closed_roads) < n_closed_roads: - closed_roads.add(rng.choice(list(roads))) - live = {(u, v): w for (u, v), w in roads.items() - if (u, v) not in closed_roads and u not in closed_nodes and v not in closed_nodes} - static, static_prev = _earliest(_adj(live), src, {}) - if static.get(dst, 0) < 15 or static[dst] == full[dst]: - return None - if level == 2: - return nodes, src, dst, roads, closed_roads, closed_nodes, {}, static[dst], _trace(static_prev, src, dst) - # timed closures: two or three on the static optimum around the minute the van reaches them, the rest at random - path = _trace(static_prev, src, dst) - windows = {} - for u, v in rng.sample(list(zip(path, path[1:])), min(rng.randint(2, 3), len(path) - 1)): - t = static[u] - windows[(u, v)] = (max(0, t - rng.randint(0, 4)), t + rng.randint(4, 14)) - while len(windows) < n_timed: - a = rng.randint(0, 50) - windows.setdefault(rng.choice(list(live)), (a, a + rng.randint(5, 20))) - timed, timed_prev = _earliest(_adj(live), src, windows) - dropped = _earliest(_adj({k: w for k, w in live.items() if k not in windows}), src, {})[0] - if dst not in timed or timed[dst] == static[dst] or dropped.get(dst) == timed[dst]: - return None - return nodes, src, dst, roads, closed_roads, closed_nodes, windows, timed[dst], _trace(timed_prev, src, dst) - - -def build_route(level: int, rng: random.Random) -> Built: - for _ in range(500): - got = _route_instance(level, rng) - if got: - break - else: - raise RuntimeError(f"math3_route_plan L{level}: no instance in 500 draws") - nodes, src, dst, roads, closed_roads, closed_nodes, windows, best, best_path = got - city, vehicle = rng.choice(CITIES), rng.choice(VEHICLES) - depart = rng.choice(("06:45", "07:30", "08:00", "08:15", "09:00")) - order = list(roads) - rng.shuffle(order) - lines = [json.dumps({"from": u, "to": v, "minutes": roads[(u, v)]}) for u, v in order] - graph = '{"roads": [\n' + ",\n".join(lines) + '\n],\n"junctions": ' + json.dumps(sorted(nodes)) + "}\n" - files = { - "graph.json": graph, - "request.json": json.dumps({"vehicle": f"{vehicle} {rng.randint(2, 40)}", "from": src, "to": dst, - "depart": depart}) + "\n", - } - if level >= 2: - md = [f"# {city} closures, today", "", "## Closed roads (one way)"] - md += [f"- {u} -> {v}" for u, v in sorted(closed_roads)] - md += ["", "## Closed junctions"] + [f"- {x}" for x in sorted(closed_nodes)] - if windows: - md += ["", "## Timed closures"] - md += [f"- {u} -> {v}: closed from minute {a} to minute {b}" for (u, v), (a, b) in sorted(windows.items())] - files["closures.md"] = "\n".join(md) + "\n" - u0, v0 = rng.choice([(u, v) for u, v in order if (v, u) not in roads]) - ex = rng.sample([x for x in nodes if x not in (src, dst)], 3) # format only: not the requested endpoints - parts = [OPENERS[rng.randrange(3)].format(vehicle=vehicle, city=city), - "It must arrive as early as possible.\n", - "- /app/request.json: the start junction, the destination and the departure time.", - f"- /app/graph.json: each road's start junction, end junction and travel time in " - f"minutes. Roads are one-way: a road from {u0} to {v0} cannot be driven from {v0} to {u0}."] - if level >= 2: - timed_clause = " and timed closures" if windows else "" - parts.append(f"- /app/closures.md: today's closed roads, closed junctions{timed_clause}.\n") - rule = "A closed road, or any road into or out of a closed junction, cannot be used." - if windows: - rule += (" A timed-closure road cannot be entered while closed (minutes from departure), but the " - "vehicle may wait at a junction until it reopens; waiting counts toward the total.") - parts.append(rule) - parts.append(f"\nWrite /app/route.json with the junctions of the route in order and the total minutes from " - f'departure to arrival, e.g. {{"path": {json.dumps(ex)}, "total_minutes": {rng.randint(20, 60)}}}. ' - f"The path runs from the start to the destination on open roads, and total_minutes is the integer " - f"time it takes. Any fastest route is accepted.") - instruction = " ".join(parts[:2]) + "\n" + "\n".join(parts[2:]) - - live = {(u, v): w for (u, v), w in roads.items() - if (u, v) not in closed_roads and u not in closed_nodes and v not in closed_nodes} - - def replay(path: list) -> int: - t = 0 - for u, v in zip(path, path[1:]): - a, b = windows.get((u, v), (0, 0)) - t = (b if a <= t < b else t) + live[(u, v)] - return t - - checks = [ - ("test_is_object", lambda p: isinstance(p, dict)), - ("test_keys", lambda p: set(p) == {"path", "total_minutes"} and isinstance(p["path"], list) - and len(p["path"]) >= 2 and all(isinstance(x, str) for x in p["path"]) and _is_int(p["total_minutes"])), - ("test_endpoints", lambda p: p["path"][0] == src and p["path"][-1] == dst), - ("test_hops_open", lambda p: all((u, v) in live for u, v in zip(p["path"], p["path"][1:]))), - ("test_total_matches_path", lambda p: replay(p["path"]) == p["total_minutes"]), - ("test_total_optimal", lambda p: p["total_minutes"] == best), - ] - if replay(best_path) != best: - raise RuntimeError(f"math3_route_plan L{level}: generator path replays to {replay(best_path)}, not {best}") - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="route.json", kind="checks", parse="json", checks=checks, - render=lambda: json.dumps({"path": best_path, "total_minutes": best}) + "\n"), - notes={"src": src, "dst": dst, "min_minutes": best, "timed": len(windows)}, - root="/app", - ) - - -# ---------------------------------------------------------------- math3_count_items - -EVENTS = ("spring", "harvest", "winter", "founders' day", "summer fair", "library") -BOOTHS = ("A1", "A2", "B1", "B2", "B3", "C1", "C4", "D2") -VOID_REASONS = ("damaged", "unpaid", "duplicate print", "returned", "misprint") - - -def _count_instance(level: int, rng: random.Random): - n_rows = {1: 120, 2: 260, 3: 380}[level] - a, b = rng.sample(range(3, 14), 2) - c = rng.choice([x for x in range(2, 10) if a % x and b % x]) - d, m = rng.choice((3, 4, 5)), rng.randint(3, 9) - - def wins(x: int) -> bool: - if not (x % a == 0 or x % b == 0) or x % c == 0: - return False - return level == 1 or sum(map(int, str(x))) % d == 0 - - numbers, seen = [], set() - while len(numbers) < n_rows: - if level >= 2 and numbers and rng.random() < 0.07: - numbers.append(rng.choice(numbers)) # a reprint: the same number on a second ticket - continue - base = rng.choice((a, b)) - x = rng.randrange(100000 // base + 1, 999999 // base + 1) * base if rng.random() < 0.6 else \ - rng.randint(100000, 999999) - if x not in seen: - seen.add(x) - numbers.append(x) - tickets = [(f"T{i:04d}", x, rng.choice(BOOTHS)) for i, x in enumerate(numbers, 1)] - voided = {t for t, _, _ in rng.sample(tickets, n_rows // 12)} if level >= 3 else set() - alive = [x for t, x, _ in tickets if t not in voided] - winners = sorted({x for x in alive if wins(x)}) - if len(winners) < 20: - return None - # each caveat must change the answer - if level >= 2 and len([x for x in numbers if wins(x)]) == len({x for x in numbers if wins(x)}): - return None # no winning reprint: counting tickets would equal counting numbers - if level >= 3: - voided_wins = [x for t, x, _ in tickets if t in voided and wins(x)] - if not any(x not in alive for x in voided_wins) or not any(x in alive for x in voided_wins): - return None # need a voided winner that is gone and one that survives on its reprint - k = rng.randint(max(2, len(winners) // 4), len(winners) - 1) - residues = [0] * m - for x in winners: - residues[x % m] += 1 - pairs = residues[0] * (residues[0] - 1) // 2 + sum( - residues[r] * residues[m - r] for r in range(1, (m + 1) // 2)) - if m % 2 == 0: - pairs += residues[m // 2] * (residues[m // 2] - 1) // 2 - expected = {"count": len(winners), "kth_smallest": winners[k - 1], "largest": winners[-1]} - draw = {"draw": "", "divisors": [a, b], "excluded_divisor": c, "rank": k} - if level >= 2: - expected["pairs"] = pairs - draw.update(digit_sum_divisor=d, pair_modulus=m) - return draw, tickets, voided, expected - - -def build_count(level: int, rng: random.Random) -> Built: - for _ in range(500): - got = _count_instance(level, rng) - if got: - break - else: - raise RuntimeError(f"math3_count_items L{level}: no instance in 500 draws") - draw, tickets, voided, expected = got - event = rng.choice(EVENTS) - draw["draw"] = f"{event} raffle {rng.choice((2025, 2026))}" - files = {"data/tickets.csv": "ticket,number,booth\n" + "".join(f"{t},{x},{bo}\n" for t, x, bo in tickets), - "data/draw.json": "{\n" + ",\n".join(f' "{k}": {json.dumps(v)}' for k, v in draw.items()) + "\n}\n"} - if voided: - files["data/voided.csv"] = "ticket,reason\n" + "".join( - f"{t},{rng.choice(VOID_REASONS)}\n" for t in sorted(voided)) - head = (f"The {event} raffle sold {len(tickets)} tickets and the committee needs the prize figures. " - f"/root/data/tickets.csv has one row per ticket: ticket id, six-digit number and selling booth. " - f"/root/data/draw.json holds this draw's settings.") - rule = "its number is divisible by at least one of divisors and not by excluded_divisor" - rank = "kth_smallest (the winning number at position rank in ascending order, counting from 1)" - if level == 1: - body = (f" Every ticket carries a different number.\n\nA ticket wins when {rule}.\n\n" - f"Write /root/results.json with three integer keys: count (the number of winning tickets), {rank} " - f"and largest (the largest winning number).") - example = {"count": 31, "kth_smallest": 402115, "largest": 987350} - else: - void = " /root/data/voided.csv lists cancelled tickets; leave those tickets out." if voided else "" - after = " among the tickets that are not voided" if voided else "" - body = (f"{void}\n\nA ticket wins when {rule}, and its digit sum is divisible by " - f"digit_sum_divisor. Some numbers were printed on more than one ticket: count each winning number " - f"once{after}.\n\nWrite /root/results.json with four integer keys: count (distinct winning " - f"numbers), {rank}, largest (the largest winning number) and pairs (unordered pairs of different " - f"winning numbers whose sum is divisible by pair_modulus).") - example = {"count": 31, "kth_smallest": 402115, "largest": 987350, "pairs": 96} - instruction = head + body + f" For example: {json.dumps(example)}. Values are compared exactly." - keys = list(expected) - checks = [("test_is_object", lambda p: isinstance(p, dict)), - ("test_keys", lambda p: set(p) == set(keys) and all(_is_int(p[x]) for x in keys))] - checks += [(f"test_{key}", lambda p, key=key: p[key] == expected[key]) for key in keys] - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="results.json", kind="checks", parse="json", checks=checks, - render=lambda: json.dumps(expected) + "\n"), - notes=dict(expected), - root="/root", - ) - - -# ---------------------------------------------------------------- math3_exam_slots - -DEPTS = ("CHEM", "MATH", "PHYS", "BIOL", "HIST", "ECON", "PSYC", "ENGL", "COMP", "PHIL", "SOCI", "STAT", "GEOG") -EXAM_OPENERS = ( - "You are helping the registrar sequence final exams.", - "The registrar's office needs the final-exam timetable for this term.", - "Our exams office has to place this term's final exams into slots.", -) - - -def _exam_terms(slots: list, pair: dict, trip: dict): - """slots: [(day, period)] in order; pair/trip keyed by sorted index tuples. Returns terms(order) -> - (back-to-back + same-day-triple cost, evening-to-morning pair sum).""" - p2 = {} - for (x, y), c in pair.items(): - p2[(x, y)] = p2[(y, x)] = c - t3 = {perm: c for key, c in trip.items() for perm in itertools.permutations(key)} - same, em = [], [] - for i in range(len(slots) - 1): - (d1, p1), (d2, q2) = slots[i], slots[i + 1] - if d1 == d2: - same.append(i) - elif p1 == "PM" and q2 == "AM" and d2 == d1 + 1: - em.append(i) - days = {} - for i, (day, _) in enumerate(slots): - days.setdefault(day, []).append(i) - triples = [ix for ix in days.values() if len(ix) == 3] - - def terms(order) -> tuple: - base = 3 * sum(p2[order[i], order[i + 1]] for i in same) - base += 10 * sum(t3[order[i], order[j], order[k]] for i, j, k in triples) - return base, sum(p2[order[i], order[i + 1]] for i in em) - - return terms - - -def _exam_instance(level: int, rng: random.Random): - days = {1: (3, 3), 2: (3, 3, 1), 3: (3, 3, 2)}[level] - periods = ("AM", "MID", "PM") - slots = [(d + 1, periods[i]) for d, n in enumerate(days) for i in range(n)] - n = len(slots) - letter = rng.choice("BEX") - blocks = [f"{letter}{i:02d}" for i in sorted(rng.sample(range(1, 30), n))] - courses, used = [], set() - for b in blocks: - for _ in range(rng.randint(24, 36)): - code = f"{rng.choice(DEPTS)}-{rng.randint(1, 4)}{rng.randint(0, 9)}{rng.randint(0, 9)}0" - if code not in used: - used.add(code) - courses.append((code, b, rng.randint(6, 30))) - size = {b: sum(s for _, bb, s in courses if bb == b) for b in blocks} - pair = {(i, j): 0 if rng.random() < 0.1 else rng.randint(1, 25) for i, j in - itertools.combinations(range(n), 2)} - trip = {(i, j, k): rng.randint(0, min(6, pair[(i, j)], pair[(i, k)], pair[(j, k)])) for i, j, k in - itertools.combinations(range(n), 3)} - cutoff, early, large = None, set(), [] - if level >= 2: - desc = sorted(size.values(), reverse=True) - n_large = rng.choice((1, 2)) - lo, hi = desc[n_large], desc[n_large - 1] - cutoff = (hi // 10) * 10 - if cutoff <= lo: - return None - early = {1, 2, 3} - large = [i for i, b in enumerate(blocks) if size[b] >= cutoff] - em = level >= 3 - terms = _exam_terms(slots, pair, trip) - late = [i for i in range(n) if i + 1 not in early] - # one pass: (cost without the README terms, cost with them, feasible under front-loading, schedule) - table = [] - for o in itertools.permutations(range(n)): - base, extra = terms(o) - table.append((base, base + extra if em else base, not any(o[i] in large for i in late), o)) - feasible = [row for row in table if row[2]] - best = min(row[1] for row in feasible) - orders = [row[3] for row in feasible if row[1] == best] - if best == 0: - return None - if level >= 2 and min(row[0] for row in table) >= min(row[0] for row in feasible): - return None # front-loading must cost something - if em: - naive = min(row[0] for row in feasible) - if any(row[1] == best for row in feasible if row[0] == naive): - return None # some schedule that ignores the evening-to-morning term would still be optimal - return slots, blocks, courses, size, pair, trip, cutoff, sorted(early), large, best, orders - - -def build_exams(level: int, rng: random.Random) -> Built: - for _ in range(200): - got = _exam_instance(level, rng) - if got: - break - else: - raise RuntimeError(f"math3_exam_slots L{level}: no instance in 200 draws") - slots, blocks, courses, size, pair, trip, cutoff, early, large, best, orders = got - n, days = len(blocks), slots[-1][0] - inst = {"blocks": blocks, "slots": [{"slot": i + 1, "day": d, "period": p} for i, (d, p) in enumerate(slots)], - "block_size": size} - readme = ["# Exam sequencing rules, this term", "", - "- Pair and triple counts are unordered: each group of blocks appears once, ids in ascending order."] - if level >= 2: - inst["large_block_cutoff"], inst["early_slots"] = cutoff, early - readme.append("- Front-loading: a block whose size is at or above `large_block_cutoff` in instance.json must " - "be placed in one of the `early_slots`.") - if level >= 3: - readme.append("- Evening-to-morning: when the PM slot of one day is followed by the AM slot of the next day, " - "add 1 x the pair count of the two blocks placed in them to the objective.") - rng.shuffle(courses) - files = { - "data/instance.json": json.dumps(inst, indent=1) + "\n", - "data/pair_counts.csv": "block_a,block_b,students\n" + "".join( - f"{blocks[i]},{blocks[j]},{c}\n" for (i, j), c in sorted(pair.items())), - "data/triplet_counts.csv": "block_a,block_b,block_c,students\n" + "".join( - f"{blocks[i]},{blocks[j]},{blocks[k]},{c}\n" for (i, j, k), c in sorted(trip.items())), - "data/blockmap.csv": "course,block,students\n" + "".join(f"{c},{b},{s}\n" for c, b, s in courses), - "data/README.md": "\n".join(readme) + "\n", - } - words = {6: "six", 7: "seven", 8: "eight"}[n] - instruction = ( - f"{rng.choice(EXAM_OPENERS)} The exams form {words} blocks, and {words} slots run over " - f"{'two' if days == 2 else 'three'} days. Place them so students sit as few close-together exams as " - f"possible.\n\nInputs in /root/data/:\n" - f"- instance.json: the blocks, the slots in order (slot, day, period) and each block's size.\n" - f"- pair_counts.csv and triplet_counts.csv: students taking both blocks of a pair, or all three of a triple.\n" - f"- blockmap.csv: the courses in each block.\n" - f"- README.md: this term's scheduling rules. Apply them.\n\n" - f"Objective, lower is better: for two consecutive slots on the same day, add 3 x the pair count of their " - f"blocks; for a day with three slots, add 10 x the triplet count of its three blocks.\n\n" - f"Create /root/output/ and write /root/output/schedule.csv with the header slot,block and one row per slot " - f"in slot order, for example 1,{rng.choice(blocks)}. Every block appears once. It must follow every rule " - f"and reach the lowest objective; any optimal schedule is accepted." - ) - index = {b: i for i, b in enumerate(blocks)} - terms = _exam_terms(slots, pair, trip) - - def cost(order) -> int: - base, extra = terms(order) - return base + extra if level >= 3 else base - - large_ids = {blocks[i] for i in large} - - def order_of(p) -> tuple: - return tuple(index[r["block"]] for r in p["rows"]) - - checks = [ - ("test_header", lambda p: p["header"] == ["slot", "block"]), - ("test_row_count", lambda p: len(p["rows"]) == n), - ("test_slots_in_order", lambda p: [r["slot"] for r in p["rows"]] == [str(i + 1) for i in range(n)]), - ("test_blocks_once", lambda p: sorted(r["block"] for r in p["rows"]) == sorted(blocks)), - ] - if level >= 2: - checks.append(("test_front_loading", lambda p: all( - int(r["slot"]) in early for r in p["rows"] if r["block"] in large_ids))) - checks.append(("test_objective_optimal", lambda p: cost(order_of(p)) == best)) - want = orders[0] - schedule = "slot,block\n" + "".join(f"{i + 1},{blocks[x]}\n" for i, x in enumerate(want)) - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="output/schedule.csv", kind="checks", parse="csv", checks=checks, - render=lambda: schedule), - notes={"objective": best, "optimal_schedules": len(orders), "large": sorted(large_ids)}, - root="/root", - ) - - -FAMILIES = [ - Family("math3_route_plan", "math and formal reasoning", "Fastest route under closures", build_route, v3=True), - Family("math3_count_items", "math and formal reasoning", "Count raffle winners and pairs", build_count, v3=True), - Family("math3_exam_slots", "math and formal reasoning", "Sequence exam blocks into slots", build_exams, v3=True), -] diff --git a/components/dnakhla/upstream/terminal_desk/families/media.py b/components/dnakhla/upstream/terminal_desk/families/media.py deleted file mode 100644 index f6953af350510507ac4a6921f4f1ebdf4d48b670..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/families/media.py +++ /dev/null @@ -1,180 +0,0 @@ -"""Media production: fix subtitle timing; extract segments, a trim or a channel from a WAV recording.""" - -import io -import math -import random -import struct -import wave - -from .base import Artifact, Built, Family, Field - -WORDS = ( - "we need to leave before the tide turns and the road floods again so pack light take the map " - "and do not wait for me if the bridge is out find the ferry at the north dock" -).split() - -# ---------------------------------------------------------------- med_srt - - -def _ts(ms: int) -> str: - h, rem = divmod(ms, 3600000) - m, rem = divmod(rem, 60000) - s, ms = divmod(rem, 1000) - return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}" - - -def build_srt(level: int, rng: random.Random) -> Built: - n = {1: 12, 2: 25, 3: 45}[level] - cues, t = [], rng.randint(1000, 5000) - for i in range(n): - dur = rng.randint(900, 4500) - lines = [] - for _ in range(rng.choice([1, 1, 2])): - lines.append(" ".join(rng.choice(WORDS) for _ in range(rng.randint(2, 7))).capitalize()) - if level == 3 and rng.random() < 0.25: - lines[0] = f"{lines[0]}" - cues.append([t, t + dur, lines]) - t = t + dur + rng.randint(-600, 1500) - t = max(t, cues[-1][0] + 100) - if level == 1: - shift_from, shift_ms = 1, rng.choice([2000, 3500, 5000]) - else: - shift_from = rng.randint(n // 3, 2 * n // 3) - shift_ms = rng.choice([1250, 800, 2000]) - texts = ["\n".join(lines) for _, _, lines in cues] - if level == 1: - # the file as shipped is late; the correct cues are the generated ones - fixed = [(s, e) for s, e, _ in cues] - late = [(s + shift_ms, e + shift_ms) for s, e in fixed] - else: - late = [(s, e) for s, e, _ in cues] - fixed = [(s - shift_ms, e - shift_ms) if i + 1 >= shift_from else (s, e) for i, (s, e) in enumerate(late)] - blocks = [f"{i + 1}\n{_ts(s)} --> {_ts(e)}\n{texts[i]}\n" for i, (s, e) in enumerate(late)] - text = "\n".join(blocks) - if level == 3: - text = "\ufeff" + text.replace("\n", "\r\n") - secs = f"{shift_ms / 1000:g}" - if level == 1: - what = f"Every cue in /app/episode.srt is {secs} s late." - else: - what = f"In /app/episode.srt, cues {shift_from} to the end are {secs} s late." - rest = "" if level == 1 else ", leave the other cues untouched" - instruction = ( - f"{what} Subtract that from both the start and end times of {'every cue' if level == 1 else 'those cues'}" - f"{rest}, keep all text as is, and save the corrected subtitles to /app/episode_fixed.srt in the same " - "SRT format." - ) - artifact = Artifact( - path="episode_fixed.srt", - kind="srt", - tol_ms=1, - expected=[(s, e, texts[i]) for i, (s, e) in enumerate(fixed)], - ) - return Built(instruction=instruction, files={"episode.srt": text}, artifact=artifact) - - -# ---------------------------------------------------------------- med_wav - -THRESH = 200 - - -def _segments(samples: list[int], rate: int) -> list[tuple[float, float]]: - """(first, last) loud sample time in seconds of each sound segment.""" - gap_max = int(0.05 * rate) - spans: list[list[int]] = [] - for i, x in enumerate(samples): - if abs(x) > THRESH: - if not spans or i - spans[-1][1] - 1 >= gap_max: - spans.append([i, i]) - else: - spans[-1][1] = i - return [(a / rate, b / rate) for a, b in spans] - - -def _wav_bytes(frames: bytes, channels: int, rate: int) -> bytes: - buf = io.BytesIO() - with wave.open(buf, "wb") as w: - w.setnchannels(channels) - w.setsampwidth(2) - w.setframerate(rate) - w.writeframes(frames) - return buf.getvalue() - - -def _track(rng: random.Random, rate: int, noise: int) -> list[int]: - out = [] - - def quiet(seconds): - for _ in range(int(seconds * rate)): - out.append(rng.randint(-noise, noise) if noise else 0) - - quiet(rng.uniform(0.1, 0.4)) - for _ in range(rng.randint(3, 7)): - amp, freq = rng.randint(2000, 20000), rng.uniform(200, 1000) - for j in range(int(rng.uniform(0.2, 0.8) * rate)): - v = amp * math.sin(2 * math.pi * freq * j / rate) - if noise: - v += rng.randint(-noise, noise) - out.append(int(max(-32768, min(32767, round(v))))) - quiet(rng.uniform(0.1, 0.6)) - return out - - -def build_wav(level: int, rng: random.Random) -> Built: - rate = {1: 8000, 2: 16000, 3: 16000}[level] - noise = 0 if level == 1 else rng.randint(40, 150) - left = _track(rng, rate, noise) - channels = 1 - right = [] - if level == 3: - right = _track(rng, rate, noise) - length = max(len(left), len(right)) - left += [0] * (length - len(left)) - right += [0] * (length - len(right)) - channels = 2 - frames = b"".join(struct.pack(" THRESH] - trimmed = struct.pack(f"<{loud[-1] - loud[0] + 1}h", *left[loud[0] : loud[-1] + 1]) - instruction = ( - f"take.wav in /app is a 16-bit mono recording with quiet background noise before and after the " - f"sound. A sample is loud when its absolute value is above {THRESH}. Cut the recording from the first " - "loud sample to the last loud sample, both included, and save it to /app/trimmed.wav as a WAV with " - "the same sample rate and sample width." - ) - artifact = Artifact(path="trimmed.wav", kind="wav", expected=_wav_bytes(trimmed, 1, rate)) - else: - mono = struct.pack(f"<{len(right)}h", *right) - instruction = ( - "take.wav in /app is a 16-bit stereo recording. Extract channel 2 (the right channel) as a mono WAV " - "of the same length, sample rate and sample width, and save it to /app/right.wav." - ) - artifact = Artifact(path="right.wav", kind="wav", expected=_wav_bytes(mono, 1, rate)) - return Built(instruction=instruction, files=files, artifact=artifact) - - -FAMILIES = [ - Family("med_srt", "media and content production", "Fix subtitle timing", build_srt), - Family("med_wav", "media and content production", "Process a WAV recording", build_wav), -] diff --git a/components/dnakhla/upstream/terminal_desk/families/media3.py b/components/dnakhla/upstream/terminal_desk/families/media3.py deleted file mode 100644 index 54e71e98a1ffa5a5723e22467837d974829d00de..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/families/media3.py +++ /dev/null @@ -1,557 +0,0 @@ -"""Media and content production, v3: silence report on a lecture WAV (/app), subtitle retiming -through an edit decision list (/root), sprite counting in game keyframes (/root, Pillow + numpy). - -Every generator computes the expected answer from its own construction and, where a numeric rule -could disagree with the construction (window levels, template matches), recomputes it from the -written data and asserts the two agree. A disagreement is a generator bug and raises. -""" - -import io -import json -import math -import random -import re -from array import array - -from .base import Artifact, Built, Family -from .media import WORDS, _ts, _wav_bytes - -DOMAIN = "media and content production" - -# ---------------------------------------------------------------- med3_silence_report - -RATE = 8000 -WIN = 400 # samples per 50 ms window at 8 kHz -WIN_S = 0.05 -QUIET_AMP, NOISY_AMP = 60, 1000 # uniform noise: about -59.5 and -35 dBFS -THR, NOISY_THR, PAUSE_S = -40.0, -30.0, 2.0 -TIME_TOL, PCT_TOL = 0.02, 0.1 - - -def _level_db(window) -> float: - rms = math.sqrt(sum(v * v for v in window) / len(window)) - return 20 * math.log10(max(rms, 1e-9) / 32768) - - -def _timeline(rng: random.Random, total_s: float) -> list[list]: - """[kind, windows] spans: an opening of quiet, then bursts of tone and gaps. Gap lengths avoid - 1.5-2.5 s so the 2.0 s rule is never decided by one window.""" - opening = rng.randint(12, 36) if rng.random() < 0.5 else rng.randint(60, 160) - spans = [["gap", opening]] - while sum(n for _, n in spans) < total_s / WIN_S: - spans.append(["tone", rng.randint(30, 140)]) - spans.append(["gap", rng.randint(50, 100) if rng.random() < 0.35 else rng.randint(4, 30)]) - spans.append(["tone", rng.randint(30, 80)]) - spans.append(["gap", rng.randint(4, 20)]) - return spans - - -def _noisy_span(rng: random.Random, spans: list[list]) -> tuple[float, float] | None: - """A 10-20 s span that starts and ends inside bursts and holds at least one long gap.""" - starts, t = [], 0 - for kind, n in spans: - starts.append(t) - t += n - tones = [i for i, (kind, _) in enumerate(spans) if kind == "tone"] - pairs = [] - for a in tones: - for b in tones: - inner = range(a + 1, b) - length = (starts[b] + spans[b][1] / 2 - starts[a] - spans[a][1] / 2) * WIN_S - if b > a and 10 <= length <= 20 and any(spans[i][0] == "gap" and spans[i][1] >= 50 for i in inner): - pairs.append((a, b)) - if not pairs: - return None - a, b = rng.choice(pairs) - for i in range(a + 1, b): - if spans[i][0] == "gap": - spans[i][0] = "noisy" - lo = round(rng.uniform(starts[a] + 4, starts[a] + spans[a][1] - 4) * WIN_S, 2) - hi = round(rng.uniform(starts[b] + 4, starts[b] + spans[b][1] - 4) * WIN_S, 2) - return lo, hi - - -def _render_channel(rng: random.Random, spans: list[list]) -> array: - pools = {kind: [array("h", (rng.randint(-amp, amp) for _ in range(WIN))) for _ in range(24)] - for kind, amp in (("gap", QUIET_AMP), ("noisy", NOISY_AMP))} - out = array("h") - for kind, n in spans: - if kind == "tone": - amp, freq = rng.randint(3000, 12000), rng.uniform(150, 600) - step = 2 * math.pi * freq / RATE - out.extend(int(round(amp * math.sin(step * j))) for j in range(n * WIN)) - else: - for _ in range(n): - out.extend(rng.choice(pools[kind])) - return out - - -def build_silence(level: int, rng: random.Random) -> Built: - total = {1: rng.uniform(60, 78), 2: rng.uniform(75, 88), 3: rng.uniform(40, 43)}[level] - seg_range = {1: (4, 8), 2: (4, 9), 3: (3, 7)}[level] - for _ in range(500): - spans = _timeline(rng, total) - span = _noisy_span(rng, spans) if level >= 2 else None - if level >= 2 and span is None: - continue - silent = [] - for kind, n in spans: - silent += [kind != "tone"] * n - runs, i = [], 0 - while i < len(silent): - j = i - while j < len(silent) and silent[j] == silent[i]: - j += 1 - if silent[i] and (i == 0 or (j - i) * WIN_S > PAUSE_S): - runs.append((i, j)) - i = j - if seg_range[0] <= len(runs) <= seg_range[1]: - break - else: - raise RuntimeError("med3_silence_report: no timeline in range after 500 draws") - lapel = _render_channel(rng, spans) - nwin = len(lapel) // WIN - if len(lapel) != nwin * WIN or nwin != len(silent): - raise AssertionError("med3_silence_report: samples do not fill whole windows of the timeline") - lo, hi = span if span else (math.inf, math.inf) - for w in range(nwin): # the stated rule applied to the written samples must give the built mask - limit = NOISY_THR if lo <= w * WIN_S < hi else THR - if (_level_db(lapel[w * WIN:(w + 1) * WIN]) < limit) != silent[w]: - raise AssertionError(f"med3_silence_report: window {w} disagrees with the timeline") - channels, frames = 1, lapel - if level == 3: # channel 2: the room mic, 60 Hz hum near -22 dBFS plus faint noise - hum, step = rng.randint(3500, 3900), 2 * math.pi * 60 / RATE - frames = array("h", bytes(4 * len(lapel))) - frames[0::2] = lapel - frames[1::2] = array("h", (int(round(hum * math.sin(step * j))) + rng.randint(-40, 40) - for j in range(len(lapel)))) - channels = 2 - files = {"data/lecture.wav": _wav_bytes(frames.tobytes(), channels, RATE)} - if level >= 2: - notes = (f"# Recording notes\n\nFrom {lo:.2f} s to {hi:.2f} s the class moved to the workshop, where the " - "air handling is loud. For windows starting in that span (start inclusive, end exclusive) use " - "-30 dBFS instead of -40 dBFS.\n") - if level == 3: - notes += ("\nThe file is stereo. Channel 1 is the instructor's lapel microphone. Channel 2 is a room " - "microphone that carries mains hum the whole time, so it never goes quiet: judge silence on " - "channel 1 only.\n") - files["data/notes.md"] = notes - original = round(nwin * WIN_S, 3) - segs = [{"start": round(a * WIN_S, 3), "end": round(b * WIN_S, 3), "duration": round((b - a) * WIN_S, 3)} - for a, b in runs] - removed = round(sum(s["duration"] for s in segs), 3) - report = {"original_duration_seconds": original, "compressed_duration_seconds": round(original - removed, 3), - "removed_duration_seconds": removed, "compression_percentage": round(removed / original * 100, 2), - "segments_removed": segs} - notes_line = " Recording notes in /app/data/notes.md override these rules where they differ." if level >= 2 else "" - instruction = ( - "A lecture recording for the course site, /app/data/lecture.wav (16-bit PCM), opens with dead air, and " - f"the instructor pauses between topics. Both should be cut.{notes_line}\n\n" - "1. Split the audio into consecutive 50 ms windows from 0 s.\n" - "2. A window's level is 20 * log10(rms / 32768) dBFS, rms being the root mean square of its samples. " - "Below -40 dBFS it is silent.\n" - "3. A silent run is a maximal stretch of consecutive silent windows (start of its first window to end " - "of its last).\n" - "4. Remove the run at the very start of the file, whatever its length, and every other run longer than " - "2.0 s.\n\n" - "Write /app/compression_report.json with the keys original_duration_seconds, " - "compressed_duration_seconds, removed_duration_seconds, compression_percentage (removed / original * " - "100) and segments_removed: a list in time order of objects like " - '{"start": 0.0, "end": 6.3, "duration": 6.3}. Times are checked within 0.02 s, the percentage within 0.1.' - ) - - def near(got, want, tol=TIME_TOL) -> bool: - return isinstance(got, (int, float)) and not isinstance(got, bool) and abs(got - want) <= tol + 1e-9 - - def seg_ok(p) -> bool: - got = p["segments_removed"] - return all(near(g[k], w[k]) for g, w in zip(got, segs) for k in ("start", "end", "duration")) - - keys = set(report) - checks = [ - ("test_valid_json", lambda p: isinstance(p, dict)), - ("test_keys", lambda p: set(p) == keys and isinstance(p["segments_removed"], list) - and all(isinstance(s, dict) and set(s) == {"start", "end", "duration"} for s in p["segments_removed"])), - ("test_original_duration", lambda p: near(p["original_duration_seconds"], original)), - ("test_segment_count", lambda p: len(p["segments_removed"]) == len(segs)), - ("test_segments", seg_ok), - ("test_removed_duration", lambda p: near(p["removed_duration_seconds"], removed)), - ("test_compressed_duration", lambda p: near(p["compressed_duration_seconds"], original - removed)), - ("test_consistency", lambda p: near(p["original_duration_seconds"], - p["compressed_duration_seconds"] + p["removed_duration_seconds"])), - ("test_compression_percentage", lambda p: near(p["compression_percentage"], - report["compression_percentage"], PCT_TOL)), - ] - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="compression_report.json", kind="checks", parse="json", checks=checks, - render=lambda: json.dumps(report, indent=2) + "\n"), - notes={"segments": len(segs), "noisy_span": span}, - root="/app", - ) - -# ---------------------------------------------------------------- med3_subtitle_retime - - -def _edl_ts(ms: int) -> str: - return _ts(ms).replace(",", ".") - - -def _cue_text(rng: random.Random, italics: bool) -> str: - lines = [" ".join(rng.choice(WORDS) for _ in range(rng.randint(2, 7))).capitalize() - for _ in range(rng.choice([1, 1, 2]))] - if italics and rng.random() < 0.25: - lines[0] = f"{lines[0]}" - return "\n".join(lines) - - -def _union(cuts: list[tuple[int, int]]) -> list[list[int]]: - merged: list[list[int]] = [] - for s, e in sorted(cuts): - if merged and s <= merged[-1][1]: - merged[-1][1] = max(merged[-1][1], e) - else: - merged.append([s, e]) - return merged - - -def _shift(t: int, union: list[list[int]]) -> int: - """t minus the removed footage before it; a time inside a cut lands on the cut point.""" - out = t - for s, e in union: - if t > s: - out -= min(t, e) - s - return out - - -def _draw_cuts(rng: random.Random, k: int, span: tuple[int, int], overlap: bool) -> list[tuple[int, int]]: - lo, hi = span - for _ in range(1000): - cuts = [] - for _ in range(k): - s = rng.randint(lo, hi - 16000) - cuts.append((s, s + rng.randint(2000, 14000))) - cuts.sort() - pairs = list(zip(cuts, cuts[1:])) - touching = any(e1 - 1000 <= s2 <= e1 + 500 for (_, e1), (s2, _) in pairs) # neither clear nor overlapping - overlapping = any(s2 < e1 - 1000 for (_, e1), (s2, _) in pairs) - if not touching and overlapping == overlap: - return cuts - raise RuntimeError("med3_subtitle_retime: no cut layout after 1000 draws") - - -def _gap_cut_cues(rng: random.Random, n_cues: int, n_cuts: int) -> tuple[list, list[tuple[int, int]]]: - """L1: cues with a long silent gap after n_cuts of them, and one cut inside each gap, so no cue - touches removed footage and every cue only shifts by the cuts before it.""" - while True: - picks = sorted(rng.sample(range(4, n_cues - 4), n_cuts)) - if all(b - a >= 8 for a, b in zip(picks, picks[1:])): - break - cues, cuts, t = [], [], rng.randint(1000, 5000) - for i in range(n_cues): - dur = rng.randint(900, 4500) - cues.append((t, t + dur, _cue_text(rng, False))) - t += dur - if i in picks: - lead, length = rng.randint(150, 600), rng.randint(2500, 12000) - cuts.append((t + lead, t + lead + length)) - t += lead + length + rng.randint(150, 600) - else: - t += rng.randint(100, 1500) - return cues, cuts - - -def build_retime(level: int, rng: random.Random) -> Built: - from ..core.grading import parse_srt # grading imports the families package, so not at module level - - n_cues, n_cuts = {1: (46, 2), 2: (46, 3), 3: (80, 7)}[level] - min_len = 500 if level == 3 else 1 - ids = [f"C{i}" for i in range(1, n_cuts + 1)] - reverted = None - if level == 1: - cues, cuts = _gap_cut_cues(rng, n_cues, n_cuts) - union = _union(cuts) - out = [(_shift(s, union), _shift(e, union), text) for s, e, text in cues] - if any(s < b and a < e for s, e, _ in cues for a, b in union): - raise AssertionError("med3_subtitle_retime: an L1 cut overlaps a cue") - else: - for _ in range(500): - cues, t = [], rng.randint(1000, 5000) - for _ in range(n_cues): - dur = rng.randint(900, 4500) - cues.append((t, t + dur, _cue_text(rng, level == 3))) - t += dur + rng.randint(100, 1500) - cuts = _draw_cuts(rng, n_cuts, (cues[0][0], cues[-1][1]), overlap=level == 3) - reverted = rng.choice(ids[1:-1]) if level == 3 else None - active = [c for cid, c in zip(ids, cuts) if cid != reverted] - union = _union(active) - out = [(_shift(s, union), _shift(e, union), text) for s, e, text in cues] - inside = sum(1 for s, e, _ in cues if any(a <= s and e <= b for a, b in union)) - straddle = sum(1 for s, e, _ in cues if any(s < a < e or s < b < e for a, b in union)) - near_min = any(abs((e - s) - 500) <= 5 for s, e, _ in out) if level == 3 else False - short = sum(1 for s, e, _ in out if 0 < e - s < 500) - sliver = any(0 < e - s < 20 for s, e, _ in out) # a kept 5 ms cue would hinge on the 1 ms tolerance - merged = len(union) < len(active) # L3: an overlapping pair survives the reverted cut - if inside >= 1 and straddle >= 2 and not near_min and not sliver and (level < 3 or (short >= 1 and merged)): - break - else: - raise RuntimeError("med3_subtitle_retime: no instance after 500 draws") - want = [(s, e, text) for s, e, text in out if e - s >= min_len] - srt = "\n".join(f"{i}\n{_ts(s)} --> {_ts(e)}\n{text}\n" for i, (s, e, text) in enumerate(cues, 1)) - if level == 3: - srt = "\ufeff" + srt.replace("\n", "\r\n") - if level == 1: - rows = [(cid, s, e, "dead air") for cid, (s, e) in zip(ids, cuts)] - else: - rows = [(cid, s, e, rng.choice(("retake", "dead air", "off topic", "legal", "pacing"))) - for cid, (s, e) in zip(ids, cuts)] - if level == 3: - rng.shuffle(rows) - edl = "cut_id,start,end,reason\n" + "".join(f"{c},{_edl_ts(s)},{_edl_ts(e)},{r}\n" for c, s, e, r in rows) - files = {"episode.srt": srt, "edl.csv": edl} - output = ( - "Write the result as an SRT file at /root/output/episode.srt with HH:MM:SS,mmm times, for example:\n" - "1\n00:00:01,250 --> 00:00:03,900\nPack light and take the map\n\n" - "Times are checked within 1 ms and text must match exactly." - ) - if level == 1: - instruction = ( - "Our editor removed stretches of dead air from an episode, and every subtitle after a removed stretch " - "now runs late. The subtitles are /root/episode.srt. The removed stretches are listed in " - "/root/edl.csv with the columns cut_id, start, end, reason; start and end are HH:MM:SS.mmm times on " - "the original timeline. Every cut lies in a silent gap between two cues, so no cue overlaps removed " - "footage.\n\n" - "1. A cue moves earlier by the total length (end - start) of all the cuts before it. Cues before the " - "first cut keep their times.\n" - "2. Shift a cue's start and end by the same amount.\n" - "3. Keep every cue, its number and its text exactly as they are.\n\n" + output - ) - elif level == 2: - instruction = ( - "Our editor cut sections out of an episode, and the subtitles now drift after each cut. The subtitles " - "are /root/episode.srt. The cuts are in /root/edl.csv (cut_id, start, end, reason); start and end are " - "HH:MM:SS.mmm times on the original timeline, and everything between them was removed.\n\n" - "1. A time t moves earlier by the removed footage before it: for every cut that starts before t, " - "subtract min(t, end) - start. A time inside a cut lands on the point where the cut was made.\n" - "2. Apply this to the start and end of every cue, so a cue that straddles a cut gets shorter.\n" - "3. Drop a cue whose start and end land on the same time.\n" - "4. Keep each cue's text exactly, line breaks included, and renumber the cues from 1.\n\n" + output - ) - else: - files["edit_notes.md"] = (f"# Edit notes\n\n{reverted} was reverted in the final cut: that footage stays " - "in. Ignore its row.\n\nAfter retiming, drop any cue shorter than 500 ms. Nobody " - "can read it.\n") - instruction = ( - "Our editor cut sections out of an episode, and the subtitles now drift after each cut. The subtitles " - "are /root/episode.srt. The cuts are in /root/edl.csv (cut_id, start, end, reason); start and end are " - "HH:MM:SS.mmm times on the original timeline, and everything between them was removed. The editor " - "left notes in /root/edit_notes.md; follow them.\n\n" - "1. A time t moves earlier by the total length of removed footage before t. A time inside a cut lands " - "on the point where the cut was made.\n" - "2. Apply this to the start and end of every cue, so a cue that straddles a cut gets shorter.\n" - "3. Drop a cue whose start and end land on the same time.\n" - "4. Keep each cue's text exactly, line breaks included, and renumber the cues from 1.\n\n" + output - ) - - def norm(text: str) -> list[str]: - return [" ".join(line.split()) for line in text.strip().split("\n")] - - def numbering(text: str) -> bool: - blocks = re.split(r"\n\s*\n", text.strip()) - return [b.strip().split("\n")[0].strip() for b in blocks] == [str(i) for i in range(1, len(blocks) + 1)] - - def times(text: str) -> bool: - got = parse_srt(text) - return len(got) == len(want) and all(abs(g[0] - w[0]) <= 1 and abs(g[1] - w[1]) <= 1 - for g, w in zip(got, want)) - - def texts(text: str) -> bool: - got = parse_srt(text) - return len(got) == len(want) and all(norm(g[2]) == norm(w[2]) for g, w in zip(got, want)) - - checks = [ - ("test_parses", lambda p: isinstance(parse_srt(p), list)), - ("test_cue_count", lambda p: len(parse_srt(p)) == len(want)), - ("test_numbering", numbering), - ("test_times", times), - ("test_text", texts), - ] - rendered = "\n".join(f"{i}\n{_ts(s)} --> {_ts(e)}\n{text}\n" for i, (s, e, text) in enumerate(want, 1)) - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="output/episode.srt", kind="checks", parse="text", checks=checks, - render=lambda: rendered), - notes={"cues": len(want), "dropped": len(cues) - len(want), "reverted": reverted}, - root="/root", - ) - - -# ---------------------------------------------------------------- med3_sprite_count - -FRAME_W, FRAME_H = 256, 144 -SPRITES = {"coin": (16, 12), "enemy": (16, 16), "turtle": (24, 16)} # (height, width) -MAX_DIFF = 10.0 -NOISE = 3 - - -def _gray(rgb): - """Pillow's mode "L" conversion, the same integer formula the instruction's step 1 runs.""" - from PIL import Image - - return __import__("numpy").asarray(Image.fromarray(rgb).convert("L"), dtype="float32") - - -def _sprite(nrng, h: int, w: int): - import numpy as np - - while True: - palette = nrng.integers(0, 256, size=(4, 3), dtype=np.uint8) - g = np.sort(palette @ np.array([0.299, 0.587, 0.114])) - if np.min(np.diff(g)) >= 40: # four clearly different gray levels - break - idx = nrng.integers(0, 4, size=(h // 2, w // 2)).repeat(2, axis=0).repeat(2, axis=1) # 2x2 pixel art - art = palette[idx] - if np.array_equal(art, art[:, ::-1]): - return _sprite(nrng, h, w) - return art - - -def _png(rgb) -> bytes: - from PIL import Image - - buf = io.BytesIO() - Image.fromarray(rgb).save(buf, format="PNG") - return buf.getvalue() - - -def _count(frame, variants) -> int: - """The instruction's rule: windows fully inside the frame, mean abs diff below 10, one hit per object. - Sums |frame - sprite pixel| one sprite pixel at a time over every window position (same numbers as a - sliding window, without the windows x sprite temporary).""" - import numpy as np - - h, w = variants[0].shape - ny, nx = frame.shape[0] - h + 1, frame.shape[1] - w + 1 - hits = np.zeros((ny, nx), dtype=bool) - for t in variants: - total = np.zeros((ny, nx), dtype=np.float32) - for dy in range(h): - for dx in range(w): - total += np.abs(frame[dy:dy + ny, dx:dx + nx] - t[dy, dx]) - hits |= total / (h * w) < MAX_DIFF - found: list[tuple[int, int]] = [] - for y, x in zip(*np.nonzero(hits)): - if all(abs(y - fy) >= h or abs(x - fx) >= w for fy, fx in found): - found.append((y, x)) - return len(found) - - -def _place(rng: random.Random, taken: list, h: int, w: int, x_range: tuple[int, int]): - for _ in range(200): - y, x = rng.randint(0, FRAME_H - h), rng.randint(*x_range) - if all(y + h + 2 <= ty or ty + th + 2 <= y or x + w + 2 <= tx or tx + tw + 2 <= x for ty, tx, th, tw in taken): - taken.append((y, x, h, w)) - return y, x - return None - - -def build_sprites(level: int, rng: random.Random) -> Built: - import numpy as np - - nrng = np.random.default_rng(rng.getrandbits(64)) - n_frames = {1: 6, 2: 8, 3: 9}[level] # the oracle at L3 takes ~4 s on a loaded 8-core host; 20 s is the cap - noisy, mirrored = level >= 2, level == 3 - art = {name: _sprite(nrng, h, w) for name, (h, w) in SPRITES.items()} - gray_art = {name: _gray(a) for name, a in art.items()} - files = {f"sprites/{name}.png": _png(a) for name, a in art.items()} - counts = [] - for f in range(1, n_frames + 1): - frame = np.empty((FRAME_H, FRAME_W, 3), dtype=np.uint8) - frame[:] = nrng.integers(0, 256, size=3, dtype=np.uint8) - for _ in range(25): # background blocks of random colours, so colour counting fails - y, x = rng.randint(0, FRAME_H - 8), rng.randint(0, FRAME_W - 8) - frame[y:y + rng.randint(8, 60), x:x + rng.randint(8, 60)] = nrng.integers(0, 256, 3, dtype=np.uint8) - taken, want = [], {name: 0 for name in SPRITES} - for _ in range(rng.randint(3, 9)): - name = rng.choice(list(SPRITES)) - h, w = SPRITES[name] - spot = _place(rng, taken, h, w, (0, FRAME_W - w)) - if spot is None: - continue - a = art[name][:, ::-1] if mirrored and rng.random() < 0.3 else art[name] - frame[spot[0]:spot[0] + h, spot[1]:spot[1] + w] = a - want[name] += 1 - for _ in range(rng.choice((0, 1, 1, 2))): # decoys cut by the left or right border - name = rng.choice(list(SPRITES)) - h, w = SPRITES[name] - cut = rng.randint(3, w - 3) - left = rng.random() < 0.5 - x_range = (-cut, -cut) if left else (FRAME_W - w + cut, FRAME_W - w + cut) - spot = _place(rng, taken, h, w, x_range) - if spot is None: - continue - y, x = spot - lo, hi = max(x, 0), min(x + w, FRAME_W) - frame[y:y + h, lo:hi] = art[name][:, lo - x:hi - x] - if noisy: - jitter = nrng.integers(-NOISE, NOISE + 1, size=frame.shape) - frame = np.clip(frame.astype(np.int16) + jitter, 0, 255).astype(np.uint8) - g = _gray(frame) - for name in SPRITES: # the stated rule on the written frame must find exactly what was placed - t = gray_art[name] - got = _count(g, [t, t[:, ::-1]] if mirrored else [t]) - if got != want[name]: - raise AssertionError(f"med3_sprite_count: frame {f} {name}: rule finds {got}, placed {want[name]}") - files[f"frames/frame_{f:03d}.png"] = _png(frame) - counts.append((f"frame_{f:03d}.png", want["coin"], want["enemy"], want["turtle"])) - if level >= 2: - notes = ("# Notes\n\nThe frames were re-encoded, so pixel values can differ by a few levels from the " - "sprites.\n") - if mirrored: - notes += "\nA sprite drawn mirrored left-to-right is the same object and counts.\n" - files["notes.md"] = notes - notes_line = " Read /root/notes.md before you start." if level >= 2 else "" - instruction = ( - "You are building ground truth for a game-footage object detector. Keyframes are in /root/frames/ as " - "frame_001.png, frame_002.png and so on; reference sprites are /root/sprites/coin.png, enemy.png and " - "turtle.png. Every object in a frame is a copy of one sprite at its original size, never rotated or " - f"scaled, and objects never overlap.{notes_line}\n\n" - "1. Convert frames and sprites to grayscale (Pillow mode \"L\").\n" - "2. A sprite occurs at a position when the mean absolute difference between the sprite and the frame " - "window of the same size there is below 10 gray levels.\n" - "3. Count each object once, even if neighbouring positions also pass.\n" - "4. An object cut off by the frame border does not count.\n\n" - "Write /root/counting_results.csv with the header frame_id,coins,enemies,turtles and one row per " - "keyframe in frame-number order; frame_id is the file name, e.g. frame_001.png,2,1,0. Every count must " - "match exactly." - ) - header = ["frame_id", "coins", "enemies", "turtles"] - - def column(i: int): - return lambda p: [r[header[i]] for r in p["rows"]] == [str(c[i]) for c in counts] - - checks = [ - ("test_header", lambda p: p["header"] == header), - ("test_row_count", lambda p: len(p["rows"]) == len(counts)), - ("test_frame_ids", column(0)), - ("test_coins", column(1)), - ("test_enemies", column(2)), - ("test_turtles", column(3)), - ] - rendered = ",".join(header) + "\n" + "".join(",".join(map(str, c)) + "\n" for c in counts) - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="counting_results.csv", kind="checks", parse="csv", checks=checks, - render=lambda: rendered), - notes={"totals": [sum(c[i] for c in counts) for i in (1, 2, 3)]}, - root="/root", - ) - -FAMILIES = [ - Family("med3_silence_report", DOMAIN, "Report silent segments in a lecture recording", build_silence, v3=True), - Family("med3_subtitle_retime", DOMAIN, "Retime subtitles through an edit decision list", build_retime, v3=True), - Family("med3_sprite_count", DOMAIN, "Count sprites in game keyframes", build_sprites, v3=True), -] diff --git a/components/dnakhla/upstream/terminal_desk/families/office.py b/components/dnakhla/upstream/terminal_desk/families/office.py deleted file mode 100644 index d80607cd66bb56ad36fa08723862faff26cf04ab..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/families/office.py +++ /dev/null @@ -1,234 +0,0 @@ -"""Office work: reconcile invoices against payments; find a meeting slot across time zones.""" - -import datetime as dt -import random - -from .base import Artifact, Built, Family, Field, money - -CUSTOMERS = ["Arden Foods", "Blue Kettle", "Cobalt Labs", "Dune Freight", "Elm & Oak", "Fable Print"] - -# ---------------------------------------------------------------- off_recon - - -def _cents(x: float) -> int: - return int(round(x * 100)) - - -def build_recon(level: int, rng: random.Random) -> Built: - n_inv = {1: 8, 2: 15, 3: 25}[level] - while True: - ids = [1001 + i for i in range(n_inv)] - amount = {i: _cents(rng.uniform(120, 4800)) for i in ids} - day0 = dt.date(2026, 9, 1) - inv_date = {i: day0 + dt.timedelta(days=rng.randint(0, 20)) for i in ids} - credits = [] - if level >= 2: - for i in rng.sample(ids, max(2, n_inv // 6)): - credits.append((f"CN-{len(credits) + 1:03d}", i, _cents(rng.uniform(20, amount[i] / 100 * 0.3)))) - voided = rng.choice(ids) if level == 3 else None - payable = [i for i in ids if i != voided] - # Plan payments: each names 1 (or 2-3 at level >= 2) invoices; amounts cover them fully or partly. - payments, pool = [], payable[:] - rng.shuffle(pool) - while pool: - k = 1 if level == 1 else rng.choice([1, 1, 2, 3]) - named, pool = pool[:k], pool[k:] - if rng.random() < 0.2: - continue # these invoices get nothing - due = sum(amount[i] for i in named) - pay = due if rng.random() < 0.55 else _cents(due / 100 * rng.uniform(0.3, 0.95)) - paid_on = max(inv_date[i] for i in named) + dt.timedelta(days=rng.randint(3, 25)) - payments.append([named, pay, paid_on]) - moved = None - if level == 3 and len(payments) >= 3: - p = rng.randrange(len(payments)) - targets = [i for i in payable if i not in payments[p][0]] - moved = (p, rng.choice(targets)) - # Compute balances. - bal = {i: amount[i] for i in payable} - for _, i, c in credits: - if i in bal: - bal[i] = max(0, bal[i] - c) - for idx in sorted(range(len(payments)), key=lambda j: (payments[j][2], j)): - named, pay, _ = payments[idx] - order = [moved[1]] if moved and moved[0] == idx else named - left = pay - for i in order: - take = min(left, bal[i]) - bal[i] -= take - left -= take - unpaid = sorted(f"INV-{i}" for i, b in bal.items() if b > 0) - if 2 <= len(unpaid) < len(payable): - break - - def ref(i: int) -> str: - if level < 3: - return f"INV-{i}" - return rng.choice([f"INV-{i}", f"inv {i}", f"#{i}", f"invoice {i}"]) - - pay_rows = [] - for idx, (named, pay, d) in enumerate(payments): - memo = rng.choice(["Payment for ", "Remit ", "Re: ", ""]) + " ".join(ref(i) for i in named) - pay_rows.append((d, f"P-{idx + 1:04d}", pay, memo)) - pay_rows.sort(key=lambda r: (r[0], r[1])) - files = { - "invoices.csv": "invoice,customer,date,amount\n" - + "".join( - f"INV-{i},{rng.choice(CUSTOMERS)},{inv_date[i].isoformat()},{money(amount[i] / 100)}\n" for i in ids - ), - "payments.csv": "date,payment,amount,memo\n" - + "".join(f"{d.isoformat()},{pid},{money(a / 100)},\"{m}\"\n" for d, pid, a, m in pay_rows), - } - rules = ( - "Process payments in date order, then by payment ID. Each payment's memo names one or more invoices by number. Apply the payment to them in the order named, " - "paying each invoice's remaining balance in full before moving to the next; anything left over is " - "unapplied credit and is ignored." - ) - if credits: - files["credit_notes.csv"] = "credit_note,invoice,amount\n" + "".join( - f"{cid},INV-{i},{money(c / 100)}\n" for cid, i, c in credits - ) - rules += " Credit notes reduce their invoice's balance and are applied before any payment." - if level == 3: - memo = [f"INV-{voided} was voided: it is not owed and must not appear in your output."] - if moved: - pid = f"P-{moved[0] + 1:04d}" - memo.append(f"{pid} was keyed against the wrong invoice. Apply all of it to INV-{moved[1]} instead of what its memo says.") - files["controller_memo.txt"] = "\n".join(memo) + "\n" - rules += " controller_memo.txt has corrections that override the files." - instruction = ( - "Reconcile accounts receivable from /app/invoices.csv and /app/payments.csv. " + rules + " " - "Write /app/balances.csv with the header invoice,balance and one row per invoice (voided ones " - "excluded) giving the balance still owed in dollars, e.g. INV-1001,0.00" - ) - return Built( - instruction=instruction, - files=files, - artifact=Artifact( - path="balances.csv", - kind="csv", - key=("invoice",), - fields=[Field("invoice", "text"), Field("balance", "number", tol=0.005)], - expected=[{"invoice": f"INV-{i}", "balance": bal[i] / 100} for i in payable], - ), - ) - - -# ---------------------------------------------------------------- off_sched - -PEOPLE = ["ana", "ben", "chen", "dara", "eli"] -OFFSETS = [-7, -5, -4, 0, 1, 2, 3, 5.5] - - -def _fmt_off(h: float) -> str: - sign = "+" if h >= 0 else "-" - hh, mm = int(abs(h)), int(round((abs(h) % 1) * 60)) - return f"UTC{sign}{hh:02d}:{mm:02d}" - - -def build_sched(level: int, rng: random.Random) -> Built: - n_people, n_days, dur = {1: (3, 2, 30), 2: (4, 3, 45), 3: (5, 3, 60)}[level] - days = [dt.date(2026, 11, 2) + dt.timedelta(days=i) for i in range(n_days)] - step = dt.timedelta(minutes=15) - while True: - names = PEOPLE[:n_people] - base = rng.choice(OFFSETS) - offs = {} - for n in names: - close = [o for o in OFFSETS if abs(o - base) <= 4] - offs[n] = rng.choice(close) - busy = {n: [] for n in names} - for n in names: - for d in days: - for _ in range(rng.randint(1, 4)): - start = dt.datetime.combine(d, dt.time(9)) + step * rng.randint(0, 28) - busy[n].append((start, start + step * rng.randint(2, 8))) - lunch = level == 3 - ooo = {} - if level == 3: - ooo[rng.choice(names)] = rng.choice(days[:-1]) - - def free(n: str, t_utc: dt.datetime) -> bool: - off = dt.timedelta(hours=offs[n]) - s, e = t_utc + off, t_utc + off + dt.timedelta(minutes=dur) - day = s.date() - if ooo.get(n) == day: - return False - if s < dt.datetime.combine(day, dt.time(9)) or e > dt.datetime.combine(day, dt.time(17)): - return False - blocks = list(busy[n]) - if lunch: - blocks.append((dt.datetime.combine(day, dt.time(12)), dt.datetime.combine(day, dt.time(13)))) - return all(e <= b0 or s >= b1 for b0, b1 in blocks) - - valid = [] - t = dt.datetime.combine(days[0], dt.time(0)) - end = dt.datetime.combine(days[-1], dt.time(23, 45)) - while t <= end: - if all(free(n, t) for n in names): - valid.append(t) - t += step - if 2 <= len(valid): - break - files = {} - for n in names: - lines = [f"timezone: {_fmt_off(offs[n])}", "working hours: 09:00-17:00 local"] - if lunch: - lines.append("lunch: 12:00-13:00 local every day (not available)") - if n in ooo: - lines.append(f"out of office: {ooo[n].isoformat()} (whole local day)") - lines.append("busy (local time):") - for b0, b1 in sorted(busy[n]): - lines.append(f" {b0:%Y-%m-%d} {b0:%H:%M}-{b1:%H:%M}") - files[f"calendars/{n}.txt"] = "\n".join(lines) + "\n" - instruction = ( - f"Find a {dur}-minute meeting for everyone in /app/calendars/, one file per person with their time zone, " - "working hours and busy blocks in local time. A start works when, for every person, the whole meeting " - "falls inside their working hours on one local day and overlaps none of their busy blocks (a block " - "ending at 10:00 does not clash with a meeting starting at 10:00). Consider quarter-hour UTC starts " - f"from {days[0]} 00:00 to {days[-1]} 23:45. Create /app/meeting.ics with one VEVENT at the earliest " - "such slot. DTSTART and DTEND must be UTC (YYYYMMDDTHHMMSSZ)." - ) - want_start, want_end = valid[0], valid[0] + dt.timedelta(minutes=dur) - - def verify(app: str) -> bool: - from ..core.grading import read_artifact - - data = read_artifact(app, "meeting.ics") - if data is None: - return False - text = data.decode("utf-8", errors="replace").replace("\r\n", "\n") - if "BEGIN:VEVENT" not in text or "END:VEVENT" not in text: - return False - block = text.split("BEGIN:VEVENT", 1)[1].split("END:VEVENT", 1)[0] - got = {} - for line in block.split("\n"): - name, _, value = line.partition(":") - if name.strip() in ("DTSTART", "DTEND"): - got[name.strip()] = value.strip() - try: - start = dt.datetime.strptime(got["DTSTART"], "%Y%m%dT%H%M%SZ") - end = dt.datetime.strptime(got["DTEND"], "%Y%m%dT%H%M%SZ") - except (KeyError, ValueError): - return False - return start == want_start and end == want_end - - def render() -> str: - return ( - "BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//terminal-desk//EN\nBEGIN:VEVENT\n" - f"UID:meeting-{want_start:%Y%m%dT%H%M%S}@terminal-desk\nDTSTAMP:20261101T000000Z\n" - f"DTSTART:{want_start:%Y%m%dT%H%M%SZ}\nDTEND:{want_end:%Y%m%dT%H%M%SZ}\n" - "SUMMARY:Team meeting\nEND:VEVENT\nEND:VCALENDAR\n" - ) - - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="meeting.ics", kind="custom", verify=verify, render=render), - ) - - -FAMILIES = [ - Family("off_recon", "office and white-collar work", "Reconcile receivables", build_recon), - Family("off_sched", "office and white-collar work", "Schedule across time zones", build_sched), -] diff --git a/components/dnakhla/upstream/terminal_desk/families/office3.py b/components/dnakhla/upstream/terminal_desk/families/office3.py deleted file mode 100644 index 0635b8bce75c0bec4678f36718e6cb1c7ecb66c9..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/families/office3.py +++ /dev/null @@ -1,505 +0,0 @@ -"""Office v3: receivables reconciliation, a meeting slot across time zones, and a PDF-vs-workbook diff. - -off3_ar_recon and off3_meeting_slot are stdlib csv/json tasks reshaped from v2's off_recon and off_sched. -off3_pdf_xlsx_diff is the domain's one library family (pdfplumber + openpyxl), modeled on SkillsBench -pdf-excel-diff. Every generator computes the expected answer itself; the oracles in terminal_desk/oracles/ -only prove the files carry it. -""" - -import datetime as dt -import io -import json -import random - -from .base import Artifact, Built, Family, money - -DOMAIN = "office and white-collar work" -CUSTOMERS = ["Arden Foods", "Blue Kettle", "Cobalt Labs", "Dune Freight", "Elm & Oak", "Fable Print", "Gull Marine"] - -# ---------------------------------------------------------------- off3_ar_recon - - -def _cents(x: float) -> int: - return int(round(x * 100)) - - -def _apply(bal: dict, order: list, pay: int) -> None: - """Pay each named invoice's remaining balance in full before the next; the excess is ignored.""" - left = pay - for i in order: - take = min(left, bal[i]) - bal[i] -= take - left -= take - - -def _plan_payments(level: int, rng: random.Random, payable: list, amount: dict, day0: dt.date) -> list: - """Payments as [named invoices, cents, date], sorted by date (ties keep plan order).""" - payments, pool = [], payable[:] - rng.shuffle(pool) - while pool: - k = 1 if level == 1 else rng.choice([1, 1, 2, 3]) - named, pool = pool[:k], pool[k:] - due = sum(amount[i] for i in named) - r = rng.random() - if r < 0.15: - continue # nothing paid yet - if r < 0.5: - pays = [due] - elif r < 0.65: - pays = [due + _cents(rng.uniform(5, 300))] # overpaid - elif r < 0.8 and level == 1: - pays = [_cents(due / 100 * rng.uniform(0.3, 0.6)), _cents(due / 100 * rng.uniform(0.2, 0.5))] - else: - pays = [_cents(due / 100 * rng.uniform(0.2, 0.9))] - for p in pays: - payments.append([named, p, day0 + dt.timedelta(days=rng.randint(0, 40))]) - payments.sort(key=lambda p: p[2]) - return payments - - -def _balances(amount: dict, payable: list, credits: list, payments: list, moved) -> dict: - bal = {i: amount[i] for i in payable} - for _, i, c in credits: - if i in bal: - bal[i] = max(0, bal[i] - c) - for j, (named, pay, _) in enumerate(payments): - _apply(bal, [moved[1]] if moved and moved[0] == j else named, pay) - return bal - - -def _status(amount: int, bal: int) -> str: - return "paid" if bal == 0 else "open" if bal == amount else "partial" - - -def build_ar_recon(level: int, rng: random.Random) -> Built: - n_inv = {1: 90, 2: 120, 3: 150}[level] - base = rng.randint(1001, 7000) - ids = [base + i for i in range(n_inv)] - amount = {i: _cents(rng.uniform(120, 2400)) for i in ids} - customer = {i: rng.choice(CUSTOMERS) for i in ids} - voided = rng.choice(ids) if level == 3 else None - payable = [i for i in ids if i != voided] - credits = [] - if level >= 2: - for i in sorted(rng.sample(ids, n_inv // 8)): - credits.append((f"CN-{len(credits) + 1:03d}", i, _cents(rng.uniform(10, amount[i] / 100 * 0.4)))) - while True: - payments = _plan_payments(level, rng, payable, amount, dt.date(2026, 9, 1)) - moved = None - if level == 3: - keys = [(p[1], p[2]) for p in payments] - idx = rng.choice([j for j, p in enumerate(payments) if keys.count((p[1], p[2])) == 1]) - moved = (idx, rng.choice([i for i in payable if i not in payments[idx][0]])) - bal = _balances(amount, payable, credits, payments, moved) - status = {i: _status(amount[i], bal[i]) for i in payable} - # every rule of the level must change the answer, so a script that skips one fails - naive = [] - if level == 1: - paid = {i: sum(p for named, p, _ in payments if named == [i]) for i in payable} - naive.append({i: amount[i] - paid[i] for i in payable}) # no floor at 0 - else: - naive.append(_balances(amount, payable, credits, [[n[::-1], p, d] for n, p, d in payments], moved)) - naive.append(_balances(amount, payable, [], payments, moved)) - if level == 3: - naive.append(_balances(amount, payable, credits, payments, None)) - # from L2 a credited invoice nobody paid is partial, not open - paid_any = {i for named, _, _ in payments for i in named} | ({moved[1]} if moved else set()) - credit_only = [i for _, i, _ in credits if i in status and i not in paid_any and status[i] == "partial"] - if (all(v != bal for v in naive) and set(status.values()) == {"paid", "open", "partial"} - and (level == 1 or credit_only)): - break - want = [(f"INV-{i}", customer[i], bal[i], status[i]) for i in payable] - - def ref(i: int) -> str: - return rng.choice([f"INV-{i}", f"inv {i}", f"#{i}"]) if level == 3 else f"INV-{i}" - - files = {"invoices.csv": "invoice,customer,amount\n" - + "".join(f"INV-{i},{customer[i]},{money(amount[i] / 100)}\n" for i in ids)} - if level == 1: - files["payments.csv"] = "date,invoice,amount\n" + "".join( - f"{d.isoformat()},INV-{named[0]},{money(p / 100)}\n" for named, p, d in payments) - else: - files["payments.csv"] = "date,amount,memo\n" + "".join( - f"{d.isoformat()},{money(p / 100)},{' '.join(ref(i) for i in named)}\n" for named, p, d in payments) - files["credit_notes.csv"] = "credit_note,invoice,amount\n" + "".join( - f"{cid},INV-{i},{money(c / 100)}\n" for cid, i, c in credits) - if level == 3: - _, p, d = payments[moved[0]] - files["controller_memo.md"] = ( - "# Controller memo\n\nCorrections for this month's receivables close:\n\n" - f"1. INV-{voided} was voided. It is not owed and must not appear in the balances.\n" - f"2. The payment of {money(p / 100)} received on {d.isoformat()} was keyed against the wrong invoice. " - f"Apply all of it to INV-{moved[1]} instead of what its memo says.\n") - opener = rng.choice([ - "You are closing the month for the receivables team.", - "Finance needs the open balance of every customer invoice.", - "Our accounts receivable ledger needs reconciling before the month closes.", - ]) - if level == 1: - rule = ( - "/root/invoices.csv lists each invoice with its customer and amount in dollars. /root/payments.csv lists " - "every payment received, one row per payment, with the invoice it pays. An invoice's balance is its " - "amount minus all payments against it; it can receive several payments or none. If the payments add up " - "to more than the amount, the balance is 0.00, never negative, and the excess is ignored.") - else: - rule = ( - "/root/invoices.csv lists invoices with customer and amount in dollars. /root/payments.csv lists " - "payments in the order received; each memo names one or more invoices. First apply the credit notes in " - "/root/credit_notes.csv, each reducing its invoice's balance (not below 0). Then take the payments top " - "to bottom: each pays the invoices its memo names, in that order, clearing one invoice's balance before " - "the next. Leftover money is ignored.") - if level == 3: - rule += (" Memos write invoice numbers as INV-1042, inv 1042 or #1042. " - "/root/controller_memo.md holds corrections that override the files.") - instruction = ( - f"{opener}\n\n{rule}\n\n" - "Write /root/balances.csv with the header invoice,customer,balance,status and one row per invoice in " - "invoice order. balance is in dollars with 2 decimals; status is paid when the balance is 0.00, open when " - "it equals the full amount, partial otherwise. Example row: INV-1001,Arden Foods,0.00,paid. Balances are " - "checked to within 0.005." - ) - - def column(p, name): - return [r[name] for r in p["rows"]] - - checks = [ - ("test_header", lambda p: p["header"] == ["invoice", "customer", "balance", "status"]), - ("test_row_count", lambda p: len(p["rows"]) == len(want)), - ("test_invoice_ids", lambda p: column(p, "invoice") == [w[0] for w in want]), - ("test_customers", lambda p: column(p, "customer") == [w[1] for w in want]), - ("test_balances", lambda p: len(p["rows"]) == len(want) and all( - abs(float(b) - w[2] / 100) <= 0.005 + 1e-9 for b, w in zip(column(p, "balance"), want))), - ("test_status", lambda p: column(p, "status") == [w[3] for w in want]), - ] - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="balances.csv", kind="checks", parse="csv", checks=checks, - render=lambda: "invoice,customer,balance,status\n" - + "".join(f"{k},{c},{money(b / 100)},{st}\n" for k, c, b, st in want)), - root="/root", - ) - - -# ---------------------------------------------------------------- off3_meeting_slot - -PEOPLE = ["ana", "ben", "chen", "dara", "eli"] -OFFSETS = {1: [-5, -4, 0, 1, 2, 3], 2: [-4, -3, 0, 1, 2, 3, 5.5], 3: [-4, -3, 0, 1, 2, 3, 5.5]} -STEP = dt.timedelta(minutes=15) - - -def _fmt_off(h: float) -> str: - sign = "+" if h >= 0 else "-" - return f"UTC{sign}{int(abs(h)):02d}:{int(round(abs(h) % 1 * 60)):02d}" - - -def _local_hour(t: dt.datetime, off: float) -> float: - s = t + dt.timedelta(hours=off) - return s.hour + s.minute / 60 - - -def _slots(days, offs, busy_local, dur, ooo, lunch): - """Quarter-hour UTC starts where everyone is inside 09:00-17:00 local on one day and free.""" - out = [] - t, end = dt.datetime.combine(days[0], dt.time(0)), dt.datetime.combine(days[-1], dt.time(23, 45)) - length = dt.timedelta(minutes=dur) - while t <= end: - ok = True - for n, off in offs.items(): - s = t + dt.timedelta(hours=off) - e, day = s + length, s.date() - blocks = list(busy_local[n]) - if n in lunch: - blocks.append((dt.datetime.combine(day, lunch[n][0]), dt.datetime.combine(day, lunch[n][1]))) - if (ooo.get(n) == day or s < dt.datetime.combine(day, dt.time(9)) - or e > dt.datetime.combine(day, dt.time(17)) or any(s < b1 and e > b0 for b0, b1 in blocks)): - ok = False - break - if ok: - out.append(t) - t += STEP - return out - - -def build_meeting_slot(level: int, rng: random.Random) -> Built: - n_people, per_day = {1: (3, (5, 7)), 2: (4, (4, 6)), 3: (5, (4, 5))}[level] - dur = 30 # fixed: the oracle runs on every level and the length lives only in the instruction - days = [dt.date(2026, 11, 2) + dt.timedelta(days=i) for i in range(5)] - names = PEOPLE[:n_people] - while True: - offs = {} - for n in names: - offs[n] = rng.choice(OFFSETS[level]) - if max(offs.values()) - min(offs.values()) > 4.5 or len(set(offs.values())) < 2: - continue - busy = {n: [] for n in names} - for n in names: - for d in days: - for _ in range(rng.randint(*per_day)): - s = dt.datetime.combine(d, dt.time(8)) + STEP * rng.randint(0, 36) - busy[n].append((s, s + STEP * rng.randint(2, 6))) - busy[n].sort() - ooo, lunch = {}, {} - if level == 3: # place both notes where they move the answer: out of office on the day of the - first = _slots(days, offs, busy, dur, {}, {}) # earliest slot, lunch over the next one - if not first: - continue - who = rng.choice(names) - ooo[who] = (first[0] + dt.timedelta(hours=offs[who])).date() - second = _slots(days, offs, busy, dur, ooo, {}) - noon = [n for n in names if second and 11.5 < _local_hour(second[0], offs[n]) < 13] - if not noon: - continue - lunch[rng.choice(noon)] = (dt.time(12), dt.time(13)) - valid = _slots(days, offs, busy, dur, ooo, lunch) - if not valid: - continue - free = {n: [] for n in names} - flipped = busy # offsets read with the wrong sign; at L1 that also moves the UTC busy blocks - if level == 1: - flipped = {n: [(b0 - dt.timedelta(hours=2 * offs[n]), b1 - dt.timedelta(hours=2 * offs[n])) - for b0, b1 in v] for n, v in busy.items()} - naive = [_slots(days, offs, free, dur, ooo, lunch), - _slots(days, {n: -o for n, o in offs.items()}, flipped, dur, ooo, lunch)] - if level >= 2: - as_utc = {n: [(b0 + dt.timedelta(hours=offs[n]), b1 + dt.timedelta(hours=offs[n])) for b0, b1 in v] - for n, v in busy.items()} # busy read as UTC where it is local - naive.append(_slots(days, offs, as_utc, dur, ooo, lunch)) - if level == 3: - naive.append(_slots(days, offs, busy, dur, {}, lunch)) - naive.append(_slots(days, offs, busy, dur, ooo, {})) - if all(not v or v[0] != valid[0] for v in naive) and valid[0].date() != days[0]: - break - start, end = valid[0], valid[0] + dt.timedelta(minutes=dur) - - rows = [] - for n in names: - for b0, b1 in busy[n]: - if level == 1: - b0, b1 = b0 - dt.timedelta(hours=offs[n]), b1 - dt.timedelta(hours=offs[n]) - assert b0.date() == b1.date(), (n, b0, b1) - rows.append((b0, n, b1)) - rows.sort() - zone = "utc" if level == 1 else "local" - files = { - "people.csv": "person,utc_offset\n" + "".join(f"{n},{_fmt_off(offs[n])}\n" for n in names), - "busy.csv": f"person,date,start_{zone},end_{zone}\n" - + "".join(f"{n},{b0:%Y-%m-%d},{b0:%H:%M},{b1:%H:%M}\n" for b0, n, b1 in rows), - } - if level == 3: - (o_name, o_day), = ooo.items() - (l_name, _), = lunch.items() - files["calendar_notes.md"] = ( - "# Calendar notes\n\n" - f"- {o_name} is out of office for the whole local day {o_day.isoformat()}.\n" - f"- {l_name} takes lunch 12:00-13:00 local time every day; treat it as busy.\n") - opener = rng.choice([ - f"You are scheduling a {dur}-minute review for a distributed team and need the earliest time that works.", - f"The team lead asked you to book a {dur}-minute sync at the first time everyone can make it.", - ]) - where = "in UTC" if level == 1 else "in that person's local time" - notes = " /root/calendar_notes.md has extra constraints from the team." if level == 3 else "" - instruction = ( - f"{opener}\n\n/root/people.csv gives each person's UTC offset (UTC+05:30 means local = UTC + 5h30m). " - f"/root/busy.csv lists everyone's busy blocks, one per row, {where}.{notes}\n\n" - "A start time works when, for every person, the whole meeting falls inside 09:00-17:00 of one local day " - "and overlaps none of their busy blocks. A block ending at 10:00 does not clash with a meeting starting " - "at 10:00. Try starts on the quarter hour in UTC from 2026-11-02 00:00 to 2026-11-06 23:45 and take " - "the earliest that works.\n\n" - "Write /root/meeting.json as a JSON object with start_utc and end_utc in this format: " - '{"start_utc": "2026-12-01T14:15", "end_utc": "2026-12-01T14:45"}.' - ) - - def ts(v) -> dt.datetime: - got = dt.datetime.fromisoformat(v.strip().removesuffix("Z")) - if got.tzinfo is not None: - raise ValueError("naive UTC expected") - return got - - checks = [ - ("test_is_object", lambda p: isinstance(p, dict)), - ("test_keys", lambda p: set(p) == {"start_utc", "end_utc"}), - ("test_start_utc", lambda p: ts(p["start_utc"]) == start), - ("test_end_utc", lambda p: ts(p["end_utc"]) == end), - ] - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="meeting.json", kind="checks", parse="json", checks=checks, - render=lambda: json.dumps({"start_utc": f"{start:%Y-%m-%dT%H:%M}", - "end_utc": f"{end:%Y-%m-%dT%H:%M}"}) + "\n"), - root="/root", - ) - - -# ---------------------------------------------------------------- off3_pdf_xlsx_diff - -FIRST = ["Ava", "Ben", "Cara", "Dev", "Ena", "Femi", "Gus", "Hana", "Ivo", "Jun", "Kai", "Lena", "Milo", "Nia", - "Omar", "Pia", "Quin", "Rosa", "Sami", "Tess", "Uma", "Vik", "Wren", "Yara", "Zeke"] -LAST = ["Abara", "Brandt", "Costa", "Diaz", "Eklund", "Fischer", "Gallo", "Haddad", "Ito", "Jansen", "Kowal", - "Lindqvist", "Moreau", "Novak", "Okafor", "Petrov", "Quist", "Rossi", "Sato", "Tanaka", "Ueda", "Varga"] -DEPTS = ["Sales", "Finance", "Legal", "Support", "Operations", "IT", "HR", "Marketing", "Research"] -TITLES = ["Analyst", "Senior Analyst", "Engineer", "Senior Engineer", "Account Manager", "Manager", "Coordinator", - "Specialist", "Director", "Associate"] -COLS = ["ID", "Name", "Department", "Title", "Salary", "Years", "Score"] -NUMERIC = ("Salary", "Years", "Score") -NOTE = "Text cells were pasted from the HR system and some carry trailing spaces; those are not changes." - - -def _pdf_bytes(rows: list[list[str]], heading: str) -> bytes: - from reportlab.lib import colors - from reportlab.lib.pagesizes import letter - from reportlab.lib.styles import getSampleStyleSheet - from reportlab.platypus import Paragraph, SimpleDocTemplate, Table, TableStyle - - buf = io.BytesIO() - doc = SimpleDocTemplate(buf, pagesize=letter, invariant=1, title=heading) - table = Table([COLS] + rows, repeatRows=1) # the ruled grid keeps pdfplumber's cells whole - table.setStyle(TableStyle([("GRID", (0, 0), (-1, -1), 0.5, colors.black), - ("FONTNAME", (0, 0), (-1, -1), "Helvetica"), ("FONTSIZE", (0, 0), (-1, -1), 8)])) - doc.build([Paragraph(heading, getSampleStyleSheet()["Heading2"]), table]) - return buf.getvalue() - - -def _xlsx_bytes(rows: list[list], note: str | None) -> bytes: - import openpyxl - - wb = openpyxl.Workbook() - ws = wb.active - ws.title = "Employees" - ws.append(COLS) - for r in rows: - ws.append(r) - if note: - wb.create_sheet("Notes").append([note]) - buf = io.BytesIO() - wb.save(buf) - return buf.getvalue() - - -def _changed(field: str, v, rng: random.Random): - if field == "Salary": - return v + rng.choice([-1, 1, 1, 1]) * 10 * rng.randint(100, 900) - if field == "Years": - return v + rng.randint(1, 3) - if field == "Score": - steps = [k for k in range(-10, 11) if k and 20 <= round(v * 10) + k <= 50] - return (round(v * 10) + rng.choice(steps)) / 10 - if field == "Department": - return rng.choice([d for d in DEPTS if d != v]) - if field == "Title": - return rng.choice([t for t in TITLES if t != v]) - return f"{v.split()[0]} {rng.choice([n for n in LAST if n != v.split()[1]])}" - - -def build_pdf_xlsx_diff(level: int, rng: random.Random) -> Built: - n, n_del, n_hire, n_mod, n_two = {1: (40, (2, 3), (1, 2), (3, 5), 0), 2: (70, (3, 5), (1, 3), (5, 8), 0), - 3: (100, (5, 7), (2, 3), (7, 10), 2)}[level] - n_del, n_hire, n_mod = rng.randint(*n_del), rng.randint(*n_hire), rng.randint(*n_mod) - staff = {} - for k in sorted(rng.sample(range(1, 1000), n + n_hire)): - staff[f"EMP{k:05d}"] = {"Name": f"{rng.choice(FIRST)} {rng.choice(LAST)}", "Department": rng.choice(DEPTS), - "Title": rng.choice(TITLES), "Salary": 10 * rng.randint(4200, 14500), - "Years": rng.randint(0, 30), "Score": rng.randint(20, 50) / 10} - hires = set(rng.sample(sorted(staff), n_hire)) # in the workbook only, never reported - old_ids = [i for i in sorted(staff) if i not in hires] - deleted = sorted(rng.sample(old_ids, n_del)) - kept = [i for i in old_ids if i not in deleted] - current = {i: dict(staff[i]) for i in sorted(staff) if i not in deleted} - mods = [] - for j, i in enumerate(rng.sample(kept, n_mod)): - for f in rng.sample(COLS[1:], 2 if j < n_two else 1): - current[i][f] = _changed(f, staff[i][f], rng) - mods.append((i, f, staff[i][f], current[i][f])) - mods.sort(key=lambda m: (m[0], COLS.index(m[1]))) - unchanged = [i for i in kept if i not in {m[0] for m in mods}] - spaced = set() - if level == 3: # a fifth of the names carry a trailing space, at least one on an unchanged employee - spaced = {rng.choice(unchanged)} | set(rng.sample(sorted(current), len(current) // 5)) - xlsx_rows = [[i] + [current[i][c] + " " if c == "Name" and i in spaced else current[i][c] for c in COLS[1:]] - for i in sorted(current)] - if level >= 2: - rng.shuffle(xlsx_rows) - - def pdf_cell(c, v): - if c == "Salary": - return f"${v:,}" if level >= 2 else str(v) - return f"{v:.1f}" if c == "Score" else str(v) - - backup = dt.date(2026, 3, 31) + dt.timedelta(days=rng.randint(0, 90)) - files = { - "employees_backup.pdf": _pdf_bytes([[i] + [pdf_cell(c, staff[i][c]) for c in COLS[1:]] for i in old_ids], - f"Employee records backup, {backup.isoformat()}"), - "employees_current.xlsx": _xlsx_bytes(xlsx_rows, NOTE if level == 3 else None), - } - opener = rng.choice([ - "You are helping HR find undocumented changes to the employee database.", - "Payroll needs an audit of every edit made to the employee records since the last backup.", - ]) - notes = "; read its Notes sheet as well" if level == 3 else "" - money_note = ", even though the PDF prints salaries like $52,300" if level >= 2 else "" - instruction = ( - f"{opener} The old records are a PDF table, /root/employees_backup.pdf (columns {', '.join(COLS)}). " - f"The current records are in /root/employees_current.xlsx, sheet Employees{notes}.\n\n" - "1. Match employees by ID (EMP plus 5 digits).\n" - "2. IDs in the PDF but missing from the workbook are deleted. Employees hired after the backup appear only " - "in the workbook; do not report them.\n" - "3. For an ID in both, each field whose value changed is one entry with the old (PDF) and new (workbook) " - "value.\n\n" - f"Salary, Years and Score are numbers: compare them as numbers and write JSON numbers{money_note}. " - "The other fields are strings.\n\n" - "Write /root/diff_report.json like " - '{"deleted_employees": ["EMP00002"], "modified_employees": [{"id": "EMP00003", "field": "Salary", ' - '"old_value": 50020, "new_value": 55010}]}, with deleted_employees sorted by ID.' - ) - want = {(i, f): (a, b) for i, f, a, b in mods} - - def entries(p) -> list: - ms = p["modified_employees"] - if not isinstance(ms, list) or not all(isinstance(m, dict) and set(m) == {"id", "field", "old_value", - "new_value"} for m in ms): - raise ValueError("modified_employees must be a list of {id, field, old_value, new_value}") - return ms - - def is_num(v) -> bool: - return isinstance(v, (int, float)) and not isinstance(v, bool) - - def numbers_match(p) -> bool: - got = [m for m in entries(p) if m["field"] in NUMERIC] - return all(is_num(m["old_value"]) and is_num(m["new_value"]) - and abs(m["old_value"] - want[m["id"], m["field"]][0]) <= 1e-6 - and abs(m["new_value"] - want[m["id"], m["field"]][1]) <= 1e-6 for m in got) - - def text_matches(p) -> bool: - got = [m for m in entries(p) if m["field"] not in NUMERIC] - return all(isinstance(m["old_value"], str) and isinstance(m["new_value"], str) - and (m["old_value"].strip(), m["new_value"].strip()) == want[m["id"], m["field"]] for m in got) - - checks = [ - ("test_is_object", lambda p: isinstance(p, dict)), - ("test_keys", lambda p: set(p) == {"deleted_employees", "modified_employees"}), - ("test_deleted_employees", lambda p: p["deleted_employees"] == deleted), - ("test_modified_count", lambda p: len(entries(p)) == len(mods)), - ("test_modified_fields", lambda p: sorted((m["id"], m["field"]) for m in entries(p)) == sorted(want)), - ("test_numeric_values", numbers_match), - ("test_text_values", text_matches), - ] - - def render() -> str: - return json.dumps({"deleted_employees": deleted, - "modified_employees": [{"id": i, "field": f, "old_value": a, "new_value": b} - for i, f, a, b in mods]}, indent=1) + "\n" - - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="diff_report.json", kind="checks", parse="json", checks=checks, render=render), - root="/root", - ) - - -FAMILIES = [ - Family("off3_ar_recon", DOMAIN, "Reconcile receivables to balances", build_ar_recon, v3=True), - Family("off3_meeting_slot", DOMAIN, "Earliest meeting slot across time zones", build_meeting_slot, v3=True), - Family("off3_pdf_xlsx_diff", DOMAIN, "Diff a PDF backup against a workbook", build_pdf_xlsx_diff, v3=True), -] diff --git a/components/dnakhla/upstream/terminal_desk/families/science.py b/components/dnakhla/upstream/terminal_desk/families/science.py deleted file mode 100644 index 53ad31a79095946a977ffd011971ba967cf1904e..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/families/science.py +++ /dev/null @@ -1,250 +0,0 @@ -"""Natural science: fit first-order kinetics; reaction stoichiometry with a limiting reagent.""" - -import math -import random -import re - -from .base import Artifact, Built, Family, Field - -R_GAS = 8.314 - -# ---------------------------------------------------------------- sci_kinetics - - -def _fit_k(points: list[tuple[float, float]]) -> float: - """-slope of least-squares ln(C) against t.""" - xs = [t for t, _ in points] - ys = [math.log(c) for _, c in points] - n = len(xs) - mx, my = sum(xs) / n, sum(ys) / n - sxy = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) - sxx = sum((x - mx) ** 2 for x in xs) - return -sxy / sxx - - -def _run(rng: random.Random, k: float, n: int) -> list[tuple[int, float]]: - c0 = rng.uniform(0.5, 2.0) - span = rng.uniform(2.0, 3.5) * math.log(2) / k - pts = [] - for i in range(n): - t = round(span * i / (n - 1)) - c = c0 * math.exp(-k * t) * (1 + rng.gauss(0, 0.01)) - pts.append((t, c)) - return pts - - -def build_kinetics(level: int, rng: random.Random) -> Built: - if level < 3: - k = rng.uniform(0.002, 0.02) - pts = _run(rng, k, 12 if level == 1 else 14) - if level == 1: - data = [(t, round(c, 4)) for t, c in pts] - files = {"run.csv": "time_s,conc_M\n" + "".join(f"{t},{c:.4f}\n" for t, c in data)} - used = [(float(t), c) for t, c in data] - extra = "run.csv has time in seconds and concentration in mol/L." - else: - data = [(round(t / 60, 3), round(c * 1000, 2)) for t, c in pts] - bad = rng.randrange(2, len(data) - 1) - t_bad, c_bad = data[bad] - data[bad] = (t_bad, round(c_bad * rng.choice([0.55, 1.6]), 2)) - files = { - "run.csv": "time_min,conc_mM\n" + "".join(f"{t:.3f},{c:.2f}\n" for t, c in data), - "lab_notes.txt": f"The sample at t = {t_bad:.3f} min was a bad injection; exclude it from the fit.\n", - } - used = [(t * 60, c / 1000) for i, (t, c) in enumerate(data) if i != bad] - extra = "Mind the units in run.csv, and read lab_notes.txt." - kfit = _fit_k(used) - instruction = ( - "/app/run.csv follows a first-order decay over time. Find the rate constant k as minus the slope of " - "an ordinary least-squares line of ln(concentration) against time in seconds, and the half-life " - "ln(2)/k. " + extra + " " - 'Write /app/fit.json with the keys k_per_s (1/s) and half_life_s (seconds), ' - 'for example {"k_per_s": 0.005, "half_life_s": 138.6}.' - ) - return Built( - instruction=instruction, - files=files, - artifact=Artifact( - path="fit.json", - kind="json", - expected={"k_per_s": kfit, "half_life_s": math.log(2) / kfit}, - fields=[ - Field("k_per_s", "number", "rate constant in 1/s", rel=0.005), - Field("half_life_s", "number", "half-life in seconds", rel=0.005), - ], - ), - ) - t1 = rng.randint(288, 300) - t2 = t1 + rng.randint(15, 25) - ea = rng.uniform(40, 90) * 1000 - k1 = rng.uniform(0.001, 0.006) - k2 = k1 * math.exp(-ea / R_GAS * (1 / t2 - 1 / t1)) - files, fits = {}, [] - for temp, k in ((t1, k1), (t2, k2)): - data = [(t, round(c, 4)) for t, c in _run(rng, k, 12)] - files[f"run_{temp}K.csv"] = "time_s,conc_M\n" + "".join(f"{t},{c:.4f}\n" for t, c in data) - fits.append(_fit_k([(float(t), c) for t, c in data])) - ea_fit = R_GAS * math.log(fits[1] / fits[0]) / (1 / t1 - 1 / t2) / 1000 - instruction = ( - f"/app/run_{t1}K.csv and /app/run_{t2}K.csv are the same first-order decay at two temperatures. " - "For each run, k is minus the slope of an ordinary least-squares line of ln(concentration) against " - "time in seconds. Then find the activation energy from the Arrhenius equation using the two k values " - f"and R = {R_GAS} J/(mol K). Write /app/fit.json with the keys k_low_per_s and k_high_per_s (1/s, for " - "the colder and the warmer run) and ea_kj_per_mol (kJ/mol), " - 'for example {"k_low_per_s": 0.002, "k_high_per_s": 0.006, "ea_kj_per_mol": 60.0}.' - ) - return Built( - instruction=instruction, - files=files, - artifact=Artifact( - path="fit.json", - kind="json", - expected={"k_low_per_s": fits[0], "k_high_per_s": fits[1], "ea_kj_per_mol": ea_fit}, - fields=[ - Field("k_low_per_s", "number", f"k at {t1} K in 1/s", rel=0.005), - Field("k_high_per_s", "number", f"k at {t2} K in 1/s", rel=0.005), - Field("ea_kj_per_mol", "number", "activation energy in kJ/mol", rel=0.01), - ], - ), - ) - - -# ---------------------------------------------------------------- sci_stoich - -MASSES = { - "H": 1.008, "C": 12.011, "N": 14.007, "O": 15.999, "Na": 22.990, "Mg": 24.305, "Al": 26.982, - "P": 30.974, "S": 32.06, "Cl": 35.45, "K": 39.098, "Ca": 40.078, "Fe": 55.845, "Cu": 63.546, - "Ag": 107.868, "Ba": 137.327, -} - -# (equation, product index among products) -REACTIONS = { - 1: [ - "2 H2 + O2 -> 2 H2O", - "C3H8 + 5 O2 -> 3 CO2 + 4 H2O", - "2 Na + Cl2 -> 2 NaCl", - "Fe2O3 + 3 CO -> 2 Fe + 3 CO2", - "2 NaOH + H2SO4 -> Na2SO4 + 2 H2O", - "AgNO3 + NaCl -> AgCl + NaNO3", - ], - 2: [ - "Ca(OH)2 + 2 HCl -> CaCl2 + 2 H2O", - "2 Al + 3 CuSO4 -> Al2(SO4)3 + 3 Cu", - "Mg(OH)2 + 2 HNO3 -> Mg(NO3)2 + 2 H2O", - "3 Ba(NO3)2 + 2 Na3PO4 -> Ba3(PO4)2 + 6 NaNO3", - ], - 3: [ - "CuSO4*5H2O + 2 NaOH -> Cu(OH)2 + Na2SO4 + 5 H2O", - "FeSO4*7H2O + 2 KOH -> Fe(OH)2 + K2SO4 + 7 H2O", - "BaCl2*2H2O + Na2SO4 -> BaSO4 + 2 NaCl + 2 H2O", - "3 Ca(OH)2 + 2 H3PO4 -> Ca3(PO4)2 + 6 H2O", - ], -} - - -def molar_mass(formula: str) -> float: - total = 0.0 - for part in formula.split("*"): - m = re.match(r"^(\d+)(.*)$", part) - mult, body = (int(m.group(1)), m.group(2)) if m else (1, part) - total += mult * _group_mass(body) - return total - - -def _group_mass(s: str) -> float: - stack = [0.0] - i = 0 - while i < len(s): - ch = s[i] - if ch == "(": - stack.append(0.0) - i += 1 - elif ch == ")": - i += 1 - j = i - while j < len(s) and s[j].isdigit(): - j += 1 - n = int(s[i:j] or 1) - inner = stack.pop() - stack[-1] += inner * n - i = j - else: - m = re.match(r"([A-Z][a-z]?)(\d*)", s[i:]) - stack[-1] += MASSES[m.group(1)] * int(m.group(2) or 1) - i += len(m.group(0)) - return stack[0] - - -def _side(text: str) -> list[tuple[int, str]]: - out = [] - for term in text.split(" + "): - m = re.match(r"^(\d+) (.+)$", term.strip()) - out.append((int(m.group(1)), m.group(2)) if m else (1, term.strip())) - return out - - -def build_stoich(level: int, rng: random.Random) -> Built: - eq = rng.choice(REACTIONS[level]) - left, right = eq.split(" -> ") - reactants, products = _side(left), _side(right) - (ca, fa), (cb, fb) = reactants - cp, fp = rng.choice([p for p in products if p[1] not in ("H2O",)] or products) - while True: - mass_a = round(rng.uniform(5, 60), 2) - eq_a = mass_a / molar_mass(fa) / ca - ratio = rng.choice([rng.uniform(1.15, 1.6), rng.uniform(0.6, 0.87)]) - mass_b = round(eq_a * ratio * cb * molar_mass(fb), 2) - purity = {} - if level == 3: - who = rng.choice([fa, fb]) - purity[who] = round(rng.uniform(85, 97), 1) - yield_pct = round(rng.uniform(70, 95), 1) if level >= 2 else 100.0 - - def equivalents(f, coef, mass): - pure = mass * purity.get(f, 100.0) / 100 - return pure / molar_mass(f) / coef - - ea, eb = equivalents(fa, ca, mass_a), equivalents(fb, cb, mass_b) - limiting = fa if ea < eb else fb - if abs(ea / eb - 1) >= 0.08: - break - grams = min(ea, eb) * cp * molar_mass(fp) * yield_pct / 100 - lines = [f"Balanced equation: {eq}", f"Starting masses: {mass_a} g {fa}, {mass_b} g {fb}"] - if purity: - (who, pct), = purity.items() - lines.append(f"The {who} sample is {pct}% pure by mass; the rest is inert.") - if level >= 2: - lines.append(f"The isolated yield was {yield_pct}% of the theoretical yield.") - if level == 3 and any("*" in f for _, f in reactants): - lines.append("A formula like CuSO4*5H2O is a hydrate: the water molecules count toward its molar mass.") - files = { - "reaction.txt": "\n".join(lines) + "\n", - "atomic_masses.txt": "".join(f"{el} {m}\n" for el, m in MASSES.items()), - } - instruction = ( - f"/app/reaction.txt describes one batch. Using only the atomic masses in /app/atomic_masses.txt, find " - f"the limiting reagent, the molar mass of {fp}, and the grams of {fp} isolated. Write " - "/app/batch_report.json with the keys limiting_reagent (its formula as written in the equation), " - f'product_molar_mass (g/mol) and product_grams, for example {{"limiting_reagent": "{fa}", ' - '"product_molar_mass": 100.09, "product_grams": 12.5}.' - ) - return Built( - instruction=instruction, - files=files, - artifact=Artifact( - path="batch_report.json", - kind="json", - expected={"limiting_reagent": limiting, "product_molar_mass": molar_mass(fp), "product_grams": grams}, - fields=[ - Field("limiting_reagent", "text", "formula of the limiting reagent, written as in the equation"), - Field("product_molar_mass", "number", f"molar mass of {fp} in g/mol", tol=0.01), - Field("product_grams", "number", f"grams of {fp} isolated", rel=0.003), - ], - ), - ) - - -FAMILIES = [ - Family("sci_kinetics", "natural science", "Fit first-order kinetics", build_kinetics), - Family("sci_stoich", "natural science", "Limiting reagent and yield", build_stoich), -] diff --git a/components/dnakhla/upstream/terminal_desk/families/science3.py b/components/dnakhla/upstream/terminal_desk/families/science3.py deleted file mode 100644 index 061ceaebd9ba9da0778d4da8557f0ef0753d6e0f..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/families/science3.py +++ /dev/null @@ -1,452 +0,0 @@ -"""Natural science, v3: kinetics fit, stoichiometry batch, light-curve period. All stdlib. - -sci3_kinetics_fit and sci3_stoich_batch reshape v2's sci_kinetics and sci_stoich (the board's first natural-science -solves): same arithmetic and rule shape, with a SkillsBench-length instruction, /root output, inputs whose `head` is -cheap and whose `cat` is not, and kind="checks". sci3_lightcurve_period is new (exoplanet-detection-period shape): -detrend a spotted star's light curve and find the transit period with a box search over a stated grid. -""" - -import json -import math -import random - -from .base import Artifact, Built, Family -from .science import MASSES, R_GAS, _fit_k, _side, molar_mass - -ROOT = "/root" - - -def _ols(xs: list[float], ys: list[float]) -> tuple[float, float]: - """(slope, R squared) of the least-squares line of ys on xs.""" - n = len(xs) - mx, my = sum(xs) / n, sum(ys) / n - sxx = sum((x - mx) ** 2 for x in xs) - syy = sum((y - my) ** 2 for y in ys) - sxy = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) - return sxy / sxx, sxy * sxy / (sxx * syy) - - -def _rel(got, want: float, rel: float) -> bool: - return not isinstance(got, bool) and abs(float(got) - want) <= rel * abs(want) + 1e-12 - - -# ---------------------------------------------------------------- sci3_kinetics_fit - - -def _conc(order: int, c0: float, k: float, t: float) -> float: - return c0 * math.exp(-k * t) if order == 1 else c0 / (1 + k * c0 * t) - - -def _fit(order: int, pts: list[tuple[float, float]]) -> tuple[float, float]: - """(k, R squared) for one order on (t_s, c_M) points: v2's _fit_k for first order, 1/C slope for second.""" - ts = [t for t, _ in pts] - if order == 1: - return _fit_k(pts), _ols(ts, [math.log(c) for _, c in pts])[1] - return _ols(ts, [1 / c for _, c in pts]) - - -def _kin_run(rng: random.Random, order: int, n: int, milli: bool, bad: bool): - """One sampler run: (csv text, cleaned (t_s, c_M) points, bad sample id or None, points with the bad row).""" - dt = rng.choice([5, 6, 8, 10, 12, 15, 20, 24, 30]) - c0 = rng.uniform(20, 80) / 1000 if milli else rng.uniform(0.5, 2.0) - t_half = n * dt / rng.uniform(2.5, 3.8) - k = math.log(2) / t_half if order == 1 else 1 / (t_half * c0) - lod = rng.randint(3, 6) - conc = [_conc(order, c0, k, i * dt) * (1 + rng.gauss(0, 0.01)) for i in range(n - lod)] - bad_i = rng.randrange(int(0.6 * len(conc)), len(conc) - 1) if bad else None - if bad: # a double or half injection late in the run, where it moves the slope most - conc[bad_i] *= rng.choice([0.4, 2.5]) - lines = ["sample,time_min,conc_mM" if milli else "sample,time_s,conc_M"] - pts, every = [], [] - for i in range(n): - tt = f"{i * dt / 60:.3f}" if milli else str(i * dt) - if i >= len(conc): - lines.append(f"S{i + 1:03d},{tt}, bool: - """The true order wins the R squared comparison by a margin no rounding can flip.""" - return _fit(order, pts)[1] - _fit(3 - order, pts)[1] > 0.003 - - -def _notes(rng: random.Random, bad: list[tuple[str, str]]) -> str: - filler = [ - "Thermostat bath checked against the reference thermometer before the first run.", - "Stock solution prepared fresh this morning; no precipitate seen.", - "Sampler needle flushed between runs.", - "Absorbance cell cleaned and blanked at the start of the shift.", - ] - lines = rng.sample(filler, 2) + [ - f"Sample {sid} in {fname} was a bad injection; exclude it from the fit." for sid, fname in bad - ] - rng.shuffle(lines) - return "\n".join(f"- {line}" for line in lines) + "\n" - - -def build_kinetics(level: int, rng: random.Random) -> Built: - opener = rng.choice([ - "You are analysing the decomposition of a reactant at constant temperature.", - "A kinetics lab is studying how fast a reactant decomposes at constant temperature.", - ]) - out = f"{ROOT}/kinetics_report.json" - if level == 1: - while True: # the flagged rows must move k past twice the tolerance when they are kept - text, pts, every = _kin_flagged(rng, rng.randint(110, 125)) - k = _fit_k(pts) - if _order_clear(1, pts) and abs(_fit_k(every) / k - 1) > 0.01: - break - want = {"k_per_s": k, "half_life_s": math.log(2) / k} - files = {"data/run.csv": text} - instruction = ( - f"{opener} An automatic sampler logged one row per sample to {ROOT}/data/run.csv, with the columns " - "sample, time_s (seconds since mixing), conc_M (concentration in mol/L) and flag. The reaction is " - "first order. Near the end of the run the concentration fell below the detection limit: on those rows " - "the sampler wrote the limit itself in conc_M and 0.01: - break - half = math.log(2) / k if order == 1 else 1 / (k * pts[0][1]) - want = {"order": order, "k": k, "half_life_s": half} - files = {"data/run.csv": text, "data/lab_notes.txt": _notes(rng, [(bad_id, "run.csv")])} - instruction = ( - f"{opener} An automatic sampler logged {ROOT}/data/run.csv (columns sample, time_min, conc_mM). Rows " - "below the detection limit say 0.01): - break - want = {"order": order, "k_low": ks[0], "k_high": ks[1], "ea_kj_per_mol": ea} - files = {f"data/{names[j]}": runs[j][0] for j in range(2)} - files["data/lab_notes.txt"] = _notes(rng, [(runs[bad_run][2], names[bad_run])]) - instruction = ( - f"The same decomposition was run at {t_low} K and {t_high} K. An automatic sampler logged " - f"{ROOT}/data/{names[0]} and {ROOT}/data/{names[1]} (columns sample, time_min, conc_mM). Drop rows " - f"that say Na2SO4 + 2 H2O", - "AgNO3 + NaCl -> AgCl + NaNO3", - "AgNO3 + KCl -> AgCl + KNO3", - "BaCl2 + Na2SO4 -> BaSO4 + 2 NaCl", - "CaCl2 + Na2CO3 -> CaCO3 + 2 NaCl", - "2 KOH + H2SO4 -> K2SO4 + 2 H2O", -] -HYDRATES = [ - "CuSO4*5H2O + 2 NaOH -> Cu(OH)2 + Na2SO4 + 5 H2O", - "FeSO4*7H2O + 2 KOH -> Fe(OH)2 + K2SO4 + 7 H2O", - "BaCl2*2H2O + Na2SO4 -> BaSO4 + 2 NaCl + 2 H2O", - "MgSO4*7H2O + 2 NaOH -> Mg(OH)2 + Na2SO4 + 7 H2O", -] -SHELF = [ # other stockroom formulas, so the inventory is a real lookup - "NaCl", "KCl", "NaOH", "KOH", "HCl", "HNO3", "H2SO4", "Na2CO3", "NaHCO3", "CaCO3", "CaCl2", "MgCl2", - "KNO3", "NaNO3", "Na2SO4", "K2SO4", "MgSO4", "CuSO4", "AgNO3", "BaCl2", "Na3PO4", "H3PO4", "Ca(OH)2", - "Mg(OH)2", "Ba(NO3)2", "Ba(OH)2", "Al", "Cu", "Fe", "Mg", "Na2S2O3", "CuSO4*5H2O", "FeSO4*7H2O", - "MgSO4*7H2O", "BaCl2*2H2O", "NH4Cl", "(NH4)2SO4", "CaSO4*2H2O", "Na2HPO4", "KHCO3", -] -def _lot(rng: random.Random, used: set) -> str: - while True: - lot = f"{rng.choice('ABCDEFGHJK')}{rng.randrange(100, 1000)}" - if lot not in used: - used.add(lot) - return lot - - -def _date(rng: random.Random, lo: int = 0, hi: int = 600) -> str: - day = rng.randrange(lo, hi) # days after 2025-01-01, 30-day months, days capped at 28 so every date is real - return f"{2025 + day // 360}-{day % 360 // 30 + 1:02d}-{min(day % 30 + 1, 28):02d}" - - -def build_stoich(level: int, rng: random.Random) -> Built: - eq = rng.choice(HYDRATES if level == 3 else PLAIN) - left, right = eq.split(" -> ") - (ca, fa), (cb, fb) = _side(left) - cp, fp = rng.choice([p for p in _side(right) if p[1] != "H2O"]) - n_rows = {1: 100, 2: 110, 3: 220}[level] # L1-L2: cat ~1,700 tokens, so a dump still leaves room to finish - dated = level == 3 # certified dates and re-assayed lots only at L3 - while True: - used: set = set() - lots = {fa: _lot(rng, used), fb: _lot(rng, used)} - purity = {f: round(rng.uniform(88, 99.9), 1) for f in (fa, fb)} - stale = {} - if dated: # one batch lot was re-certified: an older row with a different purity stays in the table - who = rng.choice([fa, fb]) - stale[who] = round(min(99.9, purity[who] + rng.choice([-1, 1]) * rng.uniform(3, 8)), 1) - mass_a = round(rng.uniform(8, 60), 2) - eq_a = mass_a * purity[fa] / 100 / molar_mass(fa) / ca - ratio = rng.choice([rng.uniform(1.15, 1.6), rng.uniform(0.6, 0.87)]) - mass_b = round(eq_a * ratio * cb * molar_mass(fb) / (purity[fb] / 100), 2) - - def report(pur): - ea_, eb_ = (m * pur[f] / 100 / molar_mass(f) / c for m, f, c in ((mass_a, fa, ca), (mass_b, fb, cb))) - return (fa if ea_ < eb_ else fb), min(ea_, eb_) * cp * molar_mass(fp), ea_ / eb_ - - limiting, theo, r = report(purity) - if abs(r - 1) < 0.08: - continue - iso = round(theo * rng.uniform(0.62, 0.95), 2) - if stale: - lim2, theo2, _ = report(dict(purity, **stale)) - if lim2 == limiting and abs(theo2 / theo - 1) < 0.01: - continue # the stale row must change the answer - break - pct = iso / theo * 100 - - def extra(): # the fourth column: certified date at L3, shelf position at L1-L2 - return _date(rng, 0, 600) if dated else f"{rng.choice('ABCDEF')}{rng.randint(1, 9)}" - - # inventory: the batch lots plus shelf stock, shuffled; at L3 a few unrelated lots are re-certified too - rows = [(lots[f], f, purity[f], _date(rng, 300, 600) if dated else extra()) for f in (fa, fb)] - for f, p in stale.items(): - rows.append((lots[f], f, p, _date(rng, 0, 290))) - while len(rows) < n_rows: - lot, f = _lot(rng, used), rng.choice(SHELF) - rows.append((lot, f, round(rng.uniform(85, 99.9), 1), extra())) - if dated and rng.random() < 0.08: - rows.append((lot, f, round(rng.uniform(85, 99.9), 1), extra())) - rng.shuffle(rows) - header = "lot,formula,purity_pct," + ("certified" if dated else "shelf") - reagents = header + "\n" + "".join(f"{a},{b},{c},{d}\n" for a, b, c, d in rows) - atomic = "element,mass\n" + "".join(f"{el},{m}\n" for el, m in MASSES.items()) - charges = [(mass_a, fa), (mass_b, fb)] - rng.shuffle(charges) - batch = (f"Batch B-{rng.randrange(1000, 10000)}\nReaction: {eq}\n" - + "".join(f"Charged: {m:.2f} g {f} from lot {lots[f]}\n" for m, f in charges) - + f"Isolated: {iso:.2f} g {fp} (dried)\n") - files = {"data/batch.txt": batch, "data/reagents.csv": reagents, "data/atomic_masses.csv": atomic} - if dated: - files["data/README.md"] = ( - "# Stockroom inventory notes\n\nLots are re-assayed from time to time and the new assay is added as a " - "new row, so a lot can appear more than once in reagents.csv. Use the row with the latest certified " - "date; older rows are superseded.\n\nA formula written like CuSO4*5H2O is a hydrate: the water " - "molecules are part of the solid and count toward its molar mass.\n") - out = f"{ROOT}/batch_report.json" - example = rng.choice([f for f in SHELF if f not in eq and "*" not in f and "(" not in f]) - opener = rng.choice([ - "You are checking a production batch for a small chemistry lab.", - "A process chemist asks you to audit one pilot-plant batch.", - ]) - table = (f"{ROOT}/data/reagents.csv is the stockroom inventory ({header.replace(',', ', ')}) and " - f"{ROOT}/data/atomic_masses.csv the atomic masses.") - if level == 1: # the v2 shape: the batch and both lots are named right here - charged = " and ".join(f"{m:.2f} g of {f} from lot {lots[f]}" for m, f in charges) - intro = (f"{opener} The batch ran {eq}, charging {charged}; {iso:.2f} g of {fp} was isolated " - f"(record: {ROOT}/data/batch.txt). {table}") - else: - intro = (f"{opener} {ROOT}/data/batch.txt is the batch record: the balanced equation, grams charged per " - f"reagent lot and grams of product isolated. {table}" - + (f" Apply the notes in {ROOT}/data/README.md." if dated else "")) - instruction = ( - f"{intro}\n\n" - "Only the pure part of a charge reacts: grams x purity_pct / 100. The limiting reagent has the fewest " - "moles divided by its coefficient. The theoretical yield is the grams of product that amount makes; " - "percent yield = isolated / theoretical x 100.\n\n" - f"Write {out} with the keys limiting_reagent (formula as in the equation), product_molar_mass (g/mol), " - f'theoretical_yield_g and percent_yield, for example {{"limiting_reagent": "{example}", ' - '"product_molar_mass": 158.11, "theoretical_yield_g": 25.41, "percent_yield": 88.6}. Molar mass must be ' - "within 0.01 and the others within 0.3% (relative)." - ) - want = {"limiting_reagent": limiting, "product_molar_mass": molar_mass(fp), "theoretical_yield_g": theo, - "percent_yield": pct} - checks = [ - ("test_is_object", lambda p: isinstance(p, dict)), - ("test_keys", lambda p: set(p) == set(want)), - ("test_limiting_reagent", lambda p: isinstance(p["limiting_reagent"], str) - and p["limiting_reagent"].strip() == limiting), - ("test_product_molar_mass", lambda p: not isinstance(p["product_molar_mass"], bool) - and abs(float(p["product_molar_mass"]) - want["product_molar_mass"]) <= 0.01 + 1e-9), - ("test_theoretical_yield_g", lambda p: _rel(p["theoretical_yield_g"], theo, 0.003)), - ("test_percent_yield", lambda p: _rel(p["percent_yield"], pct, 0.003)), - ] - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="batch_report.json", kind="checks", parse="json", checks=checks, - render=lambda: json.dumps(want, indent=1) + "\n"), - root=ROOT, - ) - - -# ---------------------------------------------------------------- sci3_lightcurve_period - -CADENCE_D = 20 / 1440 -QUALITY_BAD = (1, 4, 32, 128, 1024) - - -def _in_transit(t: float, period: float, t0: float, dur: float) -> bool: - return abs((t - t0 + period / 2) % period - period / 2) < dur / 2 - - -def build_lightcurve(level: int, rng: random.Random) -> Built: - days = 40.0 if level == 3 else 27.0 - start = round(rng.uniform(60000, 61000), 2) - period = round(rng.uniform(1.5, 4.2), 5) - dur = rng.choice([0.08, 0.09, 0.10, 0.11, 0.12]) - depth = rng.uniform(0.005, 0.009) - t0 = start + rng.uniform(0, period) - prot, amp, phase = rng.uniform(3.5, 9.0), rng.uniform(0.005, 0.015), rng.uniform(0, 2 * math.pi) - second = None - if level == 3: # a shallower, shorter planet whose box signal stays well below the target's - while True: - p2 = round(rng.uniform(1.1, 4.8), 5) - ratio = max(p2, period) / min(p2, period) - if min(abs(ratio - m) for m in (1, 1.5, 2, 2.5, 3, 4)) > 0.12: - break - second = (p2, start + rng.uniform(0, p2), 0.05, 0.35 * depth) - dump = None - if level >= 2: # momentum dump: quality 0 but corrupted by a ramp - a = round(start + rng.uniform(0.2, 0.8) * days, 3) - dump = (a, round(a + 0.5, 3), rng.choice([-1, 1]) * rng.uniform(0.01, 0.02)) - lines = ["# time_mjd flux quality"] - for i in range(int(days / CADENCE_D)): - t = start + i * CADENCE_D - x = 2 * math.pi * (t - start) / prot + phase - f = 1 + amp * math.sin(x) + 0.3 * amp * math.sin(2 * x + 1.0) - if _in_transit(t, period, t0, dur): - f -= depth - if second and _in_transit(t, second[0], second[1], second[2]): - f -= second[3] - f += rng.gauss(0, 0.0009) - q = 0 - if rng.random() < 0.03: - q = rng.choice(QUALITY_BAD) - f *= 1 + rng.choice([-1, 1]) * rng.uniform(0.02, 0.08) - if dump and dump[0] <= t <= dump[1]: - f *= 1 + dump[2] * (t - dump[0]) / 0.5 - lines.append(f"{t:.5f} {f:.6f} {q}") - files = {"data/lc.txt": "\n".join(lines) + "\n"} - if dump: - files["data/README.md"] = ( - "# Light curve notes\n\nBetween MJD {:.3f} and {:.3f} the spacecraft fired its thrusters (momentum " - "dump). Those points carry quality 0 but are corrupted: discard every point in that interval before " - "searching.\n".format(dump[0], dump[1])) - out = f"{ROOT}/period.txt" - hours = round(dur * 24, 2) - example = "2.44535" if abs(period - 2.44535) > 0.05 else "3.81726" # never near the answer - notes = f" Read {ROOT}/data/README.md for other data to discard." if dump else "" - two = " The data may hold two transit signals; report the deeper one." if second else "" - instruction = ( - f"{ROOT}/data/lc.txt is a space-telescope light curve: a comment line, then rows of time (MJD), " - "normalized flux and a quality flag (0 means good), one every 20 minutes. The star is spotted, so its " - "brightness swings by about one percent as it rotates every few days. Hidden under that is a planet " - f"whose transit dims the star by about 0.5-0.9% for {hours} hours ({dur:.2f} d) once per orbit.\n\n" - f"1. Drop every point with a nonzero quality flag.{notes}\n" - "2. Remove the stellar variability, for example by dividing by a running median about 0.75 d wide.\n" - "3. Search trial periods from 1.000 to 5.000 d in steps of 0.001 d for the periodic box-shaped dip of " - f"that duration. The rotation period is not the answer.{two}\n\n" - f"Write the period in days to {out} as one number with exactly 5 decimals, for example {example}. It is " - "accepted within 0.2% of the true period." - ) - - def single(text): - return len(text.split()) == 1 and float(text.strip()) > 0 - - checks = [ - ("test_single_number", single), - ("test_five_decimals", lambda s: len(s.strip().partition(".")[2]) == 5 and s.strip().count(".") == 1), - ("test_period_value", lambda s: abs(float(s.strip()) - period) <= 0.002 * period), - ] - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="period.txt", kind="checks", parse="text", checks=checks, - render=lambda: f"{period:.5f}\n"), - root=ROOT, - notes={"period": period, "second": second}, - ) - - -FAMILIES = [ - Family("sci3_kinetics_fit", "natural science", "Kinetics order, rate constant and half-life", - build_kinetics, v3=True), - Family("sci3_stoich_batch", "natural science", "Batch limiting reagent and yield from a stockroom table", - build_stoich, v3=True), - Family("sci3_lightcurve_period", "natural science", "Transit period from a spotted star's light curve", - build_lightcurve, v3=True), -] diff --git a/components/dnakhla/upstream/terminal_desk/families/security.py b/components/dnakhla/upstream/terminal_desk/families/security.py deleted file mode 100644 index 0c4b0b80daaaf2a7ace98eee255aa68138e4e2e9..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/families/security.py +++ /dev/null @@ -1,224 +0,0 @@ -"""Cybersecurity: find brute-forced SSH logins; evaluate first-match firewall rules.""" - -import datetime as dt -import ipaddress -import random - -from .base import Artifact, Built, Family, Field - -USERS = ["alice", "bob", "carol", "deploy", "backup", "root", "admin", "git"] - -# ---------------------------------------------------------------- sec_auth - - -def _ip(rng: random.Random, v6: bool = False) -> str: - if v6: - return f"2001:db8:{rng.randint(1, 0xffff):x}::{rng.randint(1, 0xffff):x}" - net = rng.choice(["198.51.100", "203.0.113", "192.0.2"]) - return f"{net}.{rng.randint(2, 254)}" - - -def build_auth(level: int, rng: random.Random) -> Built: - k = {1: 5, 2: 4, 3: 4}[level] - while True: - day = dt.datetime(2026, 11, 3, 0, 0, 0) - events = [] # (time, ip, kind, user) - actors = [] - n_actors = {1: 8, 2: 14, 3: 20}[level] - used = set() - allow_nets = ["198.51.100.0/26"] if level == 3 else [] - for _ in range(n_actors): - v6 = level >= 2 and rng.random() < 0.25 - ip = _ip(rng, v6) - if ip in used: - continue - used.add(ip) - role = rng.choice(["brute_win", "brute_fail", "legit", "legit_typo"]) - t = day + dt.timedelta(seconds=rng.randint(0, 80000)) - if role.startswith("brute"): - fails = rng.randint(k - 2, k + 8) - for _ in range(fails): - user = rng.choice(USERS) - invalid = level >= 2 and user in ("admin", "git") and rng.random() < 0.7 - events.append((t, ip, "fail_invalid" if invalid else "fail", user)) - t += dt.timedelta(seconds=rng.randint(1, 20)) - if role == "brute_win": - events.append((t, ip, "accept", rng.choice(["root", "deploy", "backup"]))) - t += dt.timedelta(seconds=rng.randint(30, 600)) - if rng.random() < 0.5: - events.append((t, ip, "fail", "root")) - else: - user = rng.choice(USERS[:4]) - if role == "legit_typo": - for _ in range(rng.randint(1, k - 1)): - events.append((t, ip, "fail", user)) - t += dt.timedelta(seconds=rng.randint(3, 30)) - events.append((t, ip, "accept", user)) - actors.append(ip) - if level == 3: - scanner = f"198.51.100.{rng.randint(2, 60)}" - if scanner not in used: - t = day + dt.timedelta(seconds=rng.randint(0, 80000)) - for _ in range(k + 3): - events.append((t, scanner, "fail", "root")) - t += dt.timedelta(seconds=2) - events.append((t, scanner, "accept", "audit")) - events.sort() - fails, breach = {}, {} - for t, ip, kind, user in events: - if kind.startswith("fail"): - if ip not in breach: - fails[ip] = fails.get(ip, 0) + 1 - elif ip not in breach and fails.get(ip, 0) >= k: - breach[ip] = t - elif kind == "accept" and ip not in breach: - fails[ip] = fails.get(ip, 0) - breach.setdefault(ip, None) - hits = { - ip: t - for ip, t in breach.items() - if t is not None and not any(ipaddress.ip_address(ip) in ipaddress.ip_network(n) for n in allow_nets) - } - if 1 <= len(hits) <= 5: - break - def line(t, ip, kind, user, pid): - port = rng.randint(30000, 65000) - stamp = f"{t:%b} {t.day:2d} {t:%H:%M:%S}" - if kind == "fail": - msg = f"Failed password for {user} from {ip} port {port} ssh2" - elif kind == "fail_invalid": - msg = f"Failed password for invalid user {user} from {ip} port {port} ssh2" - else: - method = "publickey" if level >= 2 and rng.random() < 0.4 else "password" - msg = f"Accepted {method} for {user} from {ip} port {port} ssh2" - return f"{stamp} bastion sshd[{pid}]: {msg}" - - out = [] - for t, ip, kind, user in events: - pid = rng.randint(1000, 60000) - out.append((t, line(t, ip, kind, user, pid))) - if rng.random() < 0.3: - stamp = f"{t:%b} {t.day:2d} {t:%H:%M:%S}" - out.append((t, f"{stamp} bastion sshd[{pid}]: Connection closed by {ip} port {rng.randint(30000, 65000)} [preauth]")) - files = {} - if level == 3: - cut = len(out) // 2 - files["auth.log.1"] = "\n".join(s for _, s in out[:cut]) + "\n" - files["auth.log"] = "\n".join(s for _, s in out[cut:]) + "\n" - files["allowlist.txt"] = ( - "Internal audit scanners. Their activity is expected; never report them:\n" - + "".join(f" {n}\n" for n in allow_nets) - ) - where = "auth.log.1 (older) and auth.log (newer) in /app hold one day of sshd logs; never block a source in allowlist.txt." - else: - files["auth.log"] = "\n".join(s for _, s in out) + "\n" - where = "auth.log in /app holds one day of sshd logs." - instruction = ( - f"{where} Block every source IP that logged at least {k} failed password attempts (for any user, valid " - "or not) before its first accepted login (password or key); lines after that login do not count. " - "Write the IPs to /app/blocked.txt, one per line, nothing else." - ) - artifact = Artifact(path="blocked.txt", kind="lines", expected=sorted(hits)) - return Built(instruction=instruction, files=files, artifact=artifact) - - -# ---------------------------------------------------------------- sec_fw - - -def _port_spec(rng: random.Random) -> tuple[str, set | None]: - kind = rng.random() - if kind < 0.45: - p = rng.choice([22, 53, 80, 443, 3306, 5432, 6379, 8080]) - return str(p), {p} - if kind < 0.7: - ps = rng.sample([22, 25, 80, 443, 8080, 8443], 2) - return ",".join(map(str, ps)), set(ps) - if kind < 0.9: - lo = rng.choice([1000, 3000, 8000]) - hi = lo + rng.choice([99, 999]) - return f"{lo}-{hi}", set(range(lo, hi + 1)) - return "any", None - - -NETS = ["10.0.0.0/8", "10.20.0.0/16", "10.20.5.0/24", "192.168.0.0/16", "192.168.10.0/24", "172.16.0.0/12", "any"] - - -def build_fw(level: int, rng: random.Random) -> Built: - n_rules, n_conn = {1: 5, 2: 9, 3: 14}[level], {1: 15, 2: 40, 3: 70}[level] - while True: - rules = [] - for _ in range(n_rules): - action = rng.choice(["allow", "allow", "deny"]) - proto = rng.choice(["tcp", "tcp", "udp", "any"]) - net = rng.choice(NETS if level >= 2 else ["10.0.0.0/8", "192.168.0.0/16", "any"]) - spec, ports = _port_spec(rng) - disabled = level == 3 and rng.random() < 0.2 - rules.append((action, proto, net, spec, ports, disabled)) - conns = [] - for i in range(n_conn): - src = rng.choice( - [ - f"10.{rng.choice([20, rng.randint(0, 255)])}.{rng.choice([5, rng.randint(0, 255)])}.{rng.randint(1, 254)}", - f"192.168.{rng.choice([10, rng.randint(0, 255)])}.{rng.randint(1, 254)}", - f"172.{rng.randint(10, 40)}.{rng.randint(0, 255)}.{rng.randint(1, 254)}", - f"203.0.113.{rng.randint(1, 254)}", - ] - ) - proto = rng.choice(["tcp", "tcp", "udp"]) - port = rng.choice([22, 22, 53, 80, 443, 3306, 5432, 8080, 8443, 1080, 3100, 8050, 25]) - conns.append((f"c{i + 1:03d}", src, proto, port)) - - def match(rule, src, proto, port): - action, rproto, net, _, ports, disabled = rule - if disabled: - return False - if rproto != "any" and rproto != proto: - return False - if net != "any" and ipaddress.ip_address(src) not in ipaddress.ip_network(net): - return False - return ports is None or port in ports - - hit_count = {i: 0 for i in range(n_rules + 1)} - allowed, denied_ssh, verdicts = 0, [], [] - for cid, src, proto, port in conns: - num = next((i + 1 for i, r in enumerate(rules) if match(r, src, proto, port)), 0) - hit_count[num] += 1 - verdict = rules[num - 1][0] if num else "deny" - verdicts.append({"id": cid, "verdict": verdict, "rule": num}) - if verdict == "allow": - allowed += 1 - elif port == 22: - denied_ssh.append(cid) - ranked = sorted(hit_count.items(), key=lambda kv: -kv[1]) - if ranked[0][1] > ranked[1][1] and 0 < allowed < n_conn and denied_ssh: - break - lines = ["# first matching rule wins; a connection no rule matches is denied (default deny)"] - for i, (action, proto, net, spec, _, disabled) in enumerate(rules, start=1): - text = f"{i} {action} proto={proto} src={net} port={spec}" - lines.append(f"# {text} (disabled, not loaded)" if disabled else text) - files = { - "rules.txt": "\n".join(lines) + "\n", - "connections.csv": "id,src_ip,proto,dst_port\n" + "".join(f"{c},{s},{p},{d}\n" for c, s, p, d in conns), - } - instruction = ( - "rules.txt and connections.csv are in /app. Evaluate every connection against the rules: a rule matches " - "when its proto equals the connection's (or is any), the source IP is inside its src network (or src is " - "any), and the destination port is in its port list or range (or port is any). The first matching rule " - "decides; commented-out rules are not loaded; no match means deny. Write /app/verdicts.csv with the " - "header id,verdict,rule and one row per connection: verdict is allow or deny, rule is the deciding " - "rule's number (0 for the default deny). Example: c001,allow,3" - ) - artifact = Artifact( - path="verdicts.csv", - kind="csv", - key=("id",), - fields=[Field("id", "text"), Field("verdict", "text"), Field("rule", "int")], - expected=verdicts, - ) - return Built(instruction=instruction, files=files, artifact=artifact) - - -FAMILIES = [ - Family("sec_auth", "cybersecurity", "Find brute-forced SSH logins", build_auth), - Family("sec_fw", "cybersecurity", "Evaluate firewall rules", build_fw), -] diff --git a/components/dnakhla/upstream/terminal_desk/families/security3.py b/components/dnakhla/upstream/terminal_desk/families/security3.py deleted file mode 100644 index aa79919b9af169f10430b6d5e0d97d7c42272c0f..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/families/security3.py +++ /dev/null @@ -1,521 +0,0 @@ -"""Cybersecurity v3: SSH brute-force triage, firewall verdicts, off-hours exfiltration flows. - -Each generator computes the expected answer itself from the records it emits; the oracle -scripts in terminal_desk/oracles/ only prove the files carry everything the answer needs. -""" - -import ipaddress -import json -import random - -from .base import Artifact, Built, Family - -ROOT = "/root" -DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") - - -def _clock(sec: int) -> str: - return f"{sec // 3600:02d}:{sec // 60 % 60:02d}:{sec % 60:02d}" - - -def _public_ip(rng: random.Random, used: set) -> str: - while True: - ip = f"{rng.choice([37, 45, 61, 77, 89, 91, 94])}.{rng.randint(1, 99)}.{rng.randint(0, 99)}.{rng.randint(2, 99)}" - if ip not in used: - used.add(ip) - return ip - - -def _in_any(ip: str, nets) -> bool: - addr = ipaddress.ip_address(ip) - return any(addr in ipaddress.ip_network(n) for n in nets) - - -def _ip_checks(want: set) -> list: - def one_ip_per_line(lines): - for s in lines: - ipaddress.ip_address(s) - return True - - return [ - ("test_one_ip_per_line", one_ip_per_line), - ("test_no_duplicates", lambda lines: len(lines) == len(set(lines))), - ("test_no_false_positives", lambda lines: set(lines) <= want), - ("test_no_missed_ips", lambda lines: want <= set(lines)), - ] - - -# ---------------------------------------------------------------- sec3_auth_triage - -USERS_VALID = ["root", "deploy", "git", "backup", "ubuntu", "alice", "bob", "carol"] -USERS_INVALID = ["admin", "oracle", "test", "postgres", "user", "pi", "ftp", "guest"] - - -def build_auth(level: int, rng: random.Random) -> Built: - k, w = 5, 10 # fixed: the rule lives in the instruction, so one oracle serves every instance - span = w * 60 - target = {1: 150, 2: 300, 3: 450}[level] - while True: - used: set = set() - lines = [] # (sec, ip, text, failures) - allow = [] - - def fail(t, ip, user=None): - user = user or rng.choice(USERS_VALID[:5] + USERS_INVALID) - if user in USERS_INVALID: - if level >= 2: - lines.append((t, ip, f"Invalid user {user} from {ip}", 0)) - lines.append((t, ip, f"Failed password for invalid user {user} from {ip}", 1)) - else: - lines.append((t, ip, f"Failed password for {user} from {ip}", 1)) - - def burst(ip, n, gap_lo, gap_hi, t=None, repeats=True): - t = rng.randint(0, 86399 - n * gap_hi - 700) if t is None else t - times, i = [], 0 - user = rng.choice(USERS_VALID[:5] + USERS_INVALID) - while i < n: - fail(t, ip, user) - times.append(t) - i += 1 - if repeats and level == 3 and user in USERS_VALID and n - i >= 2 and rng.random() < 0.3: - rep = rng.randint(2, min(4, n - i)) - t += rng.randint(1, 3) * rep - lines.append((t, ip, f"message repeated {rep} times: [ Failed password for {user} from {ip}]", rep)) - times += [t] * rep - i += rep - t += rng.randint(gap_lo, gap_hi) - if rng.random() < 0.3: - user = rng.choice(USERS_VALID[:5] + USERS_INVALID) - lines.append((t, ip, f"Connection closed by {ip} [preauth]", 0)) - return times - - def session(ip, user=None): - user = user or rng.choice(USERS_VALID[3:]) - t = rng.randint(0, 80000) - method = rng.choice(["password", "publickey"]) - lines.append((t, ip, f"Accepted {method} for {user} from {ip}", 0)) - lines.append((t + rng.randint(30, 5000), ip, f"Disconnected from user {user} {ip}", 0)) - - n_brute = rng.randint(*{1: (2, 4), 2: (3, 5), 3: (4, 6)}[level]) - for _ in range(n_brute): - burst(_public_ip(rng, used), rng.randint(k, k + 9), 2, 40) - for _ in range({1: 2, 2: 3, 3: 4}[level]): # slow: spaced out, unless a collapsed repeat bunches k (L3) - lo = span // (k - 1) + 5 - burst(_public_ip(rng, used), rng.randint(k + 1, k + 4), lo, lo + 120) - for _ in range({1: 2, 2: 3, 3: 4}[level]): # near miss: k-1 quick failures, then a login - ip = _public_ip(rng, used) - user = rng.choice(USERS_VALID[5:]) - t0 = rng.randint(0, 80000) - for j in range(k - 1): - fail(t0 + 9 * j, ip, user) - lines.append((t0 + 9 * (k - 1), ip, f"Accepted password for {user} from {ip}", 0)) - if level >= 2: - for exact in (True, False): # k failures spanning exactly the window (blocked) or one second more - ip = _public_ip(rng, used) - t0 = rng.randint(0, 80000) - cuts = sorted(rng.sample(range(1, span), k - 2)) - for off in [0] + cuts + [span + (0 if exact else 1)]: - fail(t0 + off, ip) - prefix, base = f"10.{rng.randint(2, 9)}.{rng.randint(2, 9)}", rng.choice([0, 64]) - allow = [f"{prefix}.{base}/26"] # the audit scanner network; its neighbour /26 is not exempt - scanner = f"{prefix}.{base + rng.randint(1, 62)}" - outsider = f"{prefix}.{64 + rng.randint(1, 35) if base == 0 else rng.randint(2, 62)}" - used.update({scanner, outsider}) - burst(scanner, rng.randint(k + 2, k + 8), 1, 5) - burst(outsider, rng.randint(k, k + 4), 3, 30) - straddle = None - if level == 3: - straddle = _public_ip(rng, used) - times = burst(straddle, k, 5, 30, t=rng.randint(40000, 46000), repeats=False) - cut = times[1] + 1 - offices = [f"10.0.{rng.randint(1, 9)}.{rng.randint(2, 99)}" for _ in range(rng.randint(4, 7))] - while len(lines) < target - 20: - r = rng.random() - if r < 0.45: - session(rng.choice(offices)) - else: # internet background noise: one or two failures - ip = _public_ip(rng, used) - t = rng.randint(0, 86000) - for j in range(rng.randint(1, 2)): - fail(t + j * rng.randint(60, 900), ip) - lines = [ln for ln in lines if ln[0] < 86400] - lines.sort(key=lambda x: x[0]) - - def blocked(notice=0, repeat=None): - """The answer; notice=1 or repeat=1 give the two README misreadings.""" - per_ip: dict = {} - for t, ip, msg, n in lines: - if msg.startswith("Invalid user"): - n = notice - elif repeat is not None and msg.startswith("message repeated"): - n = repeat - per_ip.setdefault(ip, []).extend([t] * n) - out = set() - for ip, ts in per_ip.items(): - ts.sort() - if any(ts[i + k - 1] - ts[i] <= span for i in range(len(ts) - k + 1)) and not _in_any(ip, allow): - out.add(ip) - return out - - want = blocked() - ok = 2 <= len(want) <= 10 and (straddle is None or straddle in want) - if level >= 2: # counting the Invalid user notices as attempts must change the answer - ok = ok and blocked(notice=1) != want - if level == 3: # reading a repeated-message line as one attempt must change the answer - ok = ok and blocked(repeat=1) != want - if ok: - break - - def text(chunk): - return "".join(f"{_clock(t)} {msg}\n" for t, _, msg, _ in chunk) - - if level == 3: - files = {"auth.log.1": text([x for x in lines if x[0] < cut]), "auth.log": text([x for x in lines if x[0] >= cut])} - where = ("The log was rotated at midday: /root/auth.log.1 holds the morning and /root/auth.log the rest of " - "3 November 2026.") - else: - files = {"auth.log": text(lines)} - where = "The sshd messages for 3 November 2026 are in /root/auth.log, one per line." - readme = "" - if level >= 2: - readme = ("# Bastion notes\n\nThe audit team runs a password-spray test from the scanner network below. " - "Its addresses are expected to fail logins: never block an address inside it.\n\n" - f"- {allow[0]}\n\nsshd logs `Invalid user NAME from IP` just before the matching failed password " - "line. That line is a notice, not a separate attempt.\n") - if level == 3: - readme += ("\nWhen sshd repeats an identical message, syslog writes `message repeated N times: [ ... ]` " - "instead. That line stands for N more failed attempts at that line's time.\n") - files["README.md"] = readme - opener = rng.choice([ - "You are on call for the company's SSH bastion host and need to stop a password-guessing attack.", - "A bastion host is being hit by SSH password guessing, and you have been asked to decide which sources to block.", - ]) - notes = " Notes from the security team are in /root/README.md." if level >= 2 else "" - instruction = ( - f"{opener} {where} Each line starts with the time as HH:MM:SS, for example " - f"`00:14:07 Failed password for root from 45.9.2.18`.{notes}\n\n" - "A failed attempt is a `Failed password for USER from IP` line, including `Failed password for invalid user " - "USER from IP`. Accepted logins, disconnects and other messages are not attempts.\n\n" - f"Block a source IP when it has at least {k} failed attempts within {w} minutes: some {k} of its failures, " - f"where the last is no more than {span} seconds after the first. Failures spread over a longer time do not count " - "together.\n\n" - "Write /root/blocked.txt with each blocked IP once, one per line, in any order, and nothing else." - ) - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="blocked.txt", kind="checks", parse="lines", checks=_ip_checks(want), - render=lambda: "".join(f"{ip}\n" for ip in sorted(want))), - root=ROOT, - notes={"blocked": sorted(want), "k": k, "window_s": span}, - ) - - -# ---------------------------------------------------------------- sec3_fw_verdicts - -FW_NETS = ["10.0.0.0/8", "10.20.0.0/16", "10.20.5.0/24", "192.168.0.0/16", "192.168.10.0/24", "172.16.0.0/12", - "203.0.113.0/24", "any"] -FW_PORTS = [22, 25, 53, 80, 443, 3306, 5432, 6379, 8080, 8443] - - -def _fw_ports(rng: random.Random) -> tuple[str, set | None]: - r = rng.random() - if r < 0.4: - p = rng.choice(FW_PORTS) - return str(p), {p} - if r < 0.65: - ps = sorted(rng.sample(FW_PORTS, rng.randint(2, 3))) - return ";".join(map(str, ps)), set(ps) - if r < 0.88: - lo = rng.choice([1000, 3000, 5400, 8000]) - hi = lo + rng.choice([99, 999]) - return f"{lo}-{hi}", set(range(lo, hi + 1)) - return "any", None - - -def _fw_src(rng: random.Random, nets: list[str]) -> str: - net = ipaddress.ip_network(rng.choice(nets)) - if rng.random() < 0.35: # from anywhere - return rng.choice([f"10.{rng.randint(0, 40)}.{rng.randint(0, 20)}.{rng.randint(1, 254)}", - f"192.168.{rng.choice([10, 11, rng.randint(0, 40)])}.{rng.randint(1, 254)}", - f"172.{rng.randint(12, 34)}.{rng.randint(0, 20)}.{rng.randint(1, 254)}", - f"203.0.113.{rng.randint(1, 254)}", f"198.51.100.{rng.randint(1, 254)}"]) - return str(net.network_address + rng.randint(1, net.num_addresses - 2)) - - -def build_fw(level: int, rng: random.Random) -> Built: - n_rules, n_conn = {1: 5, 2: 8, 3: 11}[level], {1: 120, 2: 220, 3: 360}[level] - protos = ["tcp", "tcp", "udp", "any"] + (["icmp"] if level >= 2 else []) - groups = {} - if level == 3: - groups = {"office": sorted(rng.sample(["10.20.5.0/24", "10.20.6.0/24", "10.20.9.0/24"], 2)), - "vpn": [rng.choice(["172.16.8.0/22", "172.20.0.0/16"])], - "partners": sorted(rng.sample(["203.0.113.0/25", "198.51.100.0/24", "192.168.10.0/24"], 2))} - while True: - nums = sorted(rng.sample(range(100, 1000, 10), n_rules)) - rules = [] # (no, action, proto, src_text, nets or None, port_text, ports or None, enabled) - for no in nums: - proto = rng.choice(protos) - if level == 3 and rng.random() < 0.3: - g = rng.choice(sorted(groups)) - src_text, nets = f"@{g}", groups[g] - else: - src_text = rng.choice(FW_NETS if level >= 2 else ["10.0.0.0/8", "192.168.0.0/16", "172.16.0.0/12", "any"]) - nets = None if src_text == "any" else [src_text] - ptext, ports = ("any", None) if proto == "icmp" else _fw_ports(rng) - enabled = not (level == 3 and rng.random() < 0.2) - rules.append((no, rng.choice(["allow", "allow", "deny"]), proto, src_text, nets, ptext, ports, enabled)) - src_pool = [n for r in rules if r[4] for n in r[4]] - if not src_pool: # every rule says src=any: draw a new table - continue - ends = [int(x) for r in rules if "-" in r[5] for x in r[5].split("-")] - conns = [] - for i in range(n_conn): - proto = rng.choice(["tcp", "tcp", "tcp", "udp"] + (["icmp"] if level >= 2 else [])) - port = "" if proto == "icmp" else str(rng.choice(FW_PORTS + [1080, 3100, 5432, 8050, 1234, 5500, 9000] + ends * 2)) - conns.append((f"c{i + 1:04d}", _fw_src(rng, src_pool), proto, port)) - - def decide(rule_list): - out = [] - for cid, src, proto, port in conns: - hit = 0 - for no, action, rproto, _, nets, _, ports, enabled in rule_list: - if not enabled or rproto not in ("any", proto): - continue - if nets is not None and not _in_any(src, nets): - continue - if ports is not None and (port == "" or int(port) not in ports): - continue - hit = no - break - verdict = next(r[1] for r in rule_list if r[0] == hit) if hit else "deny" - out.append((cid, verdict, hit)) - return out - - rows = decide(rules) - deciders = {r[2] for r in rows} - allowed = sum(r[1] == "allow" for r in rows) - ok = 0 in deciders and len(deciders - {0}) >= (n_rules + 1) // 2 and 0.15 * n_conn < allowed < 0.85 * n_conn - # a range's upper end is included: reading it as exclusive must change the answer - excl = [r[:6] + ((r[6] - {max(r[6])}) if "-" in r[5] else r[6], r[7]) for r in rules] - ok = ok and decide(excl) != rows - file_order = rules[:] - if level >= 2: - rng.shuffle(file_order) - ok = ok and decide(file_order) != rows and any(c[2] == "icmp" and r[2] for c, r in zip(conns, rows)) - if level == 3: - loaded = [r[:7] + (True,) for r in rules] - ok = ok and decide(loaded) != rows and any(r[3].startswith("@") and r[0] in deciders for r in rules) - if ok: - break - head = "rule_no,action,proto,src,ports" + (",enabled" if level == 3 else "") - body = "".join(f"{no},{a},{p},{s},{pt}" + ((",yes" if en else ",no") if level == 3 else "") + "\n" - for no, a, p, s, _, pt, _, en in file_order) - files = {"rules.csv": f"{head}\n{body}", - "connections.csv": "id,src_ip,proto,dst_port\n" + "".join(f"{c},{s},{p},{d}\n" for c, s, p, d in conns)} - if level >= 2: - readme = ("# Rule export notes\n\nICMP connections have no port, so their dst_port is empty. An ICMP " - "connection matches a rule only when the rule's proto is icmp or any and its ports is any.\n") - if level == 3: - readme += ("\nRules with enabled=no are kept for reference and are not loaded. A src that starts with `@` " - "names an address group in /root/groups.txt: the source matches when it lies inside any of " - "the group's networks.\n") - files["groups.txt"] = "# address groups, used in rules.csv as @name\n" + "".join( - f"{g}: {' '.join(n)}\n" for g, n in groups.items()) - files["README.md"] = readme - opener = rng.choice([ - "You are reviewing a perimeter firewall change before it goes live.", - "The network team wants to know what a proposed firewall rule table would have done to yesterday's traffic.", - ]) - notes = " Export notes are in /root/README.md." if level >= 2 else "" - instruction = ( - f"{opener} The rule table is /root/rules.csv with the columns rule_no, action (allow or deny), proto, src " - "(a CIDR network or any) and ports (one port, ports joined by `;`, a range such as `8000-8099`, or any). " - f"The connection attempts are in /root/connections.csv with the columns id, src_ip, proto and dst_port.{notes}\n\n" - "A rule matches a connection when its proto equals the connection's or is any, the source IP lies inside " - "its src network or src is any, and dst_port is one of its ports or inside its range (both ends included) " - "or ports is any. Rules are checked in ascending rule_no and the first match decides. A connection that no " - "rule matches is denied by the default rule, numbered 0.\n\n" - "Write /root/verdicts.csv with the header id,verdict,rule and one row per connection in input order, " - "for example `c0007,allow,120`." - ) - want = rows - - def ids_in_order(p): - return [r["id"] for r in p["rows"]] == [r[0] for r in want] - - return Built( - instruction=instruction, - files=files, - artifact=Artifact( - path="verdicts.csv", kind="checks", parse="csv", - checks=[ - ("test_header", lambda p: p["header"] == ["id", "verdict", "rule"]), - ("test_row_count", lambda p: len(p["rows"]) == len(want)), - ("test_ids_in_order", ids_in_order), - ("test_verdicts", lambda p: [r["verdict"] for r in p["rows"]] == [r[1] for r in want]), - ("test_rule_numbers", lambda p: [int(r["rule"]) for r in p["rows"]] == [r[2] for r in want]), - ], - render=lambda: "id,verdict,rule\n" + "".join(f"{c},{v},{n}\n" for c, v, n in want), - ), - root=ROOT, - notes={"allowed": sum(r[1] == "allow" for r in want), "default_deny": sum(r[2] == 0 for r in want)}, - ) - - -# ---------------------------------------------------------------- sec3_exfil_flows - - -def _hm(minute: int) -> str: - return f"{minute // 60:02d}:{minute % 60:02d}" - - -def build_exfil(level: int, rng: random.Random) -> Built: - n_flows = {1: 130, 2: 250, 3: 380}[level] - threshold = rng.choice([200, 250, 300, 400, 500]) - start_h, end_h = rng.choice([(8, 18), (7, 19), (9, 17), (8, 17)]) - bdays = list(DAYS[:5]) if rng.random() < 0.8 else list(DAYS[:6]) - offset = rng.choice([-5, -4, 1, 2]) if level == 3 else 0 - internal = ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"] - while True: - used: set = set() - cloud = [_public_ip(rng, used) for _ in range(rng.randint(14, 22))] - if level == 1: - allowlist = rng.sample(cloud, 5) - allowed_ips = set(allowlist) - else: - nets = rng.sample(["52.94.0.0/16", "13.107.6.0/24", "140.82.112.0/20", "151.101.0.0/16"], 3) - singles = rng.sample(cloud, 3) - allowlist = sorted(nets) + singles - for n in nets: # remote hosts inside the approved networks - net = ipaddress.ip_network(n) - cloud.append(str(net.network_address + rng.randint(1, min(net.num_addresses - 2, 4000)))) - cloud.append(str(net.network_address + rng.randint(1, min(net.num_addresses - 2, 4000)))) - # just outside an approved network: not approved - cloud.append(str(ipaddress.ip_network(nets[0]).broadcast_address + rng.randint(2, 200))) - allowed_ips = set(singles) - - def approved(ip): - return ip in allowed_ips or (level >= 2 and _in_any(ip, allowlist)) - - flows = [] # (local day index, local minute, dst, mb) - for _ in range(n_flows): - day = rng.randrange(7) - minute = rng.randint(start_h * 60, end_h * 60 - 1) if rng.random() < 0.65 else rng.randrange(1440) - dst = rng.choice(cloud) - if level >= 2 and rng.random() < 0.12: - dst = f"10.{rng.randint(0, 9)}.{rng.randint(0, 20)}.{rng.randint(2, 254)}" - r = rng.random() - mb = rng.randint(threshold + 1, threshold * 4) if r < 0.12 else rng.randint(0, int(threshold * 0.8)) - flows.append([day, minute, dst, mb]) - # boundary rows: exactly the threshold off hours (not flagged), starting at closing time (flagged), - # starting at opening time (not flagged) - plain = [c for c in cloud if not approved(c)] - flows += [[rng.randrange(5), start_h * 60 - rng.randint(1, 30), rng.choice(plain), threshold], - [rng.randrange(5), end_h * 60, rng.choice(plain), threshold + rng.randint(1, 40)], - [rng.randrange(5), start_h * 60, rng.choice(plain), threshold + rng.randint(1, 40)]] - - def off_hours(day, minute): - return DAYS[day % 7] not in bdays or not (start_h * 60 <= minute < end_h * 60) - - def flagged(f, clock=None, internal_rule=True, cidr=True): - day, minute, dst, mb = f - if clock is not None: - day, minute = clock // 1440, clock % 1440 - ok_dst = dst in allowed_ips or (level >= 2 and cidr and _in_any(dst, allowlist)) - inside = level >= 2 and internal_rule and _in_any(dst, internal) - return mb > threshold and not ok_dst and not inside and off_hours(day, minute) - - # display time: local for L1-L2, UTC for L3 (local = utc + offset) - shown = [] - for f in flows: - utc = (f[0] * 1440 + f[1] - offset * 60) % (7 * 1440) - shown.append((utc, f)) - shown.sort(key=lambda x: x[0]) - fid, rows, want = rng.randint(100, 199), [], [] - for utc, f in shown: - fid += rng.randint(1, 3) - rows.append(f"{fid},{DAYS[utc // 1440]},{_hm(utc % 1440)},{f[2]},{f[3]}") - if flagged(f): - want.append(fid) - big_off = [f for f in flows if f[3] > threshold and not flagged(f)] - ok = 4 <= len(want) <= 14 and len(big_off) >= 4 - if level >= 2: # ignoring the internal networks or the CIDR entries must change the answer - ok = ok and any(flagged(f, internal_rule=False) != flagged(f) for f in flows) - ok = ok and any(flagged(f, cidr=False) != flagged(f) for f in flows) - if level == 3: # judging on the UTC clock must change the answer - ok = ok and sum(flagged(f, clock=utc) != flagged(f) for utc, f in shown) >= 2 - if ok: - break - policy = {"threshold_mb": threshold, "business_days": bdays, - "business_hours": [f"{start_h:02d}:00", f"{end_h:02d}:00"]} - if level >= 2: - policy["internal_networks"] = internal - if level == 3: - policy["office_utc_offset_hours"] = offset - else: - policy["allowlist"] = allowlist - files = {"flows.csv": "flow,day,time,dst,mb_out\n" + "\n".join(rows) + "\n", - "policy.json": json.dumps(policy, indent=2) + "\n"} - if level == 1: - policy_text = "threshold_mb, business_days, business_hours as [start, end] and allowlist, the approved remote addresses" - elif level == 2: - policy_text = ("threshold_mb, business_days, business_hours as [start, end] and allowlist, the approved remote " - "destinations (addresses or CIDR networks)") - else: - files["allowlist.txt"] = "# approved remote destinations, one address or CIDR network per line\n" + "".join( - f"{a}\n" for a in allowlist) - policy_text = ("threshold_mb, business_days and business_hours as [start, end]; the approved remote destinations " - "are in /root/allowlist.txt, one address or CIDR network per line") - if level >= 2: - readme = ("# Collector notes\n\nThe collector also records traffic between internal machines. A flow whose dst " - "is inside one of policy.json's internal_networks is not outbound and never alerts.\n") - if level == 3: - readme += ("\nThe collector writes day and time in UTC. Business days and hours in policy.json are office " - "local time, which is UTC plus office_utc_offset_hours; convert before checking, which can " - "change the day.\n") - files["README.md"] = readme - opener = rng.choice([ - "You are hunting for data exfiltration in last week's outbound traffic from an office network.", - "Security suspects that someone copied data out of the office network after hours last week.", - ]) - notes = " Collector notes are in /root/README.md." if level >= 2 else "" - instruction = ( - f"{opener} The flow summary is /root/flows.csv with the columns flow (an integer id), day (Mon to Sun), time " - "(HH:MM, when the flow started), dst (the remote IP) and mb_out (whole megabytes sent). The policy file " - f"/root/policy.json gives {policy_text}.{notes}\n\n" - "Flag a flow when all three hold:\n" - "1. mb_out is greater than threshold_mb; equal is not flagged.\n" - "2. dst is not an approved destination.\n" - "3. It started outside business hours: on a day not in business_days, or before start, or at or after end.\n\n" - "Write the flagged flow ids to /root/alerts.json as a JSON array of integers sorted ascending, for example " - "`[104, 187, 203]`." - ) - - def is_int_list(p): - return isinstance(p, list) and all(isinstance(x, int) and not isinstance(x, bool) for x in p) - - want_set = set(want) - return Built( - instruction=instruction, - files=files, - artifact=Artifact( - path="alerts.json", kind="checks", parse="json", - checks=[ - ("test_is_int_list", is_int_list), - ("test_sorted_unique", lambda p: p == sorted(set(p))), - ("test_no_false_positives", lambda p: set(p) <= want_set), - ("test_no_missed_alerts", lambda p: want_set <= set(p)), - ], - render=lambda: json.dumps(want) + "\n", - ), - root=ROOT, - notes={"alerts": want, "threshold_mb": threshold}, - ) - - -FAMILIES = [ - Family("sec3_auth_triage", "cybersecurity", "Block SSH brute-force sources", build_auth, v3=True), - Family("sec3_fw_verdicts", "cybersecurity", "Evaluate an ordered firewall rule table", build_fw, v3=True), - Family("sec3_exfil_flows", "cybersecurity", "Flag off-hours exfiltration flows", build_exfil, v3=True), -] diff --git a/components/dnakhla/upstream/terminal_desk/families/software3.py b/components/dnakhla/upstream/terminal_desk/families/software3.py deleted file mode 100644 index e843a95ea6beac95b6f7f0a7c3ba5047fc1540b7..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/families/software3.py +++ /dev/null @@ -1,665 +0,0 @@ -"""Software engineering v3: repair a module against hidden tests, replay a token-bucket limiter, -resolve a lock file against a package index. All three are stdlib-only.""" - -import datetime -import itertools -import json -import os -import random -import shutil -import tempfile - -from ..core import shell -from .base import Artifact, Built, Family -from .software import FUNCS, _compile, _jsonable, _same - -# ---------------------------------------------------------------- sw3_rate_limit - -RL_OPENERS = ( - "Our gateway's token-bucket limiter rejected the wrong requests during last night's incident.", - "A customer says our gateway's rate limiter dropped requests it should have served.", - "Nobody trusts the rejection log of our gateway's token-bucket limiter after an incident.", -) - - -def _rl_tiers(rng: random.Random) -> dict: - return { - "free": {"capacity": rng.randint(5, 12), "refill_per_sec": round(rng.uniform(0.4, 1.2), 1)}, - "pro": {"capacity": rng.randint(15, 30), "refill_per_sec": round(rng.uniform(1.0, 2.5), 1)}, - "batch": {"capacity": rng.randint(30, 60), "refill_per_sec": round(rng.uniform(0.3, 0.9), 1)}, - } - - -def _rl_replay(reqs, tiers, key_tier, default, exempt, change, *, file_order=False, ignore_exempt=False, - ignore_change=False, charge_rejects=False, whole_seconds=False, unit_cost=False): - """Rejected ids, and the smallest |tokens - cost| over decisions whose token count is inexact (and - |refilled - capacity| over refills), so float evaluation order cannot flip a decision. - Keyword flags replay the common mistakes so the generator can insist each one changes the answer.""" - order = list(reqs) if file_order else sorted(reqs, key=lambda r: (r["ms"], r["id"])) - buckets, rejected, margin = {}, [], float("inf") - for r in order: - key = r["key"] - if key in exempt and not ignore_exempt: - continue - tier = key_tier.get(key, default) - cap, rate = tiers[tier]["capacity"], tiers[tier]["refill_per_sec"] - if change and not ignore_change and tier == change["tier"] and r["ms"] >= change["ms"]: - cap, rate = change["capacity"], change["refill_per_sec"] - ts = r["ms"] / 1000 - if key not in buckets: - tokens, exact = float(cap), True - else: - tokens, last, exact = buckets[key] - gap = ts - last - if whole_seconds: - gap = float(int(gap)) - refilled = tokens + gap * rate - if gap != 0: # a refill that lands within float noise of capacity could clip either way - margin = min(margin, abs(refilled - cap)) - if refilled >= cap: - tokens, exact = float(cap), True - elif gap != 0: - tokens, exact = refilled, False - cost = 1 if unit_cost else r["cost"] - if not exact: - margin = min(margin, abs(tokens - cost)) - if tokens >= cost: - tokens -= cost - else: - rejected.append(r["id"]) - if charge_rejects: - tokens = max(0.0, tokens - cost) - buckets[key] = (tokens, ts, exact) - return sorted(rejected), margin - - -def build_rate_limit(level: int, rng: random.Random) -> Built: - n_req = {1: (400, 550), 2: (600, 800), 3: (700, 900)}[level] - n_keys = {1: (6, 8), 2: (8, 10), 3: (9, 11)}[level] - while True: - keys = sorted({f"k-{rng.randrange(16 ** 4):04x}" for _ in range(rng.randint(*n_keys))}) - hot = rng.sample(keys, 4) - weights = [rng.uniform(4, 7) if k in hot else rng.uniform(0.3, 1.0) for k in keys] - tiers = _rl_tiers(rng) - key_tier = {k: rng.choice(sorted(tiers)) for k in keys} - default, exempt, change = "free", set(), None - if level >= 2: - unmapped = rng.sample([k for k in keys if k not in hot[:1]], 2) - for k in unmapped: - del key_tier[k] - default = rng.choice(sorted(tiers)) - exempt = {hot[0]} | ({rng.choice([k for k in keys if k not in hot])} if rng.random() < 0.5 else set()) - base, ms, reqs = rng.randint(100000, 899999), 0, [] - rate = rng.uniform(4.0, 6.0) - for i in range(rng.randint(*n_req)): - ms += max(1, int(rng.expovariate(rate) * 1000)) - key = rng.choices(keys, weights)[0] - reqs.append({"id": base + i, "ms": ms, "key": key, "cost": rng.choice((1, 1, 1, 2, 3, 5))}) - if level >= 3: - tier = key_tier.get(hot[1], default) - old = tiers[tier] - change = {"tier": tier, "ms": reqs[len(reqs) // 2 + rng.randint(-60, 60)]["ms"], - "capacity": max(5, old["capacity"] + rng.choice((-1, 1)) * rng.randint(3, 8)), - "refill_per_sec": round(max(0.3, old["refill_per_sec"] * rng.uniform(0.4, 0.7)), 1)} - file_reqs = list(reqs) - if level >= 2: # gateway arrival order: some same-key pairs land out of ts order - i = rng.randint(5, 15) - while i < len(file_reqs) - 6: - j = next((j for j in range(i + 1, i + 6) if file_reqs[j]["key"] == file_reqs[i]["key"]), None) - if j is not None: - file_reqs[i], file_reqs[j] = file_reqs[j], file_reqs[i] - i += rng.randint(25, 40) - args = (file_reqs, tiers, key_tier, default, exempt, change) - want, margin = _rl_replay(*args) - if margin < 1e-4 or not 0.05 <= len(want) / len(reqs) <= 0.30: - continue - traps = [dict(charge_rejects=True), dict(whole_seconds=True), dict(unit_cost=True)] - if level >= 2: - traps += [dict(file_order=True), dict(ignore_exempt=True)] - if level >= 3: - traps.append(dict(ignore_change=True)) - if all(_rl_replay(*args, **t)[0] != want for t in traps): - break - exempt_ids = {r["id"] for r in reqs if r["key"] in exempt} - example = sorted(rng.sample([r["id"] for r in reqs if r["id"] not in set(want)], 2)) - csv_lines = ["id,ts,key,cost"] + [f"{r['id']},{r['ms'] / 1000:.3f},{r['key']},{r['cost']}" for r in file_reqs] - limits = {"tiers": tiers, "keys": dict(sorted(key_tier.items()))} - if level >= 2: - limits["default_tier"] = default - limits["exempt_keys"] = sorted(exempt) - files = {"requests.csv": "\n".join(csv_lines) + "\n", "limits.json": json.dumps(limits, indent=2) + "\n"} - inputs = ("- /root/requests.csv: id, ts (seconds, millisecond precision), key and cost (tokens needed) for " - "each request.\n- /root/limits.json: the tiers (capacity, refill_per_sec) and the key-to-tier map.") - rules = ["Each key has its own bucket, full (its tier's capacity) at the key's first request."] - if level == 1: - inputs += "\n" - rules.append("Process requests in ts order.") - else: - inputs += " Unmapped keys use default_tier; exempt_keys are never limited.\n" - rules.append("Process requests in ts order, ties by id (the file is not always in ts order).") - if level >= 3: - inputs += "- /root/CHANGE_NOTICE.md: a tier change made mid-capture.\n" - t = change["ms"] / 1000 - files["CHANGE_NOTICE.md"] = ( - "# Limiter config change\n\n" - f"From ts {t:.3f} onward the {change['tier']} tier is capacity {change['capacity']}, refill_per_sec " - f"{change['refill_per_sec']}. Requests before that time use the old values. Refill for a gap that spans " - "the change uses the new rate, and stored tokens above the new capacity are clipped the next time the " - "key is seen.\n" - ) - rules += [ - "Before each request, refill: tokens = min(capacity, tokens + seconds since the key's previous request " - "x refill_per_sec).", - "If tokens >= cost, accept and subtract cost; otherwise reject without consuming anything.", - ] - instruction = ( - rng.choice(RL_OPENERS) + " Replay the traffic and find which requests should have been rejected.\n\n" - "Inputs:\n" + inputs + "\nRules:\n" + "".join(f"{i}. {r}\n" for i, r in enumerate(rules, 1)) - + "\nWrite /root/rejected.json: the rejected ids as a JSON array of integers, sorted ascending, " - f"e.g. [{example[0]}, {example[1]}]." - ) - want_set = set(want) - checks = [ - ("test_is_list", lambda p: isinstance(p, list)), - ("test_items_are_ints", lambda p: all(type(x) is int for x in p)), - ("test_sorted_unique", lambda p: all(a < b for a, b in zip(p, p[1:]))), - ] - if exempt_ids: - checks.append(("test_no_exempt_ids", lambda p: not exempt_ids & set(p))) - checks += [ - ("test_rejected_count", lambda p: len(p) == len(want)), - ("test_rejected_ids", lambda p: p == want and set(p) == want_set), - ] - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="rejected.json", kind="checks", parse="json", checks=checks, - render=lambda: json.dumps(want) + "\n"), - notes={"rejected": len(want), "requests": len(reqs)}, - root="/root", - ) - - -# ---------------------------------------------------------------- sw3_dep_lock - -PKG_POOL = ( - "acorn", "alder", "amber", "aspen", "basil", "birch", "bramble", "briar", "cedar", "clover", "cobalt", "coral", - "cypress", "dahlia", "ember", "fennel", "fern", "flint", "garnet", "ginger", "hazel", "heather", "hemlock", - "indigo", "iris", "ivy", "jasper", "juniper", "kelp", "larch", "laurel", "lichen", "linden", "maple", "marble", - "moss", "nettle", "obsidian", "onyx", "opal", "pebble", "quartz", "reed", "rowan", "saffron", "sage", "slate", - "sorrel", "spruce", "tansy", "thistle", "willow", "yarrow", "zinnia", -) -DL_OPENERS = ( - "The lock file for our build went stale when the internal package mirror was refreshed.", - "Our release pipeline will not build until the lock file is regenerated against the new package index.", - "A dependency bump broke our build, and the lock file must be regenerated from the package index.", -) - - -def _vkey(v: str) -> tuple: - return tuple(int(p) for p in v.split(".")) - - -def _dl_versions(rng: random.Random, n: int, wide: bool) -> list[str]: - """n ascending major.minor versions with single-digit minors; wide=True forces one jump to a minor of 10+.""" - major, minor, out = rng.randint(0, 3), rng.randint(0, 4), [] - for i in range(n): - out.append(f"{major}.{minor}") - if wide and i == n // 2 - 1: - minor = 10 + rng.randint(0, 3) - if minor <= int(out[-1].split(".")[1]): - minor = int(out[-1].split(".")[1]) + 1 - continue - minor += rng.randint(1, 3) - if rng.random() < 0.25 or minor > 9: # minors of 10+ come only from the wide jump above - major, minor = major + 1, 0 - return out - - -def _dl_spec(rng: random.Random, versions: list[str], ne: bool) -> list[tuple]: - """A constraint as [(op, version)], never empty over `versions`.""" - while True: - i, j = sorted(rng.sample(range(len(versions) + 1), 2)) - spec = ([(">=", versions[i])] if i > 0 else []) + ([("<", versions[j])] if j < len(versions) else []) - if ne and rng.random() < 0.35: - spec = spec[:1] + [("!=", rng.choice(versions))] - if spec and any(_dl_ok(v, spec) for v in versions): - return spec - - -def _dl_ok(v: str, spec, key=_vkey) -> bool: - ops = {">=": lambda a, b: a >= b, "<": lambda a, b: a < b, "!=": lambda a, b: a != b, "==": lambda a, b: a == b} - return all(ops[op](key(v), key(w)) for op, w in spec) - - -def _dl_fmt(spec) -> str: - return ",".join(f"{op}{w}" for op, w in spec) - - -def _dl_solve(pkgs, vers, reqs, top, yanked, key=_vkey, cap=50): - """Valid picks (one version per package; counted up to `cap`) and the preferred one: the newest version of - pkgs[0], then of pkgs[1], ... Depth-first, newest first, so the first complete pick is the preferred one.""" - found = [] - - def fits(pick, p, v): - if (p, v) in yanked or (p in top and not _dl_ok(v, top[p], key)): - return False - mine = reqs[(p, v)] - return all(not (q in mine and not _dl_ok(w, mine[q], key)) - and not (p in reqs[(q, w)] and not _dl_ok(v, reqs[(q, w)][p], key)) for q, w in pick.items()) - - def walk(i, pick): - if len(found) >= cap: - return - if i == len(pkgs): - found.append(dict(pick)) - return - p = pkgs[i] - for v in sorted(vers[p], key=key, reverse=True): - if fits(pick, p, v): - pick[p] = v - walk(i + 1, pick) - del pick[p] - - walk(0, {}) - return found, (found[0] if found else None) - - -def _strkey(v: str) -> tuple: - return tuple(v.split(".")) # the common mistake: comparing version parts as strings - - -def build_dep_lock(level: int, rng: random.Random) -> Built: - n_pkg, n_ver, n_noise = {1: (4, (3, 4), 36), 2: (5, (4, 5), 38), 3: (6, (3, 4), 40)}[level] - dep_p = {1: 0.4, 2: 0.35, 3: 0.3}[level] - names = rng.sample(PKG_POOL, n_pkg + n_noise) - pkgs, noise = names[:n_pkg], names[n_pkg:] - while True: # only the requested packages decide the answer; the mirror's other packages come after - wide = set(rng.sample(pkgs, 2)) if level >= 2 else set() - vers = {p: _dl_versions(rng, rng.randint(*n_ver), p in wide) for p in pkgs} - reqs = {} - for p in pkgs: - for v in vers[p]: - reqs[(p, v)] = {q: _dl_spec(rng, vers[q], level >= 2) for q in pkgs if q != p and rng.random() < dep_p} - top = {p: _dl_spec(rng, vers[p], False) for p in pkgs if rng.random() < 0.5} - valid, best = _dl_solve(pkgs, vers, reqs, top, set()) - yanked = set() - if level >= 3 and best: - target = rng.choice(pkgs) - yanked = {(target, best[target])} - yanked |= {(p, rng.choice(vers[p])) for p in rng.sample(pkgs, 2)} - valid, best = _dl_solve(pkgs, vers, reqs, top, yanked) - if not best or len(valid) < 3: - continue - newest = {p: max(vers[p], key=_vkey) for p in pkgs} - if best == newest: - continue - if level >= 2 and _dl_solve(pkgs, vers, reqs, top, yanked, key=_strkey)[1] == best: - continue - if level >= 3 and _dl_solve(pkgs, vers, reqs, top, set())[1] == best: - continue - break - for p in noise: - vers[p] = _dl_versions(rng, rng.randint(*n_ver), False) - for p in noise: - pool = [q for q in names if q != p] - for v in vers[p]: - deps = rng.sample(pool, rng.choice((0, 0, 1, 1, 2))) - reqs[(p, v)] = {q: _dl_spec(rng, vers[q], level >= 2) for q in deps} - if level >= 3: - yanked |= {(p, rng.choice(vers[p])) for p in rng.sample(noise, 2)} - index = ["# package version requires (';'-separated, '-' for none)"] - for p in sorted(names): - for v in vers[p]: - r = reqs[(p, v)] - index.append(f"{p} {v} " + (";".join(f"{q}{_dl_fmt(s)}" for q, s in sorted(r.items())) or "-")) - manifest = [f"{p}{_dl_fmt(top[p])}" if p in top else p for p in pkgs] - files = {"index.txt": "\n".join(index) + "\n", "requirements.txt": "\n".join(manifest) + "\n"} - ops = "'>=X' means at least X, '= 2: - ops += ", '!=X' anything but X" - ops += ", and a comma joins conditions" - extra = "" - if level >= 2: - extra = " Versions compare by major, then minor, as numbers (1.10 is newer than 1.9)." - if level >= 3: - files["yanked.txt"] = ("# yanked releases: never install these\n" - + "".join(f"{p} {v}\n" for p, v in sorted(yanked))) - extra += " Never pick a release listed in /root/yanked.txt." - instruction = ( - rng.choice(DL_OPENERS) + "\n\n" - "/root/requirements.txt names the packages to install, in priority order, some with a version condition. " - "/root/index.txt lists every release in the mirror, one per line: package, version, and what it requires. " - "Most mirror packages are unused; releases of the packages you install only require each other.\n\n" - "Pick one version of each package in requirements.txt so that its conditions and the requirements of " - f"every picked release hold ({ops}).{extra} Among all valid picks, take the newest version of the first " - "package in requirements.txt, then of the second, and so on.\n\n" - "Write /root/lock.txt with one name==version line per package, sorted by name, for example " - f"{rng.choice(noise)}==2.4, and nothing else." - ) - want = [f"{p}=={best[p]}" for p in sorted(pkgs)] - - def lock(lines): - return dict(ln.split("==", 1) for ln in lines) - - def satisfies(lines): - pick = lock(lines) - return (all(_dl_ok(pick[p], s) for p, s in top.items()) - and all(_dl_ok(pick[q], s) for p in pkgs for q, s in reqs[(p, pick[p])].items()) - and not any((p, v) in yanked for p, v in pick.items())) - - checks = [ - ("test_line_format", lambda p: all(ln.count("==") == 1 and " " not in ln for ln in p)), - ("test_one_line_per_package", lambda p: len(p) == len(pkgs) and set(lock(p)) == set(pkgs)), - ("test_sorted_by_name", lambda p: [ln.split("==")[0] for ln in p] == sorted(pkgs)), - ("test_versions_in_index", lambda p: all(v in vers[n] for n, v in lock(p).items())), - ("test_constraints_hold", satisfies), - ("test_preferred_lock", lambda p: p == want), - ] - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="lock.txt", kind="checks", parse="lines", checks=checks, - render=lambda: "\n".join(want) + "\n"), - notes={"valid": len(valid), "best": best}, - root="/root", - ) - - -# ---------------------------------------------------------------- sw3_fix_module - -MODULES = { # module name -> (test class, what the job does) - "report_utils": ("ReportUtilsTest", "nightly reporting job"), - "metrics_helpers": ("MetricsHelpersTest", "metrics rollup job"), - "toolkit": ("ToolkitTest", "nightly export job"), - "text_tools": ("TextToolsTest", "search indexing job"), -} - -# CHANGELOG revisions: the newer behaviour wins over the (stale) docstring. -REVISIONS = { - "median": { - "entry": "`median` now returns `None` for an empty list instead of raising.", - "edit": (" s = sorted(values)\n", " if not values:\n return None\n s = sorted(values)\n"), - "extra": lambda r: ([],), - }, - "percent_change": { - "entry": "`percent_change` now rounds to 1 decimal place instead of 2.", - "edit": ("old * 100, 2)", "old * 100, 1)"), - "extra": lambda r: (r.randint(3, 97), r.randint(3, 997)), - }, - "clamp": { - "entry": "`clamp` accepts its bounds in either order: when `lo > hi` the two are swapped first.", - "edit": (" if x < lo:\n", " if lo > hi:\n lo, hi = hi, lo\n if x < lo:\n"), - "extra": lambda r: (r.randint(-20, 20), r.randint(1, 10), r.randint(-10, 0)), - }, - "dedupe": { - "entry": "`dedupe` compares strings case-insensitively and keeps the first spelling it sees.", - "edit": (" if item not in seen:\n seen.add(item)\n", - " k = item.lower() if isinstance(item, str) else item\n if k not in seen:\n" - " seen.add(k)\n"), - "extra": lambda r: ([r.choice(["ok", "OK", "Ok", "red", "Red", "RED", "x"]) for _ in range(r.randint(3, 9))],), - }, - "word_count": { - "entry": "`word_count` counts digits as word characters: a word is now a run of a-z or 0-9.", - "edit": ('r"[a-z]+"', 'r"[a-z0-9]+"'), - "extra": lambda r: (" ".join(r.choice(["Room", "101", "room", "B12", "7", "go", "v2.1"]) for _ in range(r.randint(2, 7))),), - }, - "moving_average": { - "entry": "`moving_average` rounds every result to 4 decimal places.", - "edit": ("[sum(values[i:i + k]) / k ", "[round(sum(values[i:i + k]) / k, 4) "), - "extra": lambda r: ([r.randint(0, 50) for _ in range(r.randint(4, 9))], 3), - }, -} - -NOISE_ENTRIES = ( - ("Performance", "`word_count` is faster on long inputs."), - ("Performance", "`chunk` no longer copies the input list first."), - ("Docs", "Added usage examples to the README."), - ("Fixed", "Packaging: the wheel now ships `py.typed`."), - ("Internal", "CI runs on Python 3.12."), - ("Internal", "Moved the helpers out of the monolith into their own module."), - ("Docs", "Fixed a typo in the module docstring."), - ("Internal", "Type hints checked with mypy in CI."), - ("Performance", "`median` sorts a copy only once."), - ("Fixed", "The release script tags versions correctly."), -) - -FIX_HARNESS = r''' -import importlib, json, sys -sys.path.insert(0, sys.argv[1]) -cases = json.loads(sys.stdin.read()) -out = {} -try: - mod = importlib.import_module(sys.argv[2]) -except BaseException as exc: - print("@@RESULT@@" + json.dumps({"__import_error__": type(exc).__name__})) - raise SystemExit(0) -for name, arglists in cases.items(): - res = [] - for args in arglists: - try: - res.append(getattr(mod, name)(*args)) - except BaseException as exc: - res.append({"__error__": type(exc).__name__}) - out[name] = res -print("@@RESULT@@" + json.dumps(out, default=repr)) -''' - - -def _call(fn, args): - try: - return _jsonable(fn(*args)) - except Exception as exc: # the harness records raises the same way - return {"__error__": type(exc).__name__} - - -def _diff(f, g, args) -> bool: - return not _same(_call(f, args), _call(g, args)) - - -def _raises(fn, args) -> bool: - got = _call(fn, args) - return isinstance(got, dict) and "__error__" in got - - -def _run_hidden(module: str, source: str, cases: dict) -> dict | None: - """Import the agent's module as nobody on a private copy and call every hidden case.""" - tmp = tempfile.mkdtemp(prefix="tdchk-") - try: - os.chmod(tmp, 0o755) - src_dir = os.path.join(tmp, "src") - os.mkdir(src_dir) - with open(os.path.join(src_dir, f"{module}.py"), "w") as fh: - fh.write(source) - with open(os.path.join(tmp, "harness.py"), "w") as fh: - fh.write(FIX_HARNESS) - shell.give_to_nobody(tmp) - _, text = shell.run(["python3", "-I", os.path.join(tmp, "harness.py"), src_dir, module], tmp, - stdin_text=json.dumps(cases)) - lines = [ln for ln in text.splitlines() if ln.startswith("@@RESULT@@")] - return json.loads(lines[-1][len("@@RESULT@@"):]) if lines else None - finally: - shell.kill_nobody() - shutil.rmtree(tmp, ignore_errors=True) - - -def _ci_log(rng: random.Random, module: str, job: str, test_cls: str, failing: tuple) -> str: - """A noisy nightly CI log, a few hundred short lines, with the one failing visible test near the end.""" - t = rng.randint(0, 600) - - def stamp(): - nonlocal t - t += rng.randint(0, 4) - return f"02:{t // 60 % 60:02d}:{t % 60:02d}" - - out = [f"{stamp()} [ci] nightly run of the {job}, 2026-10-13"] - for step in ("checkout", "setup-python 3.12", f"restore cache (hit, {rng.randint(20, 90)} MB)"): - out.append(f"{stamp()} [step] {step}") - out.append(f"{stamp()} [step] install requirements") - for _ in range(rng.randint(24, 40)): - pkg = rng.choice(PKG_POOL) - out.append(f"{stamp()} fetched {pkg}-{rng.randint(0, 4)}.{rng.randint(0, 19)} ({rng.randint(8, 900)} kB)") - out.append(f"{stamp()} [step] run job dry-run") - for _ in range(rng.randint(70, 110)): - out.append(f"{stamp()} {rng.choice(('INFO', 'INFO', 'INFO', 'DEBUG', 'WARN'))} " - f"{rng.choice(('ingest', 'transform', 'rollup', 'export'))}: batch {rng.randint(1, 400)} " - f"rows={rng.randint(10, 9999)} took={rng.randint(3, 2000)}ms") - out.append(f"{stamp()} [step] unit tests: python3 -m unittest discover -s tests -v") - name, idx, args, got, want = failing - out.append(f"{stamp()} FAILED (failures=1)") - out += [ - "=" * 70, - f"FAIL: test_{name}_{idx} (test_{module}.{test_cls}.test_{name}_{idx})", - "-" * 70, - "Traceback (most recent call last):", - f' File "/app/tests/test_{module}.py", line {9 + 3 * idx}, in test_{name}_{idx}', - f" self.assertEqual({module}.{name}(*{list(args)!r}), {want!r})", - f"AssertionError: {got!r} != {want!r}", - f"{stamp()} [ci] job failed: exit code 1", - ] - return "\n".join(out) + "\n" - - -def _changelog(rng: random.Random, revised: str | None, n: int, position: int) -> str: - entries = rng.sample(NOISE_ENTRIES, n - (revised is not None)) - if revised is not None: - entries.insert(position, ("Changed", REVISIONS[revised]["entry"])) - minor, day = rng.randint(2, 4), datetime.date(2026, 5, 1) + datetime.timedelta(days=rng.randint(0, 60)) - blocks = [] - for patch, (kind, text) in enumerate(reversed(entries), 1): # oldest release first - day += datetime.timedelta(days=rng.randint(3, 14)) - blocks.append(f"## [{minor}.{patch}.0] - {day.isoformat()}\n\n### {kind}\n- {text}\n") - blocks.reverse() # printed newest first - return "# Changelog\n\nAll notable changes to this module. Newest first.\n\n" + "\n".join(blocks) - - -def build_fix_module(level: int, rng: random.Random) -> Built: - n_funcs, n_bugs = {1: (3, 1), 2: (4, 2), 3: (5, 2)}[level] - module = rng.choice(sorted(MODULES)) - test_cls, job = MODULES[module] - while True: - names = rng.sample(sorted(FUNCS), n_funcs) - buggy = rng.sample(names, n_bugs) - revised = None - if level == 2: # the CHANGELOG revises a function that is not buggy - pool = [n for n in names if n in REVISIONS and n not in buggy] - elif level == 3: # it revises a buggy one, so restoring the docstring is wrong - pool = [n for n in buggy if n in REVISIONS] - else: - pool = [None] - if pool: - revised = rng.choice(pool) - break - shown = next(n for n in buggy if n != revised) # the bug with a failing visible test (never the revised one) - sources, good_sources, hidden, tests, failing = [], [], {}, [], None - for name in names: - spec = FUNCS[name] - good_src = spec["src"] - if name == revised: - old, new = REVISIONS[name]["edit"] - assert old in good_src, (name, old) - good_src = good_src.replace(old, new, 1) - good = _compile(good_src) - src, bad = spec["src"], None - if name in buggy: - old, new = rng.choice(spec["bugs"]) - assert old in src, (name, old) - src = src.replace(old, new, 1) - bad = _compile(src) - cases = [spec["gen"](rng) for _ in range(40)] - if name == revised: - original = _compile(spec["src"]) - extra = [REVISIONS[name]["extra"](rng) for _ in range(6)] - assert sum(_diff(original, good, c) for c in cases + extra) >= 3, name - cases += extra - if bad is not None: - diffs = [c for c in cases if _diff(good, bad, c)] - while len(diffs) < 3: - c = spec["gen"](rng) - if _diff(good, bad, c): - diffs.append(c) - cases.append(c) - sources.append(src) - good_sources.append(good_src) - hidden[name] = (_jsonable([list(c) for c in cases]), [_call(good, c) for c in cases]) - if name == shown: - c = next(c for c in cases if _diff(good, bad, c) and not _raises(bad, c) and not _raises(good, c)) - failing = (name, len(tests), c, bad(*c), good(*c)) - tests.append((name, c, good(*c))) - elif name not in buggy and name != revised: - for c in cases[:2]: - tests.append((name, c, good(*c))) - header = f'"""{module}: small helpers used by the {job}."""\n\nimport re\n\n\n' - module_src = header + "\n\n".join(sources) - fixed_src = header + "\n\n".join(good_sources) - test_lines = [ - "import os, sys, unittest", - "sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'src'))", - f"import {module}", - "", - "", - f"class {test_cls}(unittest.TestCase):", - ] - for i, (name, args, want) in enumerate(tests): - test_lines += [f" def test_{name}_{i}(self):", - f" self.assertEqual({module}.{name}(*{list(args)!r}), {want!r})", ""] - test_lines += ["", 'if __name__ == "__main__":', " unittest.main()", ""] - files = { - f"src/{module}.py": module_src, - f"tests/test_{module}.py": "\n".join(test_lines), - "ci/nightly.log": _ci_log(rng, module, job, test_cls, failing), - } - path = f"src/{module}.py" - broken = "one of them no longer does what its docstring says" if n_bugs == 1 else \ - f"{n_bugs} of them no longer do what their docstrings say" - listing = [ - f"- src/{module}.py: the module; each function's docstring is its specification.", - f"- tests/test_{module}.py: visible unit tests. They are incomplete: a function can be wrong and still " - "pass them. Run them from /app with python3 -m unittest discover -s tests.", - "- ci/nightly.log: the log of last night's failed run.", - ] - if level >= 2: - n_entries = rng.randint(6, 8) - files["CHANGELOG.md"] = _changelog(rng, revised, n_entries, rng.randint(1, n_entries - 2) if level == 3 else - rng.randint(0, 2)) - listing.append("- CHANGELOG.md: release notes. Where an entry and a docstring disagree, the entry is newer " - "and wins; leave the docstring as it is.") - instruction = ( - f"Our {job} started failing in CI after a refactor of /app/{path}. The module has {n_funcs} functions and " - f"{broken}. Repair the module in place.\n\nFiles in /app:\n" + "\n".join(listing) + "\n\n" - "Keep every function name and signature, use only the standard library, and do not edit the tests. The " - f"grader imports /app/{path} and runs its own hidden tests against every function, including the ones the " - "visible tests do not cover; the task passes only if all of them pass." - ) - cases = {n: args for n, (args, _) in hidden.items()} - cache: dict = {} - - def results(text: str): - if cache.get("text") != text: - cache.update(text=text, got=_run_hidden(module, text, cases)) - return cache["got"] - - def imports(text): - got = results(text) - return isinstance(got, dict) and "__import_error__" not in got - - def passes(name): - return lambda text: imports(text) and _same(results(text)[name], hidden[name][1]) - - checks = [("test_module_imports", imports)] + [(f"test_{n}", passes(n)) for n in names] - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path=path, kind="checks", parse="text", checks=checks, render=lambda: fixed_src), - notes={"buggy": sorted(buggy), "revised": revised, "module": module}, - root="/app", - ) - - -FAMILIES = [ - Family("sw3_fix_module", "software engineering", "Repair a helper module against hidden tests", - build_fix_module, v3=True), - Family("sw3_rate_limit", "software engineering", "Replay token-bucket rate limiting", build_rate_limit, v3=True), - Family("sw3_dep_lock", "software engineering", "Resolve a lock file against a package index", build_dep_lock, - v3=True), -] diff --git a/components/dnakhla/upstream/terminal_desk/oracles/__init__.py b/components/dnakhla/upstream/terminal_desk/oracles/__init__.py deleted file mode 100644 index 623ca4acae1958a1dc93780585e4ad944b9d5c46..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/__init__.py +++ /dev/null @@ -1,40 +0,0 @@ -"""Oracle scripts for v3 families: terminal_desk/oracles/.py. - -An oracle is the standalone script a good agent writes in one write_file: it -reads the inputs and writes the output file using only the image's packages. -It is not the grader; it proves the files carry everything the answer needs. - -Oracles open paths relative to the working directory (the environment runs -commands with cwd = the family root), so the same script works under the real -/root and /app and under TERMINAL_DESK_ROOTS in tests. -""" - -import os - -from ..models import Tbench2Action - -ORACLE_DIR = os.path.dirname(os.path.abspath(__file__)) -ORACLE_FILE = "oracle.py" # where the runner writes the script, relative to the root -EXIT_MARK = "@@oracle-exit=" - - -def oracle_path(family_id: str, directory: str = ORACLE_DIR) -> str: - return os.path.join(directory, f"{family_id}.py") - - -def oracle_source(family_id: str, directory: str = ORACLE_DIR) -> str | None: - path = oracle_path(family_id, directory) - if not os.path.isfile(path): - return None - with open(path, encoding="utf-8") as fh: - return fh.read() - - -def run_oracle(env, source: str): - """Play the oracle the way an agent would on a reset env: write_file it, exec python3, evaluate. - Returns (exec output, evaluate observation). Commands run as nobody when the server is root.""" - wrote = env.step(Tbench2Action(action_type="write_file", file_path=ORACLE_FILE, content=source)) - if not wrote.success: - raise RuntimeError(f"could not write the oracle: {wrote.error}") - ran = env.step(Tbench2Action(action_type="exec", command=f'python3 {ORACLE_FILE}; echo "{EXIT_MARK}$?"')) - return ran.output, env.step(Tbench2Action(action_type="evaluate")) diff --git a/components/dnakhla/upstream/terminal_desk/oracles/fin3_invoice_fraud.py b/components/dnakhla/upstream/terminal_desk/oracles/fin3_invoice_fraud.py deleted file mode 100644 index a3058b71e0a669b330211a238274669bec33d261..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/fin3_invoice_fraud.py +++ /dev/null @@ -1,34 +0,0 @@ -"""Oracle for fin3_invoice_fraud: the first matching rule per invoice row, in file order.""" -import csv -import json -import os - - -def rows(name): - with open(f"data/{name}", newline="") as fh: - return list(csv.DictReader(fh)) - - -pos = {r["po_number"]: float(r["amount"]) for r in rows("purchase_orders.csv")} -vendors = {r["vendor_id"]: r["status"] for r in rows("vendors.csv")} if os.path.exists("data/vendors.csv") else None - -report, seen = [], set() -for n, inv in enumerate(rows("invoices.csv"), 1): - vid, po, amount = inv["vendor_id"], inv["po_number"], float(inv["amount"]) - key = (vid, inv["invoice_no"]) - if vendors is not None and vendors.get(vid) != "ACTIVE": - reason = "Unknown Vendor" - elif po not in pos: - reason = "Missing PO" - elif abs(amount - pos[po]) > 0.02 * pos[po]: - reason = "Amount Mismatch" - elif key in seen: - reason = "Duplicate Invoice" - else: - reason = None - seen.add(key) - if reason: - report.append({"row": n, "invoice_no": inv["invoice_no"], "amount": amount, "reason": reason}) - -with open("fraud_report.json", "w") as fh: - json.dump(report, fh, indent=1) diff --git a/components/dnakhla/upstream/terminal_desk/oracles/fin3_loan_schedule.py b/components/dnakhla/upstream/terminal_desk/oracles/fin3_loan_schedule.py deleted file mode 100644 index 9f3dcebd596e46007f4f974978878d3c7db8b460..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/fin3_loan_schedule.py +++ /dev/null @@ -1,55 +0,0 @@ -"""Oracle for fin3_loan_schedule.""" -import csv -import os -from decimal import ROUND_HALF_UP, Decimal - - -def r2(x): - return x.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) - - -def annuity(bal, pct, n): - i = pct / 1200 - return r2(bal * i / (1 - (1 + i) ** -n)) - - -def rows(name): - if not os.path.exists(f"data/{name}"): - return [] - with open(f"data/{name}", newline="") as fh: - return [r for r in csv.DictReader(fh) if r.get("loan_id") == lid] - - -lid = open("data/ticket.txt").read().split("Loan:")[1].split()[0] -loan = rows("loans.csv")[0] -bal, cur, term = Decimal(loan["principal"]), Decimal(loan["annual_rate_pct"]), int(loan["term_months"]) -extras = {} -for r in rows("extra_payments.csv"): - if r.get("status") != "REVERSED": - m = int(r["payment_no"]) - extras[m] = extras.get(m, 0) + Decimal(r["amount"]) -resets = {int(r["from_payment"]): Decimal(r["new_rate_pct"]) for r in rows("rate_resets.csv")} - -out, month, pay = [], 0, annuity(bal, cur, term) -while bal > 0: - month += 1 - if month in resets: - cur = resets[month] - pay = annuity(bal, cur, term - month + 1) - i = r2(bal * cur / 1200) - if bal + i <= pay or month == term: - out.append([month, bal + i, i, bal, 0, 0]) - break - bal -= pay - i - extra = min(extras.get(month, 0), bal) - bal -= extra - out.append([month, pay, i, pay - i, extra, bal]) - -head = ["month", "payment", "interest", "principal", "extra", "balance"] -if not os.path.exists("data/extra_payments.csv"): - head.remove("extra") - out = [r[:4] + r[5:] for r in out] -with open("schedule.csv", "w", newline="") as fh: - w = csv.writer(fh) - w.writerow(head) - w.writerows([r[0]] + [f"{Decimal(x):.2f}" for x in r[1:]] for r in out) diff --git a/components/dnakhla/upstream/terminal_desk/oracles/fin3_portfolio_value.py b/components/dnakhla/upstream/terminal_desk/oracles/fin3_portfolio_value.py deleted file mode 100644 index 67d5a7625b8ec84f1461a673b7839a0f7742d999..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/fin3_portfolio_value.py +++ /dev/null @@ -1,42 +0,0 @@ -"""Oracle for fin3_portfolio_value: replay trades and corporate actions, value at the last close.""" -import csv -import os -import re -from decimal import Decimal - -with open("data/prices.csv", newline="") as fh: - prices = list(csv.DictReader(fh)) -last = max(r["date"] for r in prices) -close = {r["ticker"]: Decimal(r["close"]) for r in prices if r["date"] == last} - -events = [] # (date, 0 = corporate action before 1 = that day's trades, kind, data) -if os.path.exists("data/corporate_actions.txt"): - for line in open("data/corporate_actions.txt"): - m = re.match(r"(\S+) (\S+) (\d+)-for-1", line) - if m: - events.append((m[1], 0, "split", (m[2], int(m[3])))) - m = re.match(r"(\S+) (\S+) cash dividend of ([\d.]+)", line) - if m: - events.append((m[1], 0, "div", (m[2], Decimal(m[3])))) -with open("data/trades.csv", newline="") as fh: - events += [(r["date"], 1, "trade", r) for r in csv.DictReader(fh)] - -cash, hold = Decimal(100000), {} -for date, _, kind, data in sorted(events, key=lambda e: (e[0], e[1])): - if kind == "split": - hold[data[0]] = hold.get(data[0], 0) * data[1] - elif kind == "div": - cash += data[1] * hold.get(data[0], 0) - else: - sign = 1 if data["side"] == "BUY" else -1 - qty = sign * int(data["shares"]) - hold[data["ticker"]] = hold.get(data["ticker"], 0) + qty - cash -= qty * Decimal(data["price"]) - -with open("positions.csv", "w", newline="") as fh: - w = csv.writer(fh) - w.writerow(["ticker", "shares", "close", "market_value"]) - for t, q in sorted(hold.items()): - if q: - w.writerow([t, q, f"{close[t]:.2f}", f"{q * close[t]:.2f}"]) - w.writerow(["CASH", 0, 0, f"{cash:.2f}"]) diff --git a/components/dnakhla/upstream/terminal_desk/oracles/ind3_service_due.py b/components/dnakhla/upstream/terminal_desk/oracles/ind3_service_due.py deleted file mode 100644 index c11722d8b60df1aa983fbc160fc1c1d036b60322..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/ind3_service_due.py +++ /dev/null @@ -1,47 +0,0 @@ -"""Oracle for ind3_service_due: run-hours and days since service against each type's limits.""" -import csv -import os -import re -from datetime import date - -ASOF = date(2026, 10, 31) - - -def rows(path): - with open(path, newline="") as fh: - return list(csv.DictReader(fh)) - - -def text(path): - return open(path).read() if os.path.exists(path) else "" - - -limits = {r["type"]: (float(r["max_run_hours"]), int(r["max_days"])) for r in rows("data/service_intervals.csv")} -machines = {r["machine"]: r for r in rows("data/machines.csv")} -service = {m: (date.fromisoformat(r["last_service_date"]), float(r["meter_at_service"])) for m, r in machines.items()} -for day, m, meter in re.findall(r"(\S+): (M\d+) was serviced again; its hour meter read ([\d.]+)", text("data/notes.md")): - service[m] = (date.fromisoformat(day), float(meter)) -swaps = {m: date.fromisoformat(d) for d, m in re.findall(r"(\S+): (M\d+) hour meter failed", text("data/shift_log.txt"))} - -readings = {} -for r in rows("data/meter_readings.csv"): - day = date.fromisoformat(r["date"]) - if day <= ASOF: - readings.setdefault(r["machine"], []).append((day, float(r["meter_hours"]))) - -out = [] -for m in sorted(machines): - served, at = service[m] - seq = sorted(readings[m]) - hours = seq[-1][1] - at - if m in swaps: # the new meter counts from zero; add the old meter's hours up to the swap - hours += max(x for x in seq if x[0] < swaps[m])[1] - days = (ASOF - served).days - max_hours, max_days = limits[machines[m]["type"]] - out.append([m, f"{hours:.1f}", days, "yes" if hours >= max_hours or days >= max_days else "no"]) - -with open("service_report.csv", "w", newline="") as fh: - w = csv.writer(fh) - w.writerow(["machine", "run_hours_since_service", "days_since_service", "due"]) - w.writerows(out) -print(out) diff --git a/components/dnakhla/upstream/terminal_desk/oracles/ind3_stl_mass.py b/components/dnakhla/upstream/terminal_desk/oracles/ind3_stl_mass.py deleted file mode 100644 index dea097e83de090357c41055ee9f510b001116e90..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/ind3_stl_mass.py +++ /dev/null @@ -1,42 +0,0 @@ -"""Oracle for ind3_stl_mass: signed-tetrahedron volume and area per solid, keep the largest, mass.""" -import csv -import json -import os - -with open("data/materials.csv", newline="") as fh: - density = {r["code"]: float(r["density_g_cm3"]) for r in csv.DictReader(fh)} -notes = open("data/scan_notes.md").read() if os.path.exists("data/scan_notes.md") else "" - -solids = [] -for line in open("data/scan.stl"): - w = line.split() - if w and w[0] == "solid": - solid = {"name": w[1], "code": w[2], "tris": [], "v": []} - solids.append(solid) - elif w and w[0] == "vertex": - solid["v"].append([float(x) for x in w[1:4]]) - if len(solid["v"]) == 3: - solid["tris"].append(solid["v"]) - solid["v"] = [] - - -def cross(a, b): - return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] - - -for s in solids: - vol = area = 0.0 - for a, b, c in s["tris"]: - vol += sum(x * y for x, y in zip(a, cross(b, c))) / 6 - n = cross([q - p for p, q in zip(a, b)], [q - p for p, q in zip(a, c)]) - area += sum(x * x for x in n) ** 0.5 / 2 - s["vol"], s["area"] = abs(vol), area - -part = max(solids, key=lambda s: s["vol"]) -k = 2.54 if "exported in inches" in notes else 0.1 # file units to cm -volume, area = part["vol"] * k**3, part["area"] * k**2 -report = {"solid": part["name"], "material": part["code"], "volume_cm3": volume, "area_cm2": area, - "mass_g": volume * density[part["code"]]} -with open("mass_report.json", "w") as fh: - json.dump(report, fh) -print(report) diff --git a/components/dnakhla/upstream/terminal_desk/oracles/ind3_tank_balance.py b/components/dnakhla/upstream/terminal_desk/oracles/ind3_tank_balance.py deleted file mode 100644 index 58ac5e66ffa7d24a3bf8a52826da4cf0a0c1309b..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/ind3_tank_balance.py +++ /dev/null @@ -1,50 +0,0 @@ -"""Oracle for ind3_tank_balance: trapezoid inflow/outflow, net, and the longest high-level run.""" -import csv -import json -import os -import re - - -def text(path): - return open(path).read() if os.path.exists(path) else "" - - -def sec(t): - h, m, s = map(int, t.split(":")) - return h * 3600 + m * 60 + s - - -readme, note = text("data/README.md"), text("data/maintenance_note.txt") -cal = re.search(r"at (\d\d:\d\d:\d\d)\. Inflow readings taken before that time read (\d+)% high", note) -with open("data/tank_log.csv", newline="") as fh: - rows = [r for r in csv.DictReader(fh) if r.get("status", "OK") != "FAULT"] - - -def inflow(r): - f = float(r["inflow_lpm"]) - if cal and sec(r["time"]) < sec(cal.group(1)): - f /= 1 + int(cal.group(2)) / 100 - return f - - -tin = tout = 0.0 -for a, b in zip(rows, rows[1:]): - minutes = (sec(b["time"]) - sec(a["time"])) / 60 - tin += (inflow(a) + inflow(b)) / 2 * minutes - tout += (float(a["outflow_lpm"]) + float(b["outflow_lpm"])) / 2 * minutes -report = {"inflow_liters": round(tin, 2), "outflow_liters": round(tout, 2), "net_liters": round(tin - tout, 2)} - -alarm = re.search(r"alarm setpoint is (\d+) cm", readme) -if alarm: - best, start = 0, None - for r in rows: - if float(r["level_cm"]) > int(alarm.group(1)): - start = sec(r["time"]) if start is None else start - best = max(best, sec(r["time"]) - start) - else: - start = None - report["longest_high_minutes"] = round(best / 60, 2) - -with open("tank_report.json", "w") as fh: - json.dump(report, fh) -print(report) diff --git a/components/dnakhla/upstream/terminal_desk/oracles/math3_count_items.py b/components/dnakhla/upstream/terminal_desk/oracles/math3_count_items.py deleted file mode 100644 index 030decb27d428867698dae2cf920128ab261fd5e..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/math3_count_items.py +++ /dev/null @@ -1,32 +0,0 @@ -"""Oracle for math3_count_items: filter the raffle tickets by the draw rules, then rank and count pairs.""" -import csv -import json -import os - -cfg = json.load(open("data/draw.json")) -void = set() -if os.path.exists("data/voided.csv"): - void = {r["ticket"] for r in csv.DictReader(open("data/voided.csv"))} - - -def wins(x): - if not any(x % d == 0 for d in cfg["divisors"]) or x % cfg["excluded_divisor"] == 0: - return False - ds = cfg.get("digit_sum_divisor") - return ds is None or sum(map(int, str(x))) % ds == 0 - - -nums = set() -for r in csv.DictReader(open("data/tickets.csv")): - x = int(r["number"]) - if r["ticket"] not in void and wins(x): - nums.add(x) -nums = sorted(nums) - -out = {"count": len(nums), "kth_smallest": nums[cfg["rank"] - 1], "largest": nums[-1]} -if "pair_modulus" in cfg: - m = cfg["pair_modulus"] - out["pairs"] = sum((p + q) % m == 0 for i, p in enumerate(nums) for q in nums[i + 1:]) -with open("results.json", "w") as f: - json.dump(out, f) -print(out) diff --git a/components/dnakhla/upstream/terminal_desk/oracles/math3_exam_slots.py b/components/dnakhla/upstream/terminal_desk/oracles/math3_exam_slots.py deleted file mode 100644 index e61e0a9aebd9f87465d61cf600f91e711cb82524..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/math3_exam_slots.py +++ /dev/null @@ -1,50 +0,0 @@ -"""Oracle for math3_exam_slots: brute-force every block order that respects front-loading.""" -import csv -import itertools -import json -import os - -inst = json.load(open("data/instance.json")) -blocks, slots = inst["blocks"], inst["slots"] -evening = "evening-to-morning" in open("data/README.md").read().lower() -cutoff = inst.get("large_block_cutoff") -large = {b for b in blocks if cutoff is not None and inst["block_size"][b] >= cutoff} -early = set(inst.get("early_slots", [])) - -pair, trip = {}, {} -for r in csv.DictReader(open("data/pair_counts.csv")): - pair[frozenset((r["block_a"], r["block_b"]))] = int(r["students"]) -for r in csv.DictReader(open("data/triplet_counts.csv")): - trip[frozenset((r["block_a"], r["block_b"], r["block_c"]))] = int(r["students"]) - - -def cost(order): - total = 0 - for i in range(len(slots) - 1): - s, t = slots[i], slots[i + 1] - k = pair[frozenset(order[i:i + 2])] - if s["day"] == t["day"]: - total += 3 * k - elif evening and s["period"] == "PM" and t["period"] == "AM" and t["day"] == s["day"] + 1: - total += k - days = {} - for s, b in zip(slots, order): - days.setdefault(s["day"], []).append(b) - return total + sum(10 * trip[frozenset(d)] for d in days.values() if len(d) == 3) - - -best = None -for order in itertools.permutations(blocks): - if any(b in large and s["slot"] not in early for s, b in zip(slots, order)): - continue - c = cost(order) - if best is None or c < best[0]: - best = (c, order) - -os.makedirs("output", exist_ok=True) -with open("output/schedule.csv", "w", newline="") as f: - w = csv.writer(f) - w.writerow(["slot", "block"]) - for s, b in zip(slots, best[1]): - w.writerow([s["slot"], b]) -print("objective", best[0]) diff --git a/components/dnakhla/upstream/terminal_desk/oracles/math3_route_plan.py b/components/dnakhla/upstream/terminal_desk/oracles/math3_route_plan.py deleted file mode 100644 index 0052baed973981f7257e7f4ef56f9156db80e7fc..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/math3_route_plan.py +++ /dev/null @@ -1,48 +0,0 @@ -"""Oracle for math3_route_plan: earliest-arrival Dijkstra over the open roads, waiting out timed closures.""" -import heapq -import json -import os -import re - -req = json.load(open("request.json")) -src, dst = req["from"], req["to"] -closed, shut, timed = set(), set(), {} -if os.path.exists("closures.md"): - section = "" - for line in open("closures.md"): - line = line.strip() - if line.startswith("## "): - section = line[3:].lower() - elif line.startswith("- "): - m = re.match(r"- (\w+) -> (\w+)(?:: closed from minute (\d+) to minute (\d+))?$", line) - if section.startswith("closed roads"): - closed.add(m.group(1, 2)) - elif section.startswith("closed junctions"): - shut.add(line[2:]) - elif section.startswith("timed"): - timed[m.group(1, 2)] = (int(m.group(3)), int(m.group(4))) - -adj = {} -for r in json.load(open("graph.json"))["roads"]: - u, v = r["from"], r["to"] - if (u, v) not in closed and u not in shut and v not in shut: - adj.setdefault(u, []).append((v, r["minutes"])) - -best, prev, heap = {src: 0}, {}, [(0, src)] -while heap: - t, u = heapq.heappop(heap) - if t > best[u]: - continue - for v, w in adj.get(u, []): - a, b = timed.get((u, v), (0, 0)) - arrive = (b if a <= t < b else t) + w - if arrive < best.get(v, float("inf")): - best[v], prev[v] = arrive, u - heapq.heappush(heap, (arrive, v)) - -path = [dst] -while path[-1] != src: - path.append(prev[path[-1]]) -with open("route.json", "w") as f: - json.dump({"path": path[::-1], "total_minutes": best[dst]}, f) -print(path[::-1], best[dst]) diff --git a/components/dnakhla/upstream/terminal_desk/oracles/med3_silence_report.py b/components/dnakhla/upstream/terminal_desk/oracles/med3_silence_report.py deleted file mode 100644 index 564ab3e29e170351afe8a9a5765a3b94ced769b5..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/med3_silence_report.py +++ /dev/null @@ -1,44 +0,0 @@ -"""Oracle for med3_silence_report: 50 ms windows, RMS in dBFS, silent runs become removed segments.""" -import json -import math -import os -import re -import wave -from array import array - -w = wave.open("data/lecture.wav") -rate, ch, n = w.getframerate(), w.getnchannels(), w.getnframes() -x = array("h", w.readframes(n))[::ch] # mono, or channel 1 (the lapel mic) of a stereo file -win = int(rate * 0.05) -nwin = len(x) // win - -notes = open("data/notes.md").read() if os.path.exists("data/notes.md") else "" -m = re.search(r"From ([\d.]+) s to ([\d.]+) s.*?use (-[\d.]+) dBFS", notes, re.S) - -silent = [] -for i in range(nwin): - rms = math.sqrt(sum(v * v for v in x[i * win:(i + 1) * win]) / win) - db = 20 * math.log10(max(rms, 1e-9) / 32768) - limit = float(m[3]) if m and float(m[1]) <= i * 0.05 < float(m[2]) else -40.0 - silent.append(db < limit) - -segments, i = [], 0 -while i < nwin: - j = i - while j < nwin and silent[j] == silent[i]: - j += 1 - if silent[i] and (i == 0 or (j - i) * 0.05 > 2.0): - segments.append({"start": round(i * 0.05, 3), "end": round(j * 0.05, 3), "duration": round((j - i) * 0.05, 3)}) - i = j - -original = n / rate -removed = sum(s["duration"] for s in segments) -report = { - "original_duration_seconds": round(original, 3), - "compressed_duration_seconds": round(original - removed, 3), - "removed_duration_seconds": round(removed, 3), - "compression_percentage": round(removed / original * 100, 2), - "segments_removed": segments, -} -json.dump(report, open("compression_report.json", "w"), indent=2) -print(len(segments), "segments removed") diff --git a/components/dnakhla/upstream/terminal_desk/oracles/med3_sprite_count.py b/components/dnakhla/upstream/terminal_desk/oracles/med3_sprite_count.py deleted file mode 100644 index c156041f5059380d7a313896a336596bd9344ef1..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/med3_sprite_count.py +++ /dev/null @@ -1,44 +0,0 @@ -"""Oracle for med3_sprite_count: grayscale template matching with a mean-abs-diff threshold.""" -import csv -import glob -import os - -import numpy as np -from numpy.lib.stride_tricks import sliding_window_view -from PIL import Image - - -def gray(path): - return np.asarray(Image.open(path).convert("L"), dtype=np.float32) - - -notes = open("notes.md").read() if os.path.exists("notes.md") else "" -templates = {} -for name in ("coin", "enemy", "turtle"): - t = gray(f"sprites/{name}.png") - templates[name] = [t, t[:, ::-1]] if "mirrored" in notes else [t] - - -def count(frame, variants): - h, w = variants[0].shape - windows = sliding_window_view(frame, (h, w)) # only windows fully inside the frame - hits = np.zeros(windows.shape[:2], dtype=bool) - for t in variants: - hits |= np.abs(windows - t).mean(axis=(2, 3)) < 10 - found = [] - for y, x in zip(*np.nonzero(hits)): - if all(abs(y - fy) >= h or abs(x - fx) >= w for fy, fx in found): - found.append((y, x)) # neighbouring hits belong to the same object - return len(found) - - -rows = [] -for path in sorted(glob.glob("frames/frame_*.png")): - frame = gray(path) - rows.append([os.path.basename(path)] + [count(frame, templates[n]) for n in ("coin", "enemy", "turtle")]) - -with open("counting_results.csv", "w", newline="") as f: - writer = csv.writer(f) - writer.writerow(["frame_id", "coins", "enemies", "turtles"]) - writer.writerows(rows) -print(len(rows), "frames; totals", [sum(r[i] for r in rows) for i in (1, 2, 3)]) diff --git a/components/dnakhla/upstream/terminal_desk/oracles/med3_subtitle_retime.py b/components/dnakhla/upstream/terminal_desk/oracles/med3_subtitle_retime.py deleted file mode 100644 index 247da0630367e359aee55d396a11e3fdd6bae019..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/med3_subtitle_retime.py +++ /dev/null @@ -1,43 +0,0 @@ -"""Oracle for med3_subtitle_retime: map every cue time through the union of the active cuts.""" -import csv -import os -import re - - -def ms(s): - h, m, sec, milli = map(int, re.search(r"(\d+):(\d\d):(\d\d)[,.](\d{3})", s).groups()) - return ((h * 60 + m) * 60 + sec) * 1000 + milli - - -def fmt(t): - return f"{t // 3600000:02d}:{t // 60000 % 60:02d}:{t // 1000 % 60:02d},{t % 1000:03d}" - - -notes = open("edit_notes.md").read() if os.path.exists("edit_notes.md") else "" -reverted = set(re.findall(r"(C\d+) was reverted", notes)) -min_len = 500 if "shorter than 500 ms" in notes else 1 - -cuts = sorted([ms(r["start"]), ms(r["end"])] for r in csv.DictReader(open("edl.csv")) if r["cut_id"] not in reverted) -union = [] -for s, e in cuts: # merge overlapping cuts so no footage is removed twice - if union and s <= union[-1][1]: - union[-1][1] = max(union[-1][1], e) - else: - union.append([s, e]) - - -def shift(t): - return t - sum(min(t, e) - s for s, e in union if t > s) - - -text = open("episode.srt", encoding="utf-8-sig").read().replace("\r\n", "\n") -out = [] -for block in re.split(r"\n\s*\n", text.strip()): - lines = block.split("\n") - start, end = (shift(ms(p)) for p in lines[1].split("-->")) - if end - start >= min_len: - out.append(f"{len(out) + 1}\n{fmt(start)} --> {fmt(end)}\n" + "\n".join(lines[2:]) + "\n") - -os.makedirs("output", exist_ok=True) -open("output/episode.srt", "w").write("\n".join(out)) -print(len(union), "cut spans;", len(out), "cues written") diff --git a/components/dnakhla/upstream/terminal_desk/oracles/off3_ar_recon.py b/components/dnakhla/upstream/terminal_desk/oracles/off3_ar_recon.py deleted file mode 100644 index e3f75adc2ad3ab9f82a0b00559c052f130352267..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/off3_ar_recon.py +++ /dev/null @@ -1,39 +0,0 @@ -"""Oracle for off3_ar_recon: credit notes first, then payments top to bottom, memo corrections applied.""" -import csv -import os -import re - - -def rows(name): - with open(name, newline="") as fh: - return list(csv.DictReader(fh)) - - -def cents(s): - return round(float(s) * 100) - - -inv = {r["invoice"]: r for r in rows("invoices.csv")} -bal = {i: cents(r["amount"]) for i, r in inv.items()} -void, moved = None, {} -if os.path.exists("controller_memo.md"): - memo = open("controller_memo.md").read() - void = re.search(r"(INV-\d+) was voided", memo).group(1) - m = re.search(r"payment of ([\d.]+) received on (\S+) .*? to (INV-\d+)", memo) - moved = {(m.group(2), cents(m.group(1))): [m.group(3)]} -if os.path.exists("credit_notes.csv"): - for r in rows("credit_notes.csv"): - bal[r["invoice"]] = max(0, bal[r["invoice"]] - cents(r["amount"])) -for r in rows("payments.csv"): - named = [f"INV-{n}" for n in re.findall(r"\d+", r["memo"])] if "memo" in r else [r["invoice"]] - left = cents(r["amount"]) - for i in moved.get((r["date"], left), named): - take = min(left, bal[i]) - bal[i] -= take - left -= take -with open("balances.csv", "w") as fh: - fh.write("invoice,customer,balance,status\n") - for i, b in bal.items(): - status = "paid" if b == 0 else "open" if b == cents(inv[i]["amount"]) else "partial" - if i != void: - fh.write(f"{i},{inv[i]['customer']},{b / 100:.2f},{status}\n") diff --git a/components/dnakhla/upstream/terminal_desk/oracles/off3_meeting_slot.py b/components/dnakhla/upstream/terminal_desk/oracles/off3_meeting_slot.py deleted file mode 100644 index f7ed9cfcbdcf3832fa4f20c789de95d354d1f609..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/off3_meeting_slot.py +++ /dev/null @@ -1,44 +0,0 @@ -"""Oracle for off3_meeting_slot: earliest quarter-hour UTC start inside everyone's 09-17 local and free.""" -import csv -import json -import os -import re -from datetime import datetime, time, timedelta - -people = {} -for r in csv.DictReader(open("people.csv")): - h, m = r["utc_offset"][4:].split(":") - sign = -1 if r["utc_offset"][3] == "-" else 1 - people[r["person"]] = sign * timedelta(hours=int(h), minutes=int(m)) -reader = csv.reader(open("busy.csv")) -in_utc = next(reader)[2] == "start_utc" -busy = {p: [] for p in people} -for p, d, s, e in reader: - b0, b1 = datetime.fromisoformat(f"{d} {s}"), datetime.fromisoformat(f"{d} {e}") - shift = people[p] if in_utc else timedelta(0) - busy[p].append((b0 + shift, b1 + shift)) -ooo, lunch = {}, set() -if os.path.exists("calendar_notes.md"): - for line in open("calendar_notes.md"): - m = re.match(r"- (\w+) is out of office .* (\d{4}-\d\d-\d\d)", line) - if m: - ooo[m.group(1)] = m.group(2) - if re.match(r"- \w+ takes lunch", line): - lunch.add(line.split()[1]) - -dur, t = timedelta(minutes=30), datetime(2026, 11, 2) - - -def works(p, off): - s = t + off - e, day = s + dur, s.date() - blocks = busy[p] + ([(datetime.combine(day, time(12)), datetime.combine(day, time(13)))] if p in lunch else []) - if str(day) == ooo.get(p) or s < datetime.combine(day, time(9)) or e > datetime.combine(day, time(17)): - return False - return all(e <= b0 or s >= b1 for b0, b1 in blocks) - - -while not all(works(p, off) for p, off in people.items()): - t += timedelta(minutes=15) -with open("meeting.json", "w") as fh: - json.dump({"start_utc": f"{t:%Y-%m-%dT%H:%M}", "end_utc": f"{t + dur:%Y-%m-%dT%H:%M}"}, fh) diff --git a/components/dnakhla/upstream/terminal_desk/oracles/off3_pdf_xlsx_diff.py b/components/dnakhla/upstream/terminal_desk/oracles/off3_pdf_xlsx_diff.py deleted file mode 100644 index 040e092decd470e6e50bff5f35818a97bec3c369..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/off3_pdf_xlsx_diff.py +++ /dev/null @@ -1,36 +0,0 @@ -"""Oracle for off3_pdf_xlsx_diff: PDF table (pdfplumber) vs workbook (openpyxl), matched by ID.""" -import json - -import openpyxl -import pdfplumber - -NUMERIC = ("Salary", "Years", "Score") - - -def value(field, v): - if field in NUMERIC: # the PDF may print salaries as $52,300 - x = float(str(v).replace("$", "").replace(",", "")) - return x if field == "Score" else int(x) - return str(v).strip() # trailing spaces are not changes - - -old, cols = {}, None -with pdfplumber.open("employees_backup.pdf") as pdf: - for page in pdf.pages: - for row in page.extract_table(): - if row[0] == "ID": # the header repeats on every page - cols = row - else: - old[row[0]] = dict(zip(cols, row)) -rows = list(openpyxl.load_workbook("employees_current.xlsx")["Employees"].iter_rows(values_only=True)) -new = {r[0]: dict(zip(rows[0], r)) for r in rows[1:]} - -mods = [] -for i in sorted(set(old) & set(new)): - for f in cols[1:]: - a, b = value(f, old[i][f]), value(f, new[i][f]) - if a != b: - mods.append({"id": i, "field": f, "old_value": a, "new_value": b}) -report = {"deleted_employees": sorted(set(old) - set(new)), "modified_employees": mods} -with open("diff_report.json", "w") as fh: - json.dump(report, fh, indent=1) diff --git a/components/dnakhla/upstream/terminal_desk/oracles/sci3_kinetics_fit.py b/components/dnakhla/upstream/terminal_desk/oracles/sci3_kinetics_fit.py deleted file mode 100644 index c88cc85582ca6eca851bc8fa6221e8352300c6f0..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/sci3_kinetics_fit.py +++ /dev/null @@ -1,38 +0,0 @@ -# sci3_kinetics_fit: order by R^2, k, half-life, Arrhenius -import csv -import glob -import json -import math -import os -import re -from statistics import correlation, linear_regression - -notes = open("data/lab_notes.txt").read() if os.path.exists("data/lab_notes.txt") else "" -bad = set(re.findall(r"Sample (S\d+) in (\S+\.csv)", notes)) -SCALE = {"time_s": 1, "time_min": 60, "conc_M": 1, "conc_mM": 0.001} - - -def ols(t, y): # slope and R^2 - return linear_regression(t, y).slope, correlation(t, y) ** 2 - - -fits = [] -for path in sorted(glob.glob("data/run*.csv")): # run_289K.csv sorts before run_302K.csv - name = os.path.basename(path) - (_, tk, ck, *_), *body = csv.reader(open(path)) - t, c = zip(*[(float(x) * SCALE[tk], float(y) * SCALE[ck]) for s, x, y, *flag in body - if " r2 else (name, 2, s2, c[0])) - -name, order, k, c0 = fits[0] -if not notes: # stated first order - report = {"k_per_s": k, "half_life_s": math.log(2) / k} -elif len(fits) == 1: - report = {"order": order, "k": k, "half_life_s": math.log(2) / k if order == 1 else 1 / (k * c0)} -else: - lo, hi, k_hi = int(name[4:7]), int(fits[1][0][4:7]), fits[1][2] - ea = 8.314 * math.log(k_hi / k) / (1 / lo - 1 / hi) / 1000 - report = {"order": order, "k_low": k, "k_high": k_hi, "ea_kj_per_mol": ea} -json.dump(report, open("kinetics_report.json", "w")) diff --git a/components/dnakhla/upstream/terminal_desk/oracles/sci3_lightcurve_period.py b/components/dnakhla/upstream/terminal_desk/oracles/sci3_lightcurve_period.py deleted file mode 100644 index d15523a0e5d531d016a7bc28f0dbb2cb6598b678..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/sci3_lightcurve_period.py +++ /dev/null @@ -1,38 +0,0 @@ -# oracle for sci3_lightcurve_period: filter, running-median detrend, box search over the stated grid -import math -import os -import re - -rows = [list(map(float, ln.split())) for ln in open("data/lc.txt") if not ln.startswith("#")] -rows = [r for r in rows if r[2] == 0] -if os.path.exists("data/README.md"): - a, b = map(float, re.search(r"MJD ([\d.]+) and ([\d.]+)", open("data/README.md").read()).groups()) - rows = [r for r in rows if not a <= r[0] <= b] -t = [r[0] for r in rows] -f = [r[1] for r in rows] -resid = [] -for i in range(len(f)): # divide by a running median ~0.75 d wide (27 points each side) - win = sorted(f[max(0, i - 27):i + 28]) - resid.append(f[i] / win[len(win) // 2] - 1) - -DUR, SUB = 0.10, 4 # box days (stated 0.08-0.12; 0.10 finds all), sub-bins per box -t = [x - t[0] for x in t] - - -def power(p): - """Best box signal at trial period p: phase-fold into bins, slide a box of SUB bins.""" - nb = int(round(SUB * p / DUR)) - c, s, n = nb / p, [0.0] * nb, [0] * nb - for b, r in zip([int(x * c) % nb for x in t], resid): - s[b] += r - n[b] += 1 - s, n = s + s[:SUB], n + n[:SUB] - return max(-sum(s[b:b + SUB]) / math.sqrt(max(sum(n[b:b + SUB]), 1)) for b in range(nb)) - - -coarse = max((k / 1000 for k in range(1000, 5001, 2)), key=power) # every other grid step -period = max((coarse + k / 10000 for k in range(-20, 21)), key=power) # then refine - -with open("period.txt", "w") as fh: - fh.write(f"{period:.5f}\n") -print(f"{period:.5f}", "power", round(power(period), 5), "points", len(t)) diff --git a/components/dnakhla/upstream/terminal_desk/oracles/sci3_stoich_batch.py b/components/dnakhla/upstream/terminal_desk/oracles/sci3_stoich_batch.py deleted file mode 100644 index 319b48401e5691959db2a50d31ae010d47996721..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/sci3_stoich_batch.py +++ /dev/null @@ -1,46 +0,0 @@ -# oracle for sci3_stoich_batch: lot lookup, molar masses, limiting reagent, yields -import csv -import json -import re - -mass = {r["element"]: float(r["mass"]) for r in csv.DictReader(open("data/atomic_masses.csv"))} - - -def molar(formula): - total = 0.0 - for part in formula.split("*"): # hydrate: CuSO4*5H2O - n, body = re.match(r"(\d*)(.*)", part).groups() - while "(" in body: # (SO4)3 -> SO4SO4SO4 - body = re.sub(r"\(([^()]*)\)(\d*)", lambda m: m.group(1) * int(m.group(2) or 1), body) - atoms = re.findall(r"([A-Z][a-z]?)(\d*)", body) - total += int(n or 1) * sum(mass[e] * int(k or 1) for e, k in atoms) - return total - - -lots = {} -for r in csv.DictReader(open("data/reagents.csv")): # latest certified row per lot wins - if r["lot"] not in lots or r["certified"] > lots[r["lot"]]["certified"]: - lots[r["lot"]] = r - -text = open("data/batch.txt").read() -left, right = re.search(r"Reaction: (.+)", text).group(1).split(" -> ") - - -def side(s): - return {f: int(c or 1) for c, f in re.findall(r"(?:(\d+) )?(\S+)", s) if f != "+"} - - -coef, prod_coef = side(left), side(right) -equiv = {} -for grams, formula, lot in re.findall(r"Charged: ([\d.]+) g (\S+) from lot (\S+)", text): - pure = float(grams) * float(lots[lot]["purity_pct"]) / 100 - equiv[formula] = pure / molar(formula) / coef[formula] -iso, product = re.search(r"Isolated: ([\d.]+) g (\S+)", text).groups() - -limiting = min(equiv, key=equiv.get) -mm = molar(product) -theo = equiv[limiting] * prod_coef[product] * mm -report = {"limiting_reagent": limiting, "product_molar_mass": mm, "theoretical_yield_g": theo, - "percent_yield": float(iso) / theo * 100} -json.dump(report, open("batch_report.json", "w"), indent=1) -print(report) diff --git a/components/dnakhla/upstream/terminal_desk/oracles/sec3_auth_triage.py b/components/dnakhla/upstream/terminal_desk/oracles/sec3_auth_triage.py deleted file mode 100644 index e264428f983d5caea715e7921cf8ba457b8575b9..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/sec3_auth_triage.py +++ /dev/null @@ -1,37 +0,0 @@ -# oracle: sec3_auth_triage. Count failed SSH passwords per source inside a 10-minute window. -import ipaddress -import os -import re -from collections import defaultdict - -K, WINDOW = 5, 600 -notes = open("README.md").read() if os.path.exists("README.md") else "" -allow = [ipaddress.ip_network(n) for n in re.findall(r"\d+\.\d+\.\d+\.\d+/\d+", notes)] - -fails = defaultdict(list) -for name in ("auth.log.1", "auth.log"): # older file first - if not os.path.exists(name): - continue - for line in open(name): - clock, _, msg = line.rstrip("\n").partition(" ") - h, m, s = map(int, clock.split(":")) - t = h * 3600 + m * 60 + s - rep = re.match(r"message repeated (\d+) times: \[ Failed password for .* from (\S+?)\]$", msg) - if rep: - fails[rep.group(2)] += [t] * int(rep.group(1)) - continue - hit = re.match(r"Failed password for .* from (\S+)$", msg) - if hit: - fails[hit.group(1)].append(t) - -if not fails: - raise SystemExit("no failed attempts parsed") -blocked = [] -for ip, ts in fails.items(): - ts.sort() - if any(ts[i + K - 1] - ts[i] <= WINDOW for i in range(len(ts) - K + 1)): - if not any(ipaddress.ip_address(ip) in net for net in allow): - blocked.append(ip) -with open("blocked.txt", "w") as f: - f.write("".join(ip + "\n" for ip in sorted(blocked))) -print(len(fails), "sources with failures,", len(blocked), "blocked:", blocked) diff --git a/components/dnakhla/upstream/terminal_desk/oracles/sec3_exfil_flows.py b/components/dnakhla/upstream/terminal_desk/oracles/sec3_exfil_flows.py deleted file mode 100644 index 4716ee3df6bf24fffae6931178e1fac40ad7bbdb..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/sec3_exfil_flows.py +++ /dev/null @@ -1,35 +0,0 @@ -# oracle: sec3_exfil_flows. Big, unapproved, outbound flows that start outside office hours. -import csv -import ipaddress -import json -import os - -DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] -policy = json.load(open("policy.json")) -approved = list(policy.get("allowlist", [])) -if os.path.exists("allowlist.txt"): - approved += [ln.strip() for ln in open("allowlist.txt") if ln.strip() and not ln.startswith("#")] -approved = [ipaddress.ip_network(a) for a in approved] -internal = [ipaddress.ip_network(n) for n in policy.get("internal_networks", [])] -offset = policy.get("office_utc_offset_hours", 0) * 60 # local = UTC + offset (README, L3) - - -def minutes(hhmm): - h, m = hhmm.split(":") - return int(h) * 60 + int(m) - - -start, end = (minutes(x) for x in policy["business_hours"]) -alerts = [] -for r in csv.DictReader(open("flows.csv", newline="")): - t = (DAYS.index(r["day"]) * 1440 + minutes(r["time"]) + offset) % (7 * 1440) - day, minute = DAYS[t // 1440], t % 1440 - off_hours = day not in policy["business_days"] or not start <= minute < end - dst = ipaddress.ip_address(r["dst"]) - if (float(r["mb_out"]) > policy["threshold_mb"] and off_hours - and not any(dst in n for n in approved) and not any(dst in n for n in internal)): - alerts.append(int(r["flow"])) -alerts.sort() -with open("alerts.json", "w") as f: - json.dump(alerts, f) -print(len(alerts), "alerts:", alerts[:10]) diff --git a/components/dnakhla/upstream/terminal_desk/oracles/sec3_fw_verdicts.py b/components/dnakhla/upstream/terminal_desk/oracles/sec3_fw_verdicts.py deleted file mode 100644 index 1d493da2de0a9726314edcc9127e519500905695..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/sec3_fw_verdicts.py +++ /dev/null @@ -1,49 +0,0 @@ -# oracle: sec3_fw_verdicts. First matching rule by ascending rule_no; default deny is rule 0. -import csv -import ipaddress -import os - -groups = {} -if os.path.exists("groups.txt"): - for line in open("groups.txt"): - if line.strip() and not line.startswith("#"): - name, _, nets = line.partition(":") - groups["@" + name.strip()] = nets.split() - -rules = [] -for r in csv.DictReader(open("rules.csv", newline="")): - if r.get("enabled", "yes") != "yes": - continue - src = r["src"] - nets = None if src == "any" else [ipaddress.ip_network(n) for n in groups.get(src, [src])] - ports = None - if r["ports"] != "any": - ports = set() - for part in r["ports"].split(";"): - lo, _, hi = part.partition("-") - ports.update(range(int(lo), int(hi or lo) + 1)) - rules.append((int(r["rule_no"]), r["action"], r["proto"], nets, ports)) -rules.sort(key=lambda r: r[0]) - - -def decide(c): - ip = ipaddress.ip_address(c["src_ip"]) - port = c["dst_port"].strip() - for no, action, proto, nets, ports in rules: - if proto not in ("any", c["proto"]): - continue - if nets is not None and not any(ip in n for n in nets): - continue - if ports is not None and (not port or int(port) not in ports): - continue - return action, no - return "deny", 0 - - -conns = list(csv.DictReader(open("connections.csv", newline=""))) -with open("verdicts.csv", "w", newline="") as f: - w = csv.writer(f) - w.writerow(["id", "verdict", "rule"]) - for c in conns: - w.writerow([c["id"], *decide(c)]) -print(len(rules), "rules loaded,", len(conns), "connections") diff --git a/components/dnakhla/upstream/terminal_desk/oracles/sw3_dep_lock.py b/components/dnakhla/upstream/terminal_desk/oracles/sw3_dep_lock.py deleted file mode 100644 index 364b07da75d4863365248614c030e4e4ee05cb49..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/sw3_dep_lock.py +++ /dev/null @@ -1,51 +0,0 @@ -"""Oracle for sw3_dep_lock: brute-force every pick of the requested packages and keep the preferred valid one.""" -import itertools -import os -import re - - -def vkey(v): - return tuple(int(x) for x in v.split(".")) - - -def parse(spec): - m = re.match(r"([a-z]+)(.*)", spec) - conds = [re.match(r"(>=|<|!=|==)(.+)", c).groups() for c in m[2].split(",") if c] - return m[1], [(op, vkey(w)) for op, w in conds] - - -def ok(v, conds): - k = vkey(v) - tests = {">=": k.__ge__, "<": k.__lt__, "!=": k.__ne__, "==": k.__eq__} - return all(tests[op](w) for op, w in conds) - - -wanted = [parse(ln.strip()) for ln in open("requirements.txt") if ln.strip()] -pkgs = [n for n, _ in wanted] -yanked = set() -if os.path.exists("yanked.txt"): - yanked = {tuple(ln.split()) for ln in open("yanked.txt") if ln.strip() and not ln.startswith("#")} - -releases = {} # package -> {version: [(dep, conds)]} -for ln in open("index.txt"): - if not ln.strip() or ln.startswith("#"): - continue - name, ver, req = ln.split() - if name in pkgs and (name, ver) not in yanked: - releases.setdefault(name, {})[ver] = [] if req == "-" else [parse(r) for r in req.split(";")] - -best = None -for combo in itertools.product(*(sorted(releases[p], key=vkey) for p in pkgs)): - pick = dict(zip(pkgs, combo)) - if not all(ok(pick[n], c) for n, c in wanted): - continue - if not all(ok(pick[d], c) for p in pkgs for d, c in releases[p][pick[p]]): - continue - score = tuple(vkey(pick[p]) for p in pkgs) - if best is None or score > best[0]: - best = (score, pick) - -pick = best[1] -with open("lock.txt", "w") as fh: - fh.write("".join(f"{p}=={pick[p]}\n" for p in sorted(pick))) -print(open("lock.txt").read()) diff --git a/components/dnakhla/upstream/terminal_desk/oracles/sw3_fix_module.py b/components/dnakhla/upstream/terminal_desk/oracles/sw3_fix_module.py deleted file mode 100644 index 2bb04cab01d9a991865a585f74c70e18c094c954..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/sw3_fix_module.py +++ /dev/null @@ -1,59 +0,0 @@ -"""Oracle for sw3_fix_module: rewrite each function from its docstring and the CHANGELOG.""" -import glob -import os -import re - -log = open("CHANGELOG.md").read() if os.path.exists("CHANGELOG.md") else "" -REV = sorted(set(re.findall(r"### Changed\n- `(\w+)`", log))) -LIB = '''import re -REV = REVSET - -def median(values): - if not values and "median" in REV: - return None - s = sorted(values) - m = len(s) // 2 - return s[m] if len(s) % 2 else (s[m - 1] + s[m]) / 2 - -def clamp(x, lo, hi): - if lo > hi and "clamp" in REV: - lo, hi = hi, lo - return min(max(x, lo), hi) - -def moving_average(values, k): - out = [sum(values[i:i + k]) / k for i in range(len(values) - k + 1)] - return [round(v, 4) for v in out] if "moving_average" in REV else out - -def percent_change(old, new): - return round((new - old) / old * 100, 1 if "percent_change" in REV else 2) - -def chunk(items, size): - return [items[i:i + size] for i in range(0, len(items), size)] - -def is_leap(year): - return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) - -def dedupe(items): - seen, out = set(), [] - for item in items: - k = item.lower() if "dedupe" in REV and isinstance(item, str) else item - if k not in seen: - seen.add(k) - out.append(item) - return out - -def overlap(a_start, a_end, b_start, b_end): - return max(0, min(a_end, b_end) - max(a_start, b_start)) - -def to_seconds(clock): - return sum(int(p) * 60 ** i for i, p in enumerate(reversed(clock.split(":")))) - -def word_count(text): - counts = {} - for w in re.findall("[a-z0-9]+" if "word_count" in REV else "[a-z]+", text.lower()): - counts[w] = counts.get(w, 0) + 1 - return counts -''' -for path in glob.glob("src/*.py"): - open(path, "w").write(LIB.replace("REVSET", repr(REV))) - print("rewrote", path, REV) diff --git a/components/dnakhla/upstream/terminal_desk/oracles/sw3_rate_limit.py b/components/dnakhla/upstream/terminal_desk/oracles/sw3_rate_limit.py deleted file mode 100644 index 1d3ac7a88d478c74b336879dadd1b90b4dd7ed7e..0000000000000000000000000000000000000000 --- a/components/dnakhla/upstream/terminal_desk/oracles/sw3_rate_limit.py +++ /dev/null @@ -1,44 +0,0 @@ -"""Oracle for sw3_rate_limit: replay per-key token buckets in ts order and list the rejected ids.""" -import csv -import json -import os -import re - -cfg = json.load(open("limits.json")) -tiers = cfg["tiers"] -key_tier = cfg["keys"] -default = cfg.get("default_tier") -exempt = set(cfg.get("exempt_keys", [])) - -changes = [] # (from_ts, tier, capacity, refill_per_sec) -if os.path.exists("CHANGE_NOTICE.md"): - num = r"(\d+(?:\.\d+)?)" - pat = rf"From ts {num} onward the (\w+) tier is capacity {num}, refill_per_sec {num}" - for m in re.finditer(pat, open("CHANGE_NOTICE.md").read()): - changes.append((float(m[1]), m[2], float(m[3]), float(m[4]))) - assert changes, "CHANGE_NOTICE.md did not parse" - -reqs = list(csv.DictReader(open("requests.csv"))) -reqs.sort(key=lambda r: (float(r["ts"]), int(r["id"]))) - -buckets, rejected = {}, [] -for r in reqs: - key, ts, cost = r["key"], float(r["ts"]), int(r["cost"]) - if key in exempt: - continue - tier = key_tier.get(key, default) - cap, rate = tiers[tier]["capacity"], tiers[tier]["refill_per_sec"] - for at, name, c, rr in changes: - if name == tier and ts >= at: - cap, rate = c, rr - tokens, last = buckets.get(key, (cap, ts)) - tokens = min(cap, tokens + (ts - last) * rate) - if tokens >= cost: - tokens -= cost - else: - rejected.append(int(r["id"])) - buckets[key] = (tokens, ts) - -rejected = sorted(set(rejected)) -json.dump(rejected, open("rejected.json", "w")) -print(len(reqs), "requests,", len(rejected), "rejected, first:", rejected[:5]) diff --git a/components/skillsdesk/.dockerignore b/components/skillsdesk/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..b908d4cbe37ccea3388a2f308595ae63a255755d --- /dev/null +++ b/components/skillsdesk/.dockerignore @@ -0,0 +1,3 @@ +__pycache__/ +*.pyc +.DS_Store diff --git a/components/skillsdesk/ADAPTER_NOTICE b/components/skillsdesk/ADAPTER_NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..1187600f72d9c86490157d1321db0c6bea1a7746 --- /dev/null +++ b/components/skillsdesk/ADAPTER_NOTICE @@ -0,0 +1,2 @@ +This distribution adds the shared Arena interface and the selected task registry. +Original Skills Desk task generators, graders and fixed instance seeds are retained. diff --git a/components/skillsdesk/Dockerfile b/components/skillsdesk/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8f28be1a5e8bb20c8eb33864128ae227b23ea7ff --- /dev/null +++ b/components/skillsdesk/Dockerfile @@ -0,0 +1,15 @@ +FROM ghcr.io/syndicate604/skills-desk@sha256:5492135dea6e9ec3b0c9a0dacf22a53d79014271c1736b152afdab69d89414df +USER root +COPY upstream/terminal_desk /opt/terminal_desk/terminal_desk +COPY upstream/openenv.yaml /opt/terminal_desk/openenv.yaml +COPY runtime /opt/skillsdesk_compat +COPY SOURCE_MANIFEST.json /opt/skillsdesk_compat/SOURCE_MANIFEST.json +COPY LICENSE NOTICE ADAPTER_NOTICE /opt/skillsdesk_compat/licenses/ +RUN chmod -R go-rwx /opt/terminal_desk /opt/skillsdesk_compat +ENV PYTHONPATH=/opt/skillsdesk_compat:/opt/terminal_desk OPENENV_MODE=production PYTHONDONTWRITEBYTECODE=1 +WORKDIR /opt/skillsdesk_compat +LABEL org.opencontainers.image.title="Skills Breadth v10" \ + org.opencontainers.image.description="Original Skills Desk artifact and code repair tasks with the shared Arena interface" \ + org.opencontainers.image.source="https://huggingface.co/datasets/bochencs/openenv-multidomain" \ + org.opencontainers.image.licenses="Apache-2.0" +CMD ["python", "-m", "skillsdesk_compat.server"] diff --git a/components/dnakhla/LICENSE b/components/skillsdesk/LICENSE similarity index 100% rename from components/dnakhla/LICENSE rename to components/skillsdesk/LICENSE diff --git a/components/skillsdesk/NOTICE b/components/skillsdesk/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..58fdbd780296862854b0fe460190c4c628d1d18b --- /dev/null +++ b/components/skillsdesk/NOTICE @@ -0,0 +1,12 @@ +Skills Desk +Copyright 2026 Syndicate604 + +This product is a fork of Terminal Desk v2 by dnakhla +(https://huggingface.co/datasets/dnakhla/terminal-desk, revision 7fe454e7), +licensed under the Apache License, Version 2.0, by way of Science Desk +(Syndicate604). The server, sandbox and grading core come from that work, and +the fix_toolkit task is adapted from its sw_fix family. Changes: all task +families are new (five skills: evidence, computation, transformation, repair, +constraints), a frozen reserved evaluation set, a fixed instance per task id, +strict output-structure grading, hidden-input grading of repaired code, +reference agent scripts and deliberate-mistake tests. diff --git a/components/skillsdesk/README.md b/components/skillsdesk/README.md new file mode 100644 index 0000000000000000000000000000000000000000..592f5af2bb6a94b2d8c0af38eae5135d7f089b8a --- /dev/null +++ b/components/skillsdesk/README.md @@ -0,0 +1,5 @@ +Original Skills Desk tasks from Syndicate604, with the shared Arena interface. + +Run: `python -m skillsdesk_compat.server` + +Run the service as root; task commands run as nobody. Use one episode per fresh sandbox and one active session. The selected original fixed IDs are listed in SOURCE_MANIFEST.json. diff --git a/components/skillsdesk/SOURCE_MANIFEST.json b/components/skillsdesk/SOURCE_MANIFEST.json new file mode 100644 index 0000000000000000000000000000000000000000..49f98d85b2bf5a6b6056e4fdfa1bf6ed1785736a --- /dev/null +++ b/components/skillsdesk/SOURCE_MANIFEST.json @@ -0,0 +1,61 @@ +{ + "dataset": "Syndicate604/skills-desk", + "revision": "a785ccdc9784ed863d0ffecec826d72176c0a785", + "license": "Apache-2.0", + "base_image": "ghcr.io/syndicate604/skills-desk@sha256:5492135dea6e9ec3b0c9a0dacf22a53d79014271c1736b152afdab69d89414df", + "original_files": { + "openenv.yaml": "88e8863954ec9a9d34d07cdde0d5d4688f1fc85a2c595f13c7b9d4d10be6218e", + "terminal_desk/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "terminal_desk/core/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "terminal_desk/core/grading.py": "d61652f92fc3691f55e71b76c9ef17ccabb4502ff7038f7626b69f52918907c9", + "terminal_desk/core/shell.py": "e6af14ad4263f3067f47dc841f28fc6d24de64c8400df91facce1fdd71dced5d", + "terminal_desk/families/__init__.py": "3d04bdea30395f1e8fa03d804a5728777633bf319f4e00575ef047f2011fa411", + "terminal_desk/families/base.py": "a0ef4dec6a2932ead3331d0cea6e5bb3b91fa91075508560aa9cf08495b0ad6f", + "terminal_desk/families/compute.py": "60c1e5c80f42479d79c86e222c3a101182955822b5b555b25cf0cff40d7bc7c3", + "terminal_desk/families/compute2.py": "91cdb191a4af146bc8901e585f213d7377584ea6c493c60839a4aeddd7e63d33", + "terminal_desk/families/constraints.py": "25494ac58d4fa7196b5e702dfc9cc55e9635dbaa1603de160a80d39fb09d3ea0", + "terminal_desk/families/constraints2.py": "411991bca80cbbdfb08eacc5192a07ba45442e41a3e600780b2efdac1b072cc4", + "terminal_desk/families/evidence.py": "c2ff755246cc006d04f36acf9f8787efad0ca22a6e2c0c9b2dc14bb4d3fb7045", + "terminal_desk/families/evidence2.py": "d32eedf32ee8e385bd123501b33c2d15c75a7604cc9a029e97d8dabf6de97e60", + "terminal_desk/families/repair.py": "a3392b6cf21d6cdb562862fb9f0999ec8a57a4116162e3b58d1c00f9fb19b781", + "terminal_desk/families/repair2.py": "1d22338235ffb0e25786a45ddb0c28be00081f89df1bee94052d57f6ac01ace6", + "terminal_desk/families/transform.py": "d478ea588230f6394fdad03fef1d377399086015f7a33d1f892e78c268808df1", + "terminal_desk/families/transform2.py": "2c176531664ffcbfb998283b1b6cc145ddac976c7b2137b5535a2a9e1b422af2", + "terminal_desk/families/util.py": "0e3b71ebcd82ccce47ea3bcbcc98efafb23b297f9831b2e37afd399d44eb5832", + "terminal_desk/models.py": "f31264b0909878c6f2d4d18a270c7d92bc895052150c56e5ac3e6b38d4ceebb4", + "terminal_desk/reserved/__init__.py": "012f259f4fd2aad8af71accaf7686f8e76235491d9ad200bfbec9f3641afa330", + "terminal_desk/reserved/compute.py": "e87cfd26e155b8c0a830cfd6809274c930ee45d31f2ac44398f35385b2dbe083", + "terminal_desk/reserved/constraints.py": "ca168704db89a1da64fd0262c44280e0461d2a58d4f9191a6c9747d19cb0bee0", + "terminal_desk/reserved/evidence.py": "e3c5f779c29f730fd2844018150078640c17425bfe6ddb922103a661a86c5ee0", + "terminal_desk/reserved/repair.py": "121c2be70cd21ca16c254153eebbce895f2bb86c37aedcaaaa237662917e18e5", + "terminal_desk/reserved/transform.py": "bd97f765a7e468bd2e4b4a6e1e959177df999a123d712c5c2b4f93e4359c99cf", + "terminal_desk/server/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "terminal_desk/server/app.py": "6bf7658ec8ad07dda230a01fd893091a9b87df18ebf6af25af6c35965ed01fd8", + "terminal_desk/server/environment.py": "82aa929676d76fe2f8d81a5122598986ac2950339dbfc4366de03a3604cd7319" + }, + "selected_tasks": [ + "ev_calibration-L1", + "cmp_fifo-L1", + "tx_events-L1", + "fix_units-L1", + "plan_shifts-L1", + "ev_badges-L1", + "cmp_meter-L1", + "tx_pivot-L1", + "fix_toolkit-L1", + "plan_load-L1", + "ev_bankrec-L1", + "cmp_smooth-L1", + "tx_sessions-L1", + "fix_bizdays-L1", + "plan_disks-L1", + "ev_backorder-L2", + "ev_dupes-L1", + "tx_mdtable-L1", + "fix_mergelogs-L1", + "plan_delivery-L1" + ], + "instance_policy": "Original fixed base instance; production ignores client seed.", + "sdk_revision": "86a180ede21e044f7929b9a7783ad83aa67d83a3", + "sdk_wheel_sha256": "c00388296c8930d67d296c5d74eacb41dbd15372a144c24aeb5d816d049c403d" +} diff --git a/components/skillsdesk/UPSTREAM_DOCKERFILE b/components/skillsdesk/UPSTREAM_DOCKERFILE new file mode 100644 index 0000000000000000000000000000000000000000..256cb33dfec6de07c63920d6f3d05622fa03b8fe --- /dev/null +++ b/components/skillsdesk/UPSTREAM_DOCKERFILE @@ -0,0 +1,40 @@ +# Skills Desk OpenEnv server (forked from Science Desk / dnakhla's Terminal Desk v2, Apache-2.0). linux/amd64 only: +# DOCKER_DEFAULT_PLATFORM=linux/amd64 docker build -t ghcr.io/syndicate604/skills-desk:v1 . +FROM python:3.12-slim + +RUN apt-get update \ + && apt-get install -y --no-install-recommends jq bc sqlite3 \ + && rm -rf /var/lib/apt/lists/* + +# The server lives outside /app: /app is the task workspace, as in the operator's task images. +WORKDIR /opt/terminal_desk +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + PYTHONPATH=/opt/terminal_desk + +# OpenEnv at the arena's pinned revision (86a180e), vendored as a wheel. +COPY vendor ./vendor +RUN pip install ./vendor/openenv-0.6.1.dev0-py3-none-any.whl && rm -rf ./vendor + +# Scientific Python for the agent's own scripts. +RUN pip install numpy==1.26.4 scipy==1.13.1 pandas==2.2.2 astropy==6.1.4 + +COPY terminal_desk ./terminal_desk +COPY openenv.yaml ./ + +# The server runs as root; agent commands run as nobody and cannot read the +# generators, the grader or the server's memory. +RUN chmod -R go-rwx /opt/terminal_desk && mkdir -p /app + +LABEL org.opencontainers.image.title="Skills Desk" \ + org.opencontainers.image.description="OpenEnv environment: multi-step tool-use tasks (evidence, computation, transformation, repair, constraints) served through the tbench2_env schema; forked from dnakhla/terminal-desk v2" \ + org.opencontainers.image.source="https://huggingface.co/datasets/Syndicate604/skills-desk" \ + org.opencontainers.image.licenses="Apache-2.0" + +EXPOSE 8000 +HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \ + CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=2)" || exit 1 + +CMD ["uvicorn", "terminal_desk.server.app:app", "--host", "0.0.0.0", "--port", "8000"] diff --git a/components/skillsdesk/UPSTREAM_TRAINING_TASKS.txt b/components/skillsdesk/UPSTREAM_TRAINING_TASKS.txt new file mode 100644 index 0000000000000000000000000000000000000000..63f0f98e9ff56805df72c83b8ac4e27ae0009362 --- /dev/null +++ b/components/skillsdesk/UPSTREAM_TRAINING_TASKS.txt @@ -0,0 +1,41 @@ +# Skills Desk v1 training bank: 40 task ids, 8 per skill. Frozen 2026-10-18. +ev_backorder-L1 +ev_backorder-L2 +ev_calibration-L1 +cmp_channels-L1 +cmp_rainfall-L1 +cmp_rainfall-L2 +tx_contacts-L1 +tx_events-L1 +fix_toolkit-L1 +fix_report-L1 +plan_shifts-L1 +plan_shifts-L2 +plan_load-L1 +ev_deliveries-L1 +ev_badges-L1 +ev_dupes-L1 +ev_bankrec-L1 +ev_fixedin-L1 +cmp_meter-L1 +cmp_grades-L1 +cmp_fifo-L1 +cmp_smooth-L1 +cmp_loan-L1 +tx_xml-L1 +tx_pivot-L1 +tx_mdtable-L1 +tx_sessions-L1 +tx_fixedwidth-L1 +tx_dates-L1 +fix_paginate-L1 +fix_logline-L1 +fix_units-L1 +fix_bizdays-L1 +fix_dedupe-L1 +fix_mergelogs-L1 +plan_roster_fix-L1 +plan_roster_fill-L1 +plan_courses-L1 +plan_disks-L1 +plan_delivery-L1 diff --git a/components/dnakhla/runtime/common/__init__.py b/components/skillsdesk/runtime/common/__init__.py similarity index 100% rename from components/dnakhla/runtime/common/__init__.py rename to components/skillsdesk/runtime/common/__init__.py diff --git a/components/dnakhla/runtime/common/contracts.py b/components/skillsdesk/runtime/common/contracts.py similarity index 100% rename from components/dnakhla/runtime/common/contracts.py rename to components/skillsdesk/runtime/common/contracts.py diff --git a/components/dnakhla/runtime/common/models.py b/components/skillsdesk/runtime/common/models.py similarity index 100% rename from components/dnakhla/runtime/common/models.py rename to components/skillsdesk/runtime/common/models.py diff --git a/components/dnakhla/upstream/terminal_desk/__init__.py b/components/skillsdesk/runtime/skillsdesk_compat/__init__.py similarity index 100% rename from components/dnakhla/upstream/terminal_desk/__init__.py rename to components/skillsdesk/runtime/skillsdesk_compat/__init__.py diff --git a/components/dnakhla/runtime/dnakhla_compat/environment.py b/components/skillsdesk/runtime/skillsdesk_compat/environment.py similarity index 52% rename from components/dnakhla/runtime/dnakhla_compat/environment.py rename to components/skillsdesk/runtime/skillsdesk_compat/environment.py index fe6e6efa5a6e2034e266ceece796cecfc9a573ee..5c65b3698ba104ada0511cc5ba68a8735f616ae8 100644 --- a/components/dnakhla/runtime/dnakhla_compat/environment.py +++ b/components/skillsdesk/runtime/skillsdesk_compat/environment.py @@ -1,7 +1,8 @@ -"""Translate the shared Arena contract without editing original task code.""" +"""Serve a fixed original Skills Desk task bank through the shared Arena contract.""" import hashlib import json import math +import os from pathlib import Path from threading import RLock @@ -9,36 +10,52 @@ from openenv.core.env_server.interfaces import Environment from openenv.core.env_server.types import EnvironmentMetadata, State from common.models import ArenaAction, ArenaObservation -ROOT = Path('/opt/terminal_desk') -MANIFEST = json.loads(Path('/opt/dnakhla_compat/SOURCE_MANIFEST.json').read_text()) +SOURCE_ROOT = Path('/opt/terminal_desk') +MANIFEST_PATH = Path('/opt/skillsdesk_compat/SOURCE_MANIFEST.json') +MANIFEST = json.loads(MANIFEST_PATH.read_text()) +if MANIFEST['dataset'] != 'Syndicate604/skills-desk' or MANIFEST['revision'] != 'a785ccdc9784ed863d0ffecec826d72176c0a785': + raise RuntimeError('Unexpected original source identity') for relative, digest in MANIFEST['original_files'].items(): - if hashlib.sha256((ROOT / relative).read_bytes()).hexdigest() != digest: - raise RuntimeError('Original Terminal Desk file hash mismatch: ' + relative) - + path = SOURCE_ROOT / relative + if (path.is_symlink() or not path.is_file() or not path.resolve().is_relative_to(SOURCE_ROOT.resolve()) + or hashlib.sha256(path.read_bytes()).hexdigest() != digest): + raise RuntimeError('Original source hash mismatch: ' + relative) +actual_python = {p.relative_to(SOURCE_ROOT).as_posix() for p in (SOURCE_ROOT / 'terminal_desk').rglob('*.py')} +if actual_python != {p for p in MANIFEST['original_files'] if p.endswith('.py')}: + raise RuntimeError('Original Python source inventory mismatch') + +from terminal_desk.core import shell +from terminal_desk.families import is_reserved, parse_task_id from terminal_desk.models import Tbench2Action -from terminal_desk.families import all_task_ids -from terminal_desk.server.environment import TerminalDeskEnvironment, MAX_CALLS +from terminal_desk.server.environment import APP, MAX_CALLS, TerminalDeskEnvironment TASK_IDS = tuple(MANIFEST['selected_tasks']) -if len(set(TASK_IDS)) != len(TASK_IDS) or not set(TASK_IDS).issubset(all_task_ids()): - raise RuntimeError('Invalid task registry') +if len(TASK_IDS) != 20 or len(set(TASK_IDS)) != len(TASK_IDS): + raise RuntimeError('Invalid selected task registry') +for task_id in TASK_IDS: + family, level, instance = parse_task_id(task_id) + if is_reserved(task_id) or instance != 0 or task_id != f'{family}-L{level}': + raise RuntimeError('Invalid selected original instance') +if APP != '/app' or MAX_CALLS != 32 or shell.WALL_TIMEOUT_S != 20 or shell.CPU_SECONDS != 20: + raise RuntimeError('Original runtime configuration changed') + PROTOCOL = ( '\n\nTools: {"op":"exec","command":""}; ' '{"op":"call","tool":"write_file","arguments":{"file_path":"","content":""}}; ' '{"op":"call","tool":"evaluate","arguments":{}}. ' - 'Use {"op":"finish"} to grade the current artifact and finish. ' - 'Every terminal action uses the original grader. There are at most 32 actions.' + 'Use {"op":"finish"} to grade the artifact and finish. There are at most 32 actions.' ) class CompatEnvironment(Environment): - # Original roots and nobody-process cleanup require one episode per container. SUPPORTS_CONCURRENT_SESSIONS = False - def __init__(self, allow_seed=False): + def __init__(self): super().__init__() + if os.geteuid() != 0 or not shell.IS_ROOT or shell.NOBODY != 65534: + raise RuntimeError('The server must run as root with the original nobody tool identity') self._lock = RLock() - self._original = TerminalDeskEnvironment(allow_seed=allow_seed) + self._original = TerminalDeskEnvironment(allow_seed=False) self._task_id = None self._actions = 0 self._terminal = None @@ -47,6 +64,8 @@ class CompatEnvironment(Environment): with self._lock: if split != 'train': raise ValueError('Unknown split') + if kwargs.get('allow_seed') not in (None, False): + raise ValueError('Production instance override is unavailable') if index is not None: if type(index) is not int or not 0 <= index < len(TASK_IDS): raise ValueError('Invalid task index') @@ -54,12 +73,18 @@ class CompatEnvironment(Environment): raise ValueError('Task selection mismatch') task_id = TASK_IDS[index] if task_id is None: - raise ValueError('reset needs task_id or an explicit task index') - if task_id not in TASK_IDS or (seed is not None and type(seed) is not int): - raise ValueError('Invalid task or seed') + raise ValueError('reset needs task_id or task index') + if not isinstance(task_id, str) or task_id not in TASK_IDS: + raise ValueError('Unknown task') + if seed is not None and type(seed) is not int: + raise ValueError('Invalid seed') + parse_task_id(task_id) + if is_reserved(task_id): + raise ValueError('Unknown task') self._task_id = None self._actions = 0 self._terminal = None + # The original fixed-instance environment ignores client seeds in production. opening = self._original.reset(task_id=task_id, seed=seed, episode_id=episode_id) self._task_id = task_id return self._translate(opening, reset=True) @@ -67,26 +92,22 @@ class CompatEnvironment(Environment): def _translate(self, original, reset=False): if original.done: reward = original.reward - if isinstance(reward, bool) or not isinstance(reward, (int, float)) or not math.isfinite(reward) or not 0 <= reward <= 1: - raise RuntimeError('Original terminal evaluation did not return a valid reward') - message = original.instruction + PROTOCOL if reset else original.output - data = { - 'task_path': original.task_path, - 'success': original.success, - 'error': original.error, - 'actions_used': self._actions, - 'steps_left': max(0, MAX_CALLS - self._actions), - 'info': original.info, - } - result = ArenaObservation(task_id=self._task_id, message=message, data=data, - reward=original.reward, done=original.done) + if isinstance(reward, bool) or not isinstance(reward, (int, float)) or not math.isfinite(reward) or reward not in (0, 1): + raise RuntimeError('Native terminal reward is not binary') + result = ArenaObservation( + task_id=self._task_id, + message=original.instruction + PROTOCOL if reset else original.output, + data={'task_path': original.task_path, 'success': original.success, 'error': original.error, + 'actions_used': self._actions, 'steps_left': max(0, MAX_CALLS - self._actions), + 'info': original.info}, + reward=original.reward, done=original.done, + ) if original.done: self._terminal = result.model_copy(deep=True) return result def _finish(self): - original = self._original.step(Tbench2Action(action_type='evaluate')) - return self._translate(original) + return self._translate(self._original.step(Tbench2Action(action_type='evaluate'))) def step(self, action, timeout_s=None, **kwargs): with self._lock: @@ -104,13 +125,12 @@ class CompatEnvironment(Environment): elif value['op'] == 'call': tool, args = value['tool'], value['arguments'] if tool in ('evaluate', 'finish', 'close') and not args: - # Never forward the original close action: it has no reward. return self._finish() - if tool == 'write_file' and set(args) == {'file_path', 'content'} and all(isinstance(args[k], str) for k in args): + if (tool == 'write_file' and set(args) == {'file_path', 'content'} + and all(isinstance(args[key], str) for key in args)): mapped = Tbench2Action(action_type='write_file', **args) original = self._original.step(mapped, timeout_s=timeout_s) if not original.done and self._actions >= MAX_CALLS: - # Execute the last allowed action before grading its resulting artifact. return self._finish() return self._translate(original) @@ -121,16 +141,15 @@ class CompatEnvironment(Environment): def close(self): with self._lock: - # Registry/metadata factories have no episode and must not kill a live - # episode's nobody subprocess during their lifecycle cleanup. + # SDK metadata factories have no episode and must not stop another session's tools. if self._task_id is not None: self._original.close() self._task_id = None self._terminal = None def get_metadata(self): - return EnvironmentMetadata(name='terminal_desk_compat', version='0.0.1', - description='dnakhla Terminal Desk tasks with the shared Arena interface.') + return EnvironmentMetadata(name='skillsdesk_compat', version='1.0.0', + description='Original Skills Desk tasks with the shared Arena interface.') def list_splits(self): return ['train'] diff --git a/components/dnakhla/runtime/dnakhla_compat/server.py b/components/skillsdesk/runtime/skillsdesk_compat/server.py similarity index 80% rename from components/dnakhla/runtime/dnakhla_compat/server.py rename to components/skillsdesk/runtime/skillsdesk_compat/server.py index e388729cda7b234b70b648dc890bd79a878a992b..28c0868ebeb1d341521e6615bc59345598d294b1 100644 --- a/components/dnakhla/runtime/dnakhla_compat/server.py +++ b/components/skillsdesk/runtime/skillsdesk_compat/server.py @@ -3,7 +3,7 @@ from common.models import ArenaAction, ArenaObservation from .environment import CompatEnvironment app = create_app(CompatEnvironment, ArenaAction, ArenaObservation, - env_name='terminal_desk_compat', max_concurrent_envs=1, mode='production') + env_name='skillsdesk_compat', max_concurrent_envs=1, mode='production') def main(): diff --git a/components/dnakhla/upstream/openenv.yaml b/components/skillsdesk/upstream/openenv.yaml similarity index 56% rename from components/dnakhla/upstream/openenv.yaml rename to components/skillsdesk/upstream/openenv.yaml index 9769259ab1e53502c4bf649e56aff8fc3f4f73c3..af39ddb3932df8bd0290f895e06878d03a194b52 100644 --- a/components/dnakhla/upstream/openenv.yaml +++ b/components/skillsdesk/upstream/openenv.yaml @@ -1,6 +1,6 @@ spec_version: 1 -name: terminal_desk -version: 3.0.0 +name: skills_desk +version: 1.0.0 type: space runtime: fastapi app: terminal_desk.server.app:app @@ -20,11 +20,4 @@ validation: kind: reward_channel types: tags: - - software-engineering - - industrial-physical-systems - - natural-science - - office-white-collar - - finance-economics - - mathematics-or-formal-reasoning - - cybersecurity - - media-content-production + - tool-use diff --git a/components/dnakhla/upstream/terminal_desk/core/__init__.py b/components/skillsdesk/upstream/terminal_desk/__init__.py similarity index 100% rename from components/dnakhla/upstream/terminal_desk/core/__init__.py rename to components/skillsdesk/upstream/terminal_desk/__init__.py diff --git a/components/dnakhla/upstream/terminal_desk/server/__init__.py b/components/skillsdesk/upstream/terminal_desk/core/__init__.py similarity index 100% rename from components/dnakhla/upstream/terminal_desk/server/__init__.py rename to components/skillsdesk/upstream/terminal_desk/core/__init__.py diff --git a/components/dnakhla/upstream/terminal_desk/core/grading.py b/components/skillsdesk/upstream/terminal_desk/core/grading.py similarity index 61% rename from components/dnakhla/upstream/terminal_desk/core/grading.py rename to components/skillsdesk/upstream/terminal_desk/core/grading.py index afef9a11a5b0b0394e6c58954f0be6c283659c6f..528a9f483cde82944f7197ec1c96575aad13fa21 100644 --- a/components/dnakhla/upstream/terminal_desk/core/grading.py +++ b/components/skillsdesk/upstream/terminal_desk/core/grading.py @@ -1,10 +1,7 @@ """Check the one output file a task names. Reward is 1.0 when every check passes, else 0.0. -Checks only parse: no file under the root is executed here. The root is -nobody-writable, so the root process only reads the artifact's bytes behind -read_artifact's lstat guards; xlsx and docx are parsed by a nobody subprocess -that prints a JSON dump (parse_in_sandbox). The sw_fix family runs its hidden -tests itself, as nobody, on a copy (see families/software.py). +Checks only parse: no file under /app is executed here. The sw_fix family runs its +hidden tests itself, as nobody, on a copy (see families/software.py). """ import csv @@ -18,12 +15,8 @@ import wave from typing import Any from ..families.base import Artifact, Built, Field, FileContent -from . import shell MAX_ARTIFACT_BYTES = 4 * 1024**2 -SANDBOX_PARSES = ("xlsx", "docx") -LOCAL_PARSES = ("json", "csv", "text", "lines", "srt") -_DUMP_MARK = "@@TD_DUMP@@" def _norm_text(value: Any) -> str: @@ -77,7 +70,7 @@ def score_field(field: Field, value: Any, expected: Any) -> float: def read_artifact(app: str, path: str) -> bytes | None: """The file's bytes, or None when it is missing, a symlink, not a regular file, - outside the root dir `app` or over MAX_ARTIFACT_BYTES. lstat first so a FIFO or a link + outside the app dir or over MAX_ARTIFACT_BYTES. lstat first so a FIFO or a link planted at the path cannot hang or redirect the root-owned reader.""" app_real = os.path.realpath(app) full = os.path.join(app_real, path) @@ -116,16 +109,11 @@ def compare_json(artifact: Artifact, data: bytes) -> bool: def _csv_rows(text: str) -> tuple[list[str], list[dict]]: - reader = csv.DictReader(io.StringIO(text)) - rows = [] - for row in reader: - # DictReader keeps extra cells as a list under None and fills missing cells with None; either is a - # malformed answer, so it is a parse failure (reward 0), never an exception out of the grader. - if None in row or any(v is None for v in row.values()): - raise ValueError("ragged csv row: cell count differs from the header") - rows.append({k.strip(): v.strip() for k, v in row.items()}) - header = [h.strip() for h in (reader.fieldnames or [])] - return header, rows + """Strict: a row with extra or missing fields makes the whole file fail (empty header).""" + from ..families.util import parse_csv_strict + + parsed = parse_csv_strict(text) + return parsed if parsed is not None else ([], []) def compare_csv(artifact: Artifact, data: bytes) -> bool: @@ -219,109 +207,6 @@ def compare_wav(artifact: Artifact, data: bytes) -> bool: return got.readframes(got.getnframes()) == want.readframes(want.getnframes()) -# The nobody parser for zip containers. It runs with python3 -I, so neither the -# root nor HOME is on sys.path, and prints one marked JSON line. -_SANDBOX_PARSER = r""" -import datetime, json, sys -kind, path = sys.argv[1], sys.argv[2] -def cell(v): - if isinstance(v, (datetime.datetime, datetime.date, datetime.time)): - return v.isoformat() - if isinstance(v, datetime.timedelta): - return v.total_seconds() - if v is None or isinstance(v, (bool, int, float, str)): - return v - return str(v) -if kind == "xlsx": - import openpyxl - values = openpyxl.load_workbook(path, data_only=True, read_only=True) - formulas = openpyxl.load_workbook(path, data_only=False, read_only=True) - out = {"sheets": {}, "formulas": {}} - for ws in values.worksheets: - out["sheets"][ws.title] = [[cell(v) for v in row] for row in ws.iter_rows(values_only=True)] - for ws in formulas.worksheets: - out["formulas"][ws.title] = {c.coordinate: c.value for row in ws.iter_rows() for c in row - if isinstance(c.value, str) and c.value.startswith("=")} -elif kind == "docx": - import docx - d = docx.Document(path) - out = {"paragraphs": [p.text for p in d.paragraphs], - "styles": [p.style.name if p.style is not None else "" for p in d.paragraphs], - "tables": [[[c.text for c in row.cells] for row in t.rows] for t in d.tables]} -else: - raise SystemExit("unknown kind " + kind) -print("@@TD_DUMP@@" + json.dumps(out)) -""" - - -def parse_in_sandbox(root: str, path: str, kind: str) -> Any: - """Parse an xlsx or docx file under root as nobody; return its JSON dump. - xlsx -> {"sheets": {title: [[value, ...], ...]}, "formulas": {title: {"B2": "=SUM(...)"}}} - (values are the cached ones, data_only=True); docx -> {"paragraphs": [str], "styles": [str], - "tables": [[[cell text]]]}. Raises ValueError when the parser fails or prints no dump.""" - if kind not in SANDBOX_PARSES: - raise ValueError(f"no sandbox parser for {kind!r}") - if read_artifact(root, path) is None: - raise ValueError(f"{path} is not a readable regular file under the root") - shell.kill_nobody() - code, text = shell.run(["python3", "-I", "-c", _SANDBOX_PARSER, kind, path], root) - dumps = [ln for ln in text.splitlines() if ln.startswith(_DUMP_MARK)] - if code != 0 or len(dumps) != 1: - raise ValueError(f"{kind} parse failed (exit {code}): {text[-300:]}") - out = json.loads(dumps[0][len(_DUMP_MARK):]) - want = ("sheets", "formulas") if kind == "xlsx" else ("paragraphs", "styles", "tables") - if not isinstance(out, dict) or tuple(sorted(out)) != tuple(sorted(want)): - raise ValueError(f"{kind} dump has keys {sorted(out) if isinstance(out, dict) else type(out)}") - return out - - -def parse_artifact(parse: str, data: bytes) -> Any: - """The in-process parses for kind="checks". json -> the loaded value; csv -> - {"header": [str], "rows": [{column: str}]} (cells and names stripped); text -> str - (utf-8, BOM and CRLF removed); lines -> non-empty lines, stripped; srt -> [(start_ms, end_ms, text)].""" - text = _text(data) - if parse == "json": - return json.loads(text) - if parse == "csv": - header, rows = _csv_rows(text) - return {"header": header, "rows": rows} - if parse == "text": - return text - if parse == "lines": - return [ln.strip() for ln in text.split("\n") if ln.strip()] - if parse == "srt": - return parse_srt(text) - raise ValueError(f"unknown parse {parse!r}") - - -def run_checks(root: str, artifact: Artifact) -> dict[str, bool]: - """kind="checks": test_file_exists, then every named check in order on the parsed file. - A parse failure fails every check; a check that raises fails.""" - names = [name for name, _ in artifact.checks] - if not names or len(set(names)) != len(names) or "test_file_exists" in names: - raise ValueError(f"checks need unique names other than test_file_exists: {names}") - if artifact.parse not in LOCAL_PARSES + SANDBOX_PARSES: - raise ValueError(f"unknown parse {artifact.parse!r}") - data = read_artifact(root, artifact.path) - results = {"test_file_exists": data is not None} - parsed, ok = None, False - if data is not None: - try: - if artifact.parse in SANDBOX_PARSES: - parsed = parse_in_sandbox(root, artifact.path, artifact.parse) - else: - parsed = parse_artifact(artifact.parse, data) - ok = True - except (ValueError, UnicodeError, csv.Error, RecursionError): - ok = False - for name, fn in artifact.checks: - try: - results[name] = ok and fn(parsed) is True - except Exception: - results[name] = False - return results - - COMPARERS = { "json": compare_json, "csv": compare_csv, @@ -341,9 +226,7 @@ def verify(app: str, built: Built) -> tuple[float, dict[str, bool], str]: artifact = built.artifact stem = _stem(artifact.path) results: dict[str, bool] = {} - if artifact.kind == "checks": - results = run_checks(app, artifact) - elif artifact.kind == "custom": + if artifact.kind == "custom": exists = read_artifact(app, artifact.path) is not None if artifact.path else True results[f"test_{stem}_exists"] = exists try: @@ -360,10 +243,7 @@ def verify(app: str, built: Built) -> tuple[float, dict[str, bool], str]: passed = sum(results.values()) failed = len(results) - passed elapsed = f"{time.time() - started:.2f}s" - if artifact.kind == "checks": - lines = [f"{'PASSED' if ok else 'FAILED'} tests/test_outputs.py::{name}" for name, ok in results.items()] - else: - lines = [f"FAILED tests/test_outputs.py::{name}" for name, ok in results.items() if not ok] + lines = [f"FAILED tests/test_outputs.py::{name}" for name, ok in results.items() if not ok] summary = f"{failed} failed, {passed} passed in {elapsed}" if failed else f"{passed} passed in {elapsed}" return (1.0 if not failed else 0.0), results, "\n".join(lines + [summary]) diff --git a/components/dnakhla/upstream/terminal_desk/core/shell.py b/components/skillsdesk/upstream/terminal_desk/core/shell.py similarity index 93% rename from components/dnakhla/upstream/terminal_desk/core/shell.py rename to components/skillsdesk/upstream/terminal_desk/core/shell.py index 298b1aa20b759ddc9e482dc01767640785aa2854..77a2083dcbfd59993817396f9a4e5d1fafadf310 100644 --- a/components/dnakhla/upstream/terminal_desk/core/shell.py +++ b/components/skillsdesk/upstream/terminal_desk/core/shell.py @@ -11,7 +11,6 @@ import os import resource import signal import subprocess -import sys import tempfile import time @@ -26,9 +25,6 @@ MAX_OUTPUT_CHARS = 60000 NOBODY = 65534 IS_ROOT = os.geteuid() == 0 -# The server's own interpreter comes first: /usr/local/bin in the image (a no-op), the -# checkout's venv in tests, so agent commands and the xlsx/docx parser see the task libraries. -PATH = ":".join(dict.fromkeys([os.path.dirname(sys.executable), "/usr/local/bin", "/usr/bin", "/bin"])) def _limits() -> None: @@ -84,7 +80,7 @@ def cut(text: str, limit: int = MAX_OUTPUT_CHARS) -> str: def run(argv: list[str], cwd: str, stdin_text: str | None = None) -> tuple[int, str]: """Run argv as nobody in cwd. Returns (exit code, combined output, uncut).""" env = { - "PATH": PATH, + "PATH": "/usr/local/bin:/usr/bin:/bin", "HOME": cwd, "LANG": "C.UTF-8", "TERM": "dumb", diff --git a/components/skillsdesk/upstream/terminal_desk/families/__init__.py b/components/skillsdesk/upstream/terminal_desk/families/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f1a07aadb92efc8d546ca1219c99ddd010511f94 --- /dev/null +++ b/components/skillsdesk/upstream/terminal_desk/families/__init__.py @@ -0,0 +1,61 @@ +"""Registry of task families. A task id is '-L' or '-L-i', +e.g. 'ev_backorder-L1' or 'ev_backorder-L1-i3'. Each task id is one fixed problem (see instance_seed).""" + +import hashlib + +from . import compute, compute2, constraints, constraints2, evidence, evidence2, repair, repair2, transform, transform2 +from .base import Family + +FAMILIES: dict[str, Family] = { + f.id: f + for module in (evidence, compute, transform, repair, constraints, + evidence2, compute2, transform2, repair2, constraints2) + for f in module.FAMILIES +} + +# Changing the salt changes every fixed instance; bump it only with a new release. +INSTANCE_SALT = "skills-desk-pilot" + + +def parse_task_id(task_id: str) -> tuple[str, int, int]: + """(family id, level, instance). The instance defaults to 0.""" + base, instance = task_id, 0 + head, sep, tail = task_id.rpartition("-i") + if sep and tail.isdigit(): + base, instance = head, int(tail) + family_id, _, level = base.rpartition("-L") + if family_id not in ALL_FAMILIES or not level.isdigit() or int(level) not in ALL_FAMILIES[family_id].levels: + raise ValueError(f"unknown task_id {task_id!r}") + return family_id, int(level), instance + + +def instance_seed(task_id: str) -> int: + """The fixed seed of a task id: every reset of the same id builds the same problem, so a GRPO + group compares answers to one question rather than to different questions.""" + family_id, level, instance = parse_task_id(task_id) + salt = RESERVED_SALT if family_id in RESERVED else INSTANCE_SALT + key = f"{salt}:{family_id}-L{level}-i{instance}".encode() + return int.from_bytes(hashlib.sha256(key).digest()[:8], "big") + + +def all_task_ids() -> list[str]: + """Training task ids only. Reserved evaluation tasks are listed by reserved_task_ids().""" + return [f"{fid}-L{lv}" for fid, fam in FAMILIES.items() for lv in fam.levels] + + +def reserved_task_ids() -> list[str]: + return [f"{fid}-L{lv}" for fid, fam in RESERVED.items() for lv in fam.levels] + + +def is_reserved(task_id: str) -> bool: + return parse_task_id(task_id)[0] in RESERVED + + +# Reserved evaluation tasks: served by the same environment so a checkpoint can be evaluated on +# them, but never part of a training task list or of difficulty-based selection (see +# tools/make_submission.py). Their own salt keeps their instances independent of training ids. +from ..reserved import RESERVED # noqa: E402 + +RESERVED_SALT = "skills-desk-reserved-v1" +ALL_FAMILIES: dict[str, Family] = {**FAMILIES, **RESERVED} +assert not set(FAMILIES) & set(RESERVED) diff --git a/components/dnakhla/upstream/terminal_desk/families/base.py b/components/skillsdesk/upstream/terminal_desk/families/base.py similarity index 60% rename from components/dnakhla/upstream/terminal_desk/families/base.py rename to components/skillsdesk/upstream/terminal_desk/families/base.py index 537e5cc087d950611f57ada4c2405c1d36786e86..397007ad2bc27a44e7ff6f7766280967e5765125 100644 --- a/components/dnakhla/upstream/terminal_desk/families/base.py +++ b/components/skillsdesk/upstream/terminal_desk/families/base.py @@ -2,8 +2,7 @@ A family builds one instance per reset from a random generator: the task instruction, the workspace files and the one output file the verifier checks. -The expected content stays in server memory; only the input files reach the -family's root (/app for v2 families, /root or /app for v3 families). +The expected content stays in server memory; only the input files reach /app. """ import random @@ -28,18 +27,13 @@ class Field: class Artifact: """The file the agent must produce, and how it is checked (all or nothing). - path: relative to the family root (Built.root), e.g. "output/schedule.csv". - kind: json | csv | lines | srt | wav | custom | checks. + path: relative to /app, e.g. "report/schedule.csv". + kind: json | csv | lines | srt | wav | custom. expected: json -> dict; csv -> list of row dicts; lines -> list of str; srt -> list of (start_ms, end_ms, text); wav -> bytes; custom -> unused. fields: json/csv comparers per key or column (reuse Field tolerances). key: csv key column(s); rows are matched by key. ordered: csv/lines keep order. - verify: custom check, root dir -> bool. render: oracle content for wav/custom/checks. - - kind="checks" (v3): the grader reads the file, parses it as `parse` - (json | csv | text | lines | srt | xlsx | docx, see grading.parse_artifact) - and runs `checks`, a list of (name, fn(parsed) -> bool), in order after the - implicit test_file_exists. A check that raises fails. Names start with test_. + verify: custom check, app dir -> bool. render: oracle content for wav/custom. """ path: str @@ -51,17 +45,14 @@ class Artifact: tol_ms: int = 1 verify: Callable[[str], bool] | None = None render: Callable[[], FileContent] | None = None - parse: str = "json" - checks: list = field(default_factory=list) @dataclass class Built: - instruction: str # names the output by absolute path under root; v2 <= 700 chars, v3 600-1,000 - files: dict[str, FileContent] # keys relative to root + instruction: str # TB2 style, at most 700 characters; names the output path under /app + files: dict[str, FileContent] artifact: Artifact notes: dict = field(default_factory=dict) - root: str = "/app" # the episode workspace: "/app" or "/root"; fixed per family @dataclass @@ -71,7 +62,6 @@ class Family: title: str build: Callable[[int, random.Random], Built] levels: tuple = (1, 2, 3) - v3: bool = False # v3 bands in tools/check_family.py and an oracle script in terminal_desk/oracles/ def money(x: float) -> str: diff --git a/components/skillsdesk/upstream/terminal_desk/families/compute.py b/components/skillsdesk/upstream/terminal_desk/families/compute.py new file mode 100644 index 0000000000000000000000000000000000000000..5ca9e1f13a9be33c026af487476781860fc86b35 --- /dev/null +++ b/components/skillsdesk/upstream/terminal_desk/families/compute.py @@ -0,0 +1,231 @@ +"""Compute from data: grouped statistics, weighted means, unit conversions, stated rounding.""" + +import random + +from .base import Artifact, Built, Family +from .util import load_csv, to_csv + + +def _num(text: str) -> float | None: + try: + return float(text.replace(",", "")) + except ValueError: + return None + + +def _check_table(app, path, header, want: dict, tols: dict) -> bool: + """want: key (first column) -> {column: number}. Every key once, numbers within tolerance.""" + got = load_csv(app, path) + if got is None or got[0] != header: + return False + seen = {} + for row in got[1]: + key = row.get(header[0], "") + if key in seen: + return False + seen[key] = row + if set(seen) != set(want): + return False + for key, cols in want.items(): + for col, value in cols.items(): + n = _num(seen[key].get(col, "")) + if n is None or abs(n - value) > tols[col] + 1e-9: + return False + return True + + +# ---------------------------------------------------------------- cmp_channels (media) + +CHANNELS = ["field-notes", "studio-live", "kitchen-lab", "night-shift", "map-room"] + + +def _clock(seconds: int) -> str: + h, rem = divmod(seconds, 3600) + m, s = divmod(rem, 60) + return f"{h}:{m:02d}:{s:02d}" if h else f"{m:02d}:{s:02d}" + + +def build_channels(level: int, rng: random.Random) -> Built: + chans = rng.sample(CHANNELS, 3) + rows = [] + for i in range(13): + ch = chans[i % 3] + secs = rng.randint(4 * 60, 95 * 60) + views = rng.randint(800, 60000) + rows.append([f"V{rng.randint(10000, 99999)}", ch, secs, views]) + for r in rng.sample(rows, 2): + r[3] = None # views not reported yet + rng.shuffle(rows) + want = {} + for ch in chans: + mine = [r for r in rows if r[1] == ch] + total_h = round(sum(r[2] for r in mine) / 3600, 2) + counted = [r for r in mine if r[3] is not None] + wm = round(sum(r[2] / 60 * r[3] for r in counted) / sum(r[3] for r in counted), 2) + want[ch] = {"total_hours": total_h, "weighted_minutes": wm} + files = {"videos.csv": to_csv(["video_id", "channel", "duration", "views"], + [[r[0], r[1], _clock(r[2]), "" if r[3] is None else f"{r[3]:,}"] for r in rows])} + header = ["channel", "total_hours", "weighted_minutes"] + + def verify(app: str) -> bool: + return _check_table(app, "channel_stats.csv", header, want, {"total_hours": 0.011, "weighted_minutes": 0.011}) + + instruction = ( + "Summarise /app/videos.csv per channel. duration is H:MM:SS or MM:SS; views may use thousands " + "separators and is blank when not yet reported. Write /app/channel_stats.csv with header " + "channel,total_hours,weighted_minutes and one row per channel: total_hours is the summed duration of all " + "the channel's videos in hours, weighted_minutes is the view-weighted mean duration in minutes over the " + "videos that have views. Round both to 2 decimals." + ) + oracle = to_csv(header, [[c, f"{v['total_hours']:.2f}", f"{v['weighted_minutes']:.2f}"] for c, v in want.items()]) + return Built(instruction=instruction, files=files, + artifact=Artifact(path="channel_stats.csv", kind="custom", verify=verify, render=lambda: oracle), + notes={"expected": want}) + + +# ---------------------------------------------------------------- cmp_rainfall (science, units) + +TO_MM = {"mm": 1.0, "cm": 10.0, "in": 25.4} +STATIONS = ["ridge", "harbor", "orchard", "quarry", "delta"] + + +def _rain_summary(stations, latest, scale_on=None, rejected=frozenset()): + """latest: (station, date) -> mm. scale_on(station, date) -> multiplier. None if a station + has no wet day.""" + want = {} + for st in stations: + vals = [v * (scale_on(s, d) if scale_on else 1.0) for (s, d), v in latest.items() + if s == st and (s, d) not in rejected] + wet = [v for v in vals if v > 0] + if not wet: + return None + total = sum(vals) + want[st] = {"total_mm": round(total, 1), "wet_days": len(wet), "mean_mm_per_wet_day": round(total / len(wet), 2), + "exact_total": total} + return want + + +def _rain_check(app: str, header, want) -> bool: + """Totals within half a unit of the exact value (either rounding of an exact half passes); the + mean may be computed from the exact or the rounded total.""" + got = load_csv(app, "rainfall.csv") + if got is None or got[0] != header or len(got[1]) != len(want): + return False + seen = set() + for row in got[1]: + w = want.get(row["station"]) + try: + total, wet, mean = float(row["total_mm"]), float(row["wet_days"]), float(row["mean_mm_per_wet_day"]) + except ValueError: + return False + if w is None or row["station"] in seen or wet != w["wet_days"]: + return False + exact = w["exact_total"] + if abs(total - exact) > 0.05 + 1e-6 or abs(mean - exact / wet) > 0.005 + 0.05 / wet + 1e-6: + return False + seen.add(row["station"]) + return seen == set(want) + + +def _rain_differs(a, b) -> bool: + return any(abs(a[s]["total_mm"] - b[s]["total_mm"]) > 0.051 or a[s]["wet_days"] != b[s]["wet_days"] + or abs(a[s]["mean_mm_per_wet_day"] - b[s]["mean_mm_per_wet_day"]) > 0.011 for s in a) + + +def build_rainfall(level: int, rng: random.Random) -> Built: + """L1: unit conversion and corrections. L2 adds a gauge replaced mid-week (a new calibration + scale from its install date) and QC decisions that reject some days' readings.""" + while True: + stations = rng.sample(STATIONS, 3) + rows = [] + for st in stations: + for day in range(1, 8): + if rng.random() < 0.35: + mm = 0.0 + else: + mm = rng.uniform(0.4, 30) + unit = rng.choice(["mm", "mm", "cm", "in"]) + amount = round(mm / TO_MM[unit], 2) + rows.append([st, f"2026-04-{day:02d}", amount, unit]) + rng.shuffle(rows) + # Corrections: a later row for the same station and date replaces the earlier one. + for r in rng.sample(rows, 3): + unit = rng.choice(["mm", "cm", "in"]) + rows.append([r[0], r[1], round(rng.uniform(0.0, 25) / TO_MM[unit], 2), unit]) + latest = {} + for r in rows: + latest[(r[0], r[1])] = r[2] * TO_MM[r[3]] + if level == 1: + want = _rain_summary(stations, latest) + if want is not None: + break + continue + # L2: replacement gauges and QC rejections, drawn after the L1 draws. + replaced = rng.sample(stations, rng.randint(1, 2)) + gauges = [[st, "2026-04-01", "1.00"] for st in stations] + installs = {} + for st in replaced: + day = f"2026-04-{rng.randint(3, 6):02d}" + scale = rng.choice([0.88, 0.92, 1.06, 1.12]) + installs[st] = (day, scale) + gauges.append([st, day, f"{scale:.2f}"]) + rng.shuffle(gauges) + wet_keys = [k for k, v in latest.items() if v > 0] + rejected = set(map(tuple, rng.sample(wet_keys, 2))) + kept = [k for k in latest if k not in rejected] + qc = [[s, d, "reject"] for s, d in sorted(rejected)] + [[s, d, "ok"] for s, d in rng.sample(kept, 2)] # sorted: set order varies by process + rng.shuffle(qc) + + def scale_on(st, date, installs=installs): + return installs[st][1] if st in installs and date >= installs[st][0] else 1.0 + + def scale_all(st, date, installs=installs): + return installs[st][1] if st in installs else 1.0 + + want = _rain_summary(stations, latest, scale_on, rejected) + naive = [_rain_summary(stations, latest, None, rejected), _rain_summary(stations, latest, scale_on), + _rain_summary(stations, latest, scale_all, rejected)] + if want is not None and all(n is not None and _rain_differs(n, want) for n in naive): + break + files = {"readings.csv": to_csv(["station", "date", "amount", "unit"], [[r[0], r[1], f"{r[2]:g}", r[3]] for r in rows])} + header = ["station", "total_mm", "wet_days", "mean_mm_per_wet_day"] + + def verify(app: str) -> bool: + return _rain_check(app, header, want) + + if level == 1: + instruction = ( + "Gauge readings for one week are in /app/readings.csv (units mm, cm or in; 1 in = 25.4 mm). When a " + "station has more than one row for a date, the later row in the file is a correction and replaces the " + "earlier ones. Write /app/rainfall.csv with header station,total_mm,wet_days,mean_mm_per_wet_day and " + "one row per station: weekly total in mm (1 decimal), days with rain above 0 mm, and total divided by " + "wet days (2 decimals)." + ) + else: + files["gauges.csv"] = to_csv(["station", "installed", "scale"], gauges) + files["qc.csv"] = to_csv(["station", "date", "decision"], qc) + files["METHOD.md"] = ( + "# Weekly rainfall method\n\n" + "1. Convert every reading to mm (1 cm = 10 mm, 1 in = 25.4 mm).\n" + "2. If a station has several rows for one date, the last row in the file is a correction and replaces the rest.\n" + "3. Multiply each day's reading by the scale of the station's gauge in service that day: the gauges.csv\n" + " row with the latest `installed` date on or before it.\n" + "4. A day whose decision in qc.csv is `reject` has no valid reading: leave it out of the total and the wet days.\n" + ) + instruction = ( + "Compute weekly rainfall per station from /app/readings.csv, /app/gauges.csv and /app/qc.csv following " + "/app/METHOD.md. Write /app/rainfall.csv with header station,total_mm,wet_days,mean_mm_per_wet_day and " + "one row per station: total in mm (1 decimal), days with a valid reading above 0 mm, and total divided " + "by those wet days (2 decimals)." + ) + oracle = to_csv(header, [[s, f"{v['total_mm']:.1f}", v["wet_days"], f"{v['mean_mm_per_wet_day']:.2f}"] + for s, v in want.items()]) + return Built(instruction=instruction, files=files, + artifact=Artifact(path="rainfall.csv", kind="custom", verify=verify, render=lambda: oracle), + notes={"expected": want}) + + +FAMILIES = [ + Family("cmp_channels", "media", "Per-channel runtime and view-weighted duration", build_channels, (1,)), + Family("cmp_rainfall", "science", "Weekly rainfall with unit conversion and corrections", build_rainfall, (1, 2)), +] diff --git a/components/skillsdesk/upstream/terminal_desk/families/compute2.py b/components/skillsdesk/upstream/terminal_desk/families/compute2.py new file mode 100644 index 0000000000000000000000000000000000000000..642b557da7840a75bcda1c61713bb26d7443b852 --- /dev/null +++ b/components/skillsdesk/upstream/terminal_desk/families/compute2.py @@ -0,0 +1,241 @@ +"""Compute from data, second batch: cumulative meters with a rollover, course grades, FIFO cost, +smoothed sensor exceedances and a loan schedule. Where a task states a rounding rule the grader +holds to it; where it does not, any correct rounding of the exact value passes.""" + +import json +import random +from decimal import ROUND_HALF_UP, Decimal + +from .base import Artifact, Built, Family +from .util import json_equal, load_csv, load_json, to_csv + +# ---------------------------------------------------------------- cmp_meter + +def build_meter(level: int, rng: random.Random) -> Built: + while True: + meters, rows, want = rng.sample(["M-A1", "M-B7", "M-C3", "M-D9"], 2), [], {} + for k, m in enumerate(meters): + reading = rng.randint(97500, 99500) if k == 0 else rng.randint(10000, 80000) # the first meter wraps + daily = {} + for day in range(1, 8): + if day > 1: + daily[day] = rng.randint(120, 900) + reading = (reading + daily[day]) % 100000 + rows.append([m, f"2026-02-{day:02d}T23:59", f"{reading:05d}"]) + peak = max(daily.values()) + want[m] = {"total_kwh": sum(daily.values()), + "peak_day": f"2026-02-{max(daily, key=daily.get):02d}" if list(daily.values()).count(peak) == 1 else None} + wrapped = any(int(a[2]) > int(b[2]) for a, b in zip(rows, rows[1:]) if a[0] == b[0] == meters[0]) + if wrapped and all(w["peak_day"] for w in want.values()): + break + rng.shuffle(rows) + files = {"readings.csv": to_csv(["meter", "read_at", "register_kwh"], rows), + "NOTE.txt": "Registers are 5 digits and wrap from 99999 back to 00000. Each reading is taken at the end of its day.\n"} + + def verify(app: str) -> bool: + return json_equal(load_json(app, "usage.json"), want) + + instruction = ( + "Each meter in /app/readings.csv has one end-of-day register reading per day (see /app/NOTE.txt). A day's " + "usage is that day's reading minus the previous day's, so the first day has no usage. Write /app/usage.json " + "as {meter: {\"total_kwh\": integer, \"peak_day\": \"YYYY-MM-DD\" of the highest daily usage}}." + ) + return Built(instruction=instruction, files=files, + artifact=Artifact(path="usage.json", kind="custom", verify=verify, + render=lambda: json.dumps(want) + "\n"), + notes={"expected": want}) + + +# ---------------------------------------------------------------- cmp_grades + +def build_grades(level: int, rng: random.Random) -> Built: + students = rng.sample(["ana", "ben", "cho", "dev", "eva", "fox", "gil"], 5) + rows, exact = [], {} + for s in students: + quizzes = [rng.randint(40, 100) for _ in range(4)] + hw_scores = [rng.randint(50, 100) for _ in range(3)] + hw_late = [rng.randint(0, 3) if rng.random() < 0.35 else 0 for _ in range(3)] + exam = rng.randint(45, 100) + for i, q in enumerate(quizzes): + rows.append([s, f"quiz{i + 1}", q, 0]) + for i, (h, late) in enumerate(zip(hw_scores, hw_late)): + rows.append([s, f"hw{i + 1}", h, late]) + rows.append([s, "exam", exam, 0]) + q = sum(sorted(quizzes)[1:]) / 3 + hw = sum(max(0, h - 10 * late) for h, late in zip(hw_scores, hw_late)) / 3 + exact[s] = 0.3 * q + 0.3 * hw + 0.4 * exam + rng.shuffle(rows) + files = {"scores.csv": to_csv(["student", "item", "score", "days_late"], rows), + "SYLLABUS.md": ("Final grade = 30% quiz average (drop each student's lowest quiz) + 30% homework average + " + "40% exam. Homework loses 10 points per day late, never below 0. All scores are out of 100.\n")} + header = ["student", "final"] + + def verify(app: str) -> bool: + got = load_csv(app, "finals.csv") + if got is None or got[0] != header or len(got[1]) != len(exact): + return False + try: + seen = {r["student"]: float(r["final"]) for r in got[1]} + except ValueError: + return False + return set(seen) == set(exact) and all(abs(seen[s] - v) <= 0.05 + 1e-6 for s, v in exact.items()) + + instruction = ( + "Compute final grades from /app/scores.csv using the rules in /app/SYLLABUS.md. Write /app/finals.csv with " + "header student,final and one row per student, final rounded to 1 decimal." + ) + oracle = to_csv(header, [[s, f"{v:.1f}"] for s, v in exact.items()]) + return Built(instruction=instruction, files=files, + artifact=Artifact(path="finals.csv", kind="custom", verify=verify, render=lambda: oracle), + notes={"expected": exact}) + + +# ---------------------------------------------------------------- cmp_fifo + +def build_fifo(level: int, rng: random.Random) -> Built: + while True: + events, lots, cogs, spanned = [], [], 0, False + on_hand = 0 + for day in range(1, 13): + if rng.random() < 0.45 or on_hand < 10: + qty, cost = rng.randint(10, 40), rng.randint(300, 900) # cents per unit + events.append([f"2026-03-{day:02d}", "buy", qty, f"{cost / 100:.2f}"]) + lots.append([qty, cost]) + on_hand += qty + else: + qty = rng.randint(5, min(on_hand, 35)) + events.append([f"2026-03-{day:02d}", "sell", qty, ""]) + on_hand -= qty + left = qty + spanned |= qty > lots[0][0] + while left: + take = min(left, lots[0][0]) + cogs += take * lots[0][1] + lots[0][0] -= take + left -= take + if lots[0][0] == 0: + lots.pop(0) + sells = sum(e[1] == "sell" for e in events) + if sells >= 3 and spanned: + break + want = {"cogs": cogs / 100, "units_on_hand": on_hand, "inventory_value": sum(q * c for q, c in lots) / 100} + files = {"movements.csv": to_csv(["date", "type", "qty", "unit_cost"], events)} + + def verify(app: str) -> bool: + got = load_json(app, "fifo.json") + if not isinstance(got, dict) or set(got) != set(want): + return False + return (json_equal(got["units_on_hand"], want["units_on_hand"]) and json_equal(got["cogs"], want["cogs"], 0.005) + and json_equal(got["inventory_value"], want["inventory_value"], 0.005)) + + instruction = ( + "Value the stock movements in /app/movements.csv first-in, first-out: each sale uses up the oldest remaining " + "purchased units first, at their purchase cost. Write /app/fifo.json as {\"cogs\": cost of all units sold, " + "\"units_on_hand\": integer, \"inventory_value\": cost of the units left}, money to 2 decimals." + ) + return Built(instruction=instruction, files=files, + artifact=Artifact(path="fifo.json", kind="custom", verify=verify, + render=lambda: json.dumps(want) + "\n"), + notes={"expected": want}) + + +# ---------------------------------------------------------------- cmp_smooth + +def build_smooth(level: int, rng: random.Random) -> Built: + while True: + sensors = rng.sample(["T1", "T2", "T3", "T4"], 3) + limit = rng.choice([60, 65, 70]) + rows, want = [], {} + for s in sensors: + vals = [round(rng.uniform(limit - 15, limit + 8), 1) for _ in range(12)] + for k in rng.sample(range(1, 11), 2): + vals[k] = round(limit + rng.uniform(20, 40), 1) # single-sample spikes + for i, v in enumerate(vals): + rows.append([s, i, v]) + med = [sorted(vals[i - 1:i + 2])[1] for i in range(1, len(vals) - 1)] + want[s] = sum(m > limit for m in med) + raw = {s: sum(r[2] > limit for r in rows if r[0] == s) for s in sensors} + if any(raw[s] != want[s] for s in sensors) and any(want.values()): + break + rows.sort(key=lambda r: (r[0], r[1])) + files = {"samples.csv": to_csv(["sensor", "seq", "temp_c"], rows), + "METHOD.md": (f"Smooth each sensor with a 3-sample rolling median: for every sample that has a neighbour on " + f"both sides (by seq), take the median of it and its two neighbours. The first and last samples " + f"get no smoothed value. Count smoothed values strictly above {limit} C.\n")} + + def verify(app: str) -> bool: + return json_equal(load_json(app, "exceedances.json"), want) + + instruction = ( + "Count temperature exceedances per sensor in /app/samples.csv after smoothing as described in /app/METHOD.md. " + "Write /app/exceedances.json as {sensor: count}." + ) + return Built(instruction=instruction, files=files, + artifact=Artifact(path="exceedances.json", kind="custom", verify=verify, + render=lambda: json.dumps(want) + "\n"), + notes={"expected": want}) + + +# ---------------------------------------------------------------- cmp_loan + +def _cents(x: Decimal) -> Decimal: + return x.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) + + +def build_loan(level: int, rng: random.Random) -> Built: + principal = Decimal(rng.randint(30, 400) * 100) + annual = Decimal(rng.choice(["4.8", "5.25", "6", "7.2", "3.9"])) + months = rng.choice([6, 9, 12]) + r = annual / Decimal(1200) + payment = _cents(principal * r / (1 - (1 + r) ** -months)) + balance, sched = principal, [] + for m in range(1, months + 1): + interest = _cents(balance * r) + pay = payment if m < months else balance + interest # last payment clears the balance + principal_part = pay - interest + balance -= principal_part + sched.append({"month": m, "payment": str(pay), "interest": str(interest), "balance": str(balance)}) + want = {"monthly_payment": str(payment), "total_interest": str(sum(Decimal(s["interest"]) for s in sched)), "schedule": sched} + files = {"loan.json": json.dumps({"principal": str(principal), "annual_rate_pct": str(annual), "months": months}) + "\n", + "RULES.md": ("Monthly rate = annual_rate_pct / 1200. Payment = principal * r / (1 - (1 + r)^-months), rounded " + "half up to cents. Each month: interest = balance * r rounded half up to cents; balance falls by " + "payment - interest. The final payment is whatever clears the balance (balance + interest), so the " + "last balance is exactly 0.00. Money values are strings with 2 decimals.\n")} + + def verify(app: str) -> bool: + got = load_json(app, "schedule.json") + if not isinstance(got, dict) or set(got) != set(want) or not isinstance(got["schedule"], list): + return False + try: + norm = lambda v: str(Decimal(str(v)).quantize(Decimal("0.01"))) # noqa: E731 + if norm(got["monthly_payment"]) != want["monthly_payment"] or norm(got["total_interest"]) != want["total_interest"]: + return False + if len(got["schedule"]) != months: + return False + for g, w in zip(got["schedule"], sched): + if set(g) != set(w) or int(g["month"]) != w["month"]: + return False + if any(norm(g[k]) != w[k] for k in ("payment", "interest", "balance")): + return False + except (ArithmeticError, ValueError, TypeError): + return False + return True + + instruction = ( + "Build the repayment schedule for the loan in /app/loan.json following /app/RULES.md exactly. Write " + "/app/schedule.json as {\"monthly_payment\": money, \"total_interest\": money, \"schedule\": [{\"month\": n, " + "\"payment\": money, \"interest\": money, \"balance\": money after that payment}, ...]}." + ) + return Built(instruction=instruction, files=files, + artifact=Artifact(path="schedule.json", kind="custom", verify=verify, + render=lambda: json.dumps(want, indent=1) + "\n"), + notes={"expected": want}) + + +FAMILIES = [ + Family("cmp_meter", "industrial", "Daily usage from wrapping meter registers", build_meter, (1,)), + Family("cmp_grades", "office", "Final grades with dropped quiz and late penalty", build_grades, (1,)), + Family("cmp_fifo", "finance", "FIFO cost of goods sold", build_fifo, (1,)), + Family("cmp_smooth", "science", "Exceedances after rolling-median smoothing", build_smooth, (1,)), + Family("cmp_loan", "finance", "Loan schedule with stated half-up rounding", build_loan, (1,)), +] diff --git a/components/skillsdesk/upstream/terminal_desk/families/constraints.py b/components/skillsdesk/upstream/terminal_desk/families/constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..677db7f604f01e9cec34883cbb478ecf7006c27d --- /dev/null +++ b/components/skillsdesk/upstream/terminal_desk/families/constraints.py @@ -0,0 +1,209 @@ +"""Follow several constraints: build a roster or pick a load that satisfies every stated rule. + +Many answers can be correct, so the verifiers check the rules instead of one expected file. +""" + +import itertools +import json +import random + +from .base import Artifact, Built, Family +from .util import load_csv, load_json, to_csv + +# ---------------------------------------------------------------- plan_shifts (scheduling) + +PEOPLE = ["Ada", "Bram", "Cleo", "Dev", "Esme", "Femi", "Gus", "Hana", "Ines", "Jon"] +SKILLS = ["forklift", "first_aid", "cashier"] +DAYS = ["mon", "tue", "wed"] + + +def _solve_roster(shifts, staff, limit_greedy=False): + """Backtracking search; with limit_greedy, take the first eligible people in file order only.""" + load = {p: 0 for p in staff} + days = {p: set() for p in staff} + out = {} + + def ok(p, s): + st = staff[p] + return (s["skill"] in st["skills"] and s["id"] not in st["off"] and load[p] < st["max"] + and s["day"] not in days[p]) + + def place(i): + if i == len(shifts): + return True + s = shifts[i] + cands = [p for p in staff if ok(p, s)] + combos = [tuple(cands[: s["need"]])] if limit_greedy else itertools.combinations(cands, s["need"]) + for combo in combos: + if len(combo) < s["need"]: + continue + for p in combo: + load[p] += 1 + days[p].add(s["day"]) + out[s["id"]] = combo + if place(i + 1): + return True + for p in combo: + load[p] -= 1 + days[p].discard(s["day"]) + del out[s["id"]] + return False + + return dict(out) if place(0) else None + + +def build_shifts(level: int, rng: random.Random) -> Built: + """L1: three days, seven people. L2: the same rules on a smaller week (two days, five people).""" + n_people, days = (7, DAYS) if level == 1 else (5, DAYS[:2]) + for _ in range(500): + names = rng.sample(PEOPLE, n_people) + staff = {p: {"skills": set(rng.sample(SKILLS, rng.randint(1, 2))), "max": 0, "off": set()} for p in names} + shifts = [] + for d in days: + for part in ("early", "late"): + shifts.append({"id": f"{d}-{part}", "day": d, "skill": rng.choice(SKILLS), "need": rng.randint(1, 2)}) + for p in names: + staff[p]["max"] = 3 + plan = _solve_roster(shifts, staff) + if plan is None: + continue + worked = {p: [s for s, ps in plan.items() if p in ps] for p in names} + for p in names: + staff[p]["max"] = max(1, len(worked[p])) + free = [s["id"] for s in shifts if s["id"] not in worked[p]] + staff[p]["off"] = set(rng.sample(free, min(len(free), rng.randint(1, 3)))) + if _solve_roster(shifts, staff) is None or _solve_roster(shifts, staff, limit_greedy=True) is not None: + continue + break + else: + raise RuntimeError("no roster instance") + oracle = _solve_roster(shifts, staff) + files = { + "staff.csv": to_csv(["name", "skills", "max_shifts", "unavailable"], + [[p, ";".join(sorted(s["skills"])), s["max"], ";".join(sorted(s["off"]))] + for p, s in staff.items()]), + "shifts.csv": to_csv(["shift_id", "day", "needs_skill", "headcount"], + [[s["id"], s["day"], s["skill"], s["need"]] for s in shifts]), + "RULES.md": ("# Rostering rules\n\n" + "1. Every shift gets exactly `headcount` different people.\n" + "2. Everyone on a shift has the shift's `needs_skill`.\n" + "3. Nobody works a shift listed in their `unavailable` column.\n" + "4. Nobody works more than `max_shifts` shifts in total.\n" + "5. Nobody works two shifts on the same day.\n"), + } + header = ["shift_id", "staff"] + + def verify(app: str) -> bool: + got = load_csv(app, "roster.csv") + if got is None or got[0] != header: + return False + by_shift = {s["id"]: [] for s in shifts} + for row in got[1]: + sid, person = row.get("shift_id", ""), row.get("staff", "") + if sid not in by_shift or person not in staff: + return False + by_shift[sid].append(person) + load, days = {p: 0 for p in staff}, {p: [] for p in staff} + for s in shifts: + people = by_shift[s["id"]] + if len(people) != s["need"] or len(set(people)) != len(people): + return False + for p in people: + if s["skill"] not in staff[p]["skills"] or s["id"] in staff[p]["off"]: + return False + load[p] += 1 + days[p].append(s["day"]) + return all(load[p] <= staff[p]["max"] and len(days[p]) == len(set(days[p])) for p in staff) + + instruction = ( + "Build next week's roster. People are in /app/staff.csv (skills and unavailable shifts are separated by " + "';'), shifts in /app/shifts.csv, and every rule in /app/RULES.md must hold. Write /app/roster.csv with " + "header shift_id,staff and one row per person per shift. Any roster that satisfies every rule is accepted." + ) + return Built(instruction=instruction, files=files, + artifact=Artifact(path="roster.csv", kind="custom", verify=verify, + render=lambda: to_csv(header, [[s, p] for s, ps in oracle.items() for p in ps])), + notes={"oracle": oracle}) + + +# ---------------------------------------------------------------- plan_load (selection under rules) + +def build_load(level: int, rng: random.Random) -> Built: + while True: + items = [] + for i in range(11): + items.append({"id": f"P-{i + 1:02d}", "kg": rng.randint(2, 38), "value": rng.randint(15, 320), + "hazmat": rng.random() < 0.25, "priority": False}) + for it in rng.sample([x for x in items if not x["hazmat"]], 2): + it["priority"] = True + cap = int(sum(x["kg"] for x in items) * rng.uniform(0.35, 0.45)) + must = [x for x in items if x["priority"]] + base_kg = sum(x["kg"] for x in must) + if base_kg >= cap: + continue + pool = [x for x in items if not x["hazmat"] and not x["priority"]] + best, best_set = -1, None + for r in range(len(pool) + 1): + for combo in itertools.combinations(pool, r): + kg = base_kg + sum(x["kg"] for x in combo) + if kg <= cap: + v = sum(x["value"] for x in combo) + if v > best: + best, best_set = v, combo + # Greedy by value per kg must miss the optimum, so the task needs a real search. + greedy, kg = 0, base_kg + for x in sorted(pool, key=lambda x: -x["value"] / x["kg"]): + if kg + x["kg"] <= cap: + kg += x["kg"] + greedy += x["value"] + if greedy < best: + break + optimum = best + sum(x["value"] for x in must) + chosen = sorted(x["id"] for x in list(must) + list(best_set)) + by_id = {x["id"]: x for x in items} + rows = [[x["id"], x["kg"], x["value"], "yes" if x["hazmat"] else "no", "yes" if x["priority"] else "no"] + for x in items] + rng.shuffle(rows) + files = { + "items.csv": to_csv(["item_id", "weight_kg", "value", "hazmat", "priority"], rows), + "MANIFEST.md": (f"# Flight AX-{rng.randint(100, 999)}\n\nMode: air. Cargo capacity: {cap} kg.\n\n" + "- Hazmat items may not fly.\n- Every priority item must be loaded.\n" + "- Among loads that follow these rules, load the one with the greatest total value.\n"), + } + + def verify(app: str) -> bool: + got = load_json(app, "load.json") + if not isinstance(got, dict) or set(got) != {"items", "total_value", "total_weight_kg"}: + return False + ids = got["items"] + if not isinstance(ids, list) or not all(isinstance(i, str) for i in ids): + return False + if ids != sorted(ids) or len(set(ids)) != len(ids) or not set(ids) <= set(by_id): + return False + picked = [by_id[i] for i in ids] + kg = sum(x["kg"] for x in picked) + value = sum(x["value"] for x in picked) + if any(x["hazmat"] for x in picked) or not all(x["id"] in ids for x in must) or kg > cap: + return False + if value != optimum: + return False + tv, tw = got["total_value"], got["total_weight_kg"] + return (not isinstance(tv, bool) and isinstance(tv, (int, float)) and tv == value + and not isinstance(tw, bool) and isinstance(tw, (int, float)) and tw == kg) + + instruction = ( + "Choose the cargo for the flight described in /app/MANIFEST.md from /app/items.csv. Follow every rule in " + "the manifest. Write /app/load.json as exactly {\"items\": [item ids sorted ascending], \"total_value\": " + "number, \"total_weight_kg\": number} for the chosen load." + ) + oracle = {"items": chosen, "total_value": optimum, "total_weight_kg": sum(by_id[i]["kg"] for i in chosen)} + return Built(instruction=instruction, files=files, + artifact=Artifact(path="load.json", kind="custom", verify=verify, + render=lambda: json.dumps(oracle) + "\n"), + notes={"oracle": oracle, "capacity": cap}) + + +FAMILIES = [ + Family("plan_shifts", "office", "Weekly roster under skill, availability and load rules", build_shifts, (1, 2)), + Family("plan_load", "industrial", "Highest-value cargo under capacity and eligibility rules", build_load, (1,)), +] diff --git a/components/skillsdesk/upstream/terminal_desk/families/constraints2.py b/components/skillsdesk/upstream/terminal_desk/families/constraints2.py new file mode 100644 index 0000000000000000000000000000000000000000..9edbd65687c33ced78950c1af1212668b03f3abd --- /dev/null +++ b/components/skillsdesk/upstream/terminal_desk/families/constraints2.py @@ -0,0 +1,310 @@ +"""Follow several constraints, second batch. Two training-only stepping stones for the roster task +(repair a nearly correct roster; complete a partly assigned one), then course selection, packing +onto the fewest disks and delivery-day planning. Every grader checks the result against the rules; +no tool sequence is required.""" + +import csv +import io +import itertools +import json +import random + +from . import constraints +from .base import Artifact, Built, Family +from .util import load_csv, load_json, to_csv + + + +def _roster_inputs(rng: random.Random): + """Staff, shifts and a valid roster from the plan_shifts generator (three-day week).""" + built = constraints.build_shifts(1, rng) + staff = {r["name"]: {"skills": set(filter(None, r["skills"].split(";"))), "max": int(r["max_shifts"]), + "off": set(filter(None, r["unavailable"].split(";")))} + for r in csv.DictReader(io.StringIO(built.files["staff.csv"]))} + shifts = [{"id": r["shift_id"], "day": r["day"], "skill": r["needs_skill"], "need": int(r["headcount"])} + for r in csv.DictReader(io.StringIO(built.files["shifts.csv"]))] + return built.files, staff, shifts, built.notes["oracle"] + + +def _roster_ok(rows, staff, shifts) -> bool: + by_shift = {s["id"]: [] for s in shifts} + for sid, person in rows: + if sid not in by_shift or person not in staff: + return False + by_shift[sid].append(person) + load, days = {p: 0 for p in staff}, {p: [] for p in staff} + for s in shifts: + people = by_shift[s["id"]] + if len(people) != s["need"] or len(set(people)) != len(people): + return False + for p in people: + if s["skill"] not in staff[p]["skills"] or s["id"] in staff[p]["off"]: + return False + load[p] += 1 + days[p].append(s["day"]) + return all(load[p] <= staff[p]["max"] and len(days[p]) == len(set(days[p])) for p in staff) + + +def _violations(rows, staff, shifts) -> int: + """How many single rows break a per-row rule (skill, availability).""" + skill = {s["id"]: s["skill"] for s in shifts} + return sum(1 for sid, p in rows if skill[sid] not in staff[p]["skills"] or sid in staff[p]["off"]) + + +HEADER = ["shift_id", "staff"] + + +def _read_roster(app: str): + got = load_csv(app, "roster.csv") + if got is None or got[0] != HEADER: + return None + return [(r["shift_id"], r["staff"]) for r in got[1]] + + +# ---------------------------------------------------------------- plan_roster_fix (stepping stone) + +def build_roster_fix(level: int, rng: random.Random) -> Built: + while True: + files, staff, shifts, oracle = _roster_inputs(rng) + rows = [(s, p) for s, ps in oracle.items() for p in ps] + broken = list(rows) + k = rng.randrange(len(broken)) + sid = broken[k][0] + wrong = [p for p in staff if p not in oracle[sid] and + (next(s["skill"] for s in shifts if s["id"] == sid) not in staff[p]["skills"] or sid in staff[p]["off"])] + if not wrong: + continue + broken[k] = (sid, rng.choice(wrong)) + if not _roster_ok(broken, staff, shifts) and _violations(broken, staff, shifts) == 1: + break + files = dict(files) + files["roster.csv"] = to_csv(HEADER, [list(r) for r in broken]) + + def verify(app: str) -> bool: + got = _read_roster(app) + return got is not None and _roster_ok(got, staff, shifts) + + instruction = ( + "/app/roster.csv is a draft roster that breaks the rules in /app/RULES.md somewhere. People are in " + "/app/staff.csv (skills and unavailable shifts separated by ';') and shifts in /app/shifts.csv. Correct " + "/app/roster.csv in place so every rule holds (header shift_id,staff, one row per person per shift). Any " + "valid roster is accepted." + ) + return Built(instruction=instruction, files=files, + artifact=Artifact(path="roster.csv", kind="custom", verify=verify, + render=lambda: to_csv(HEADER, [list(r) for r in rows])), + notes={"oracle": oracle}) + + +# ---------------------------------------------------------------- plan_roster_fill (stepping stone) + +def build_roster_fill(level: int, rng: random.Random) -> Built: + files, staff, shifts, oracle = _roster_inputs(rng) + rows = [(s, p) for s, ps in oracle.items() for p in ps] + fixed = sorted(rng.sample(rows, max(1, len(rows) // 2))) + files = dict(files) + files["assigned.csv"] = to_csv(HEADER, [list(r) for r in fixed]) + + def verify(app: str) -> bool: + got = _read_roster(app) + return got is not None and set(fixed) <= set(got) and _roster_ok(got, staff, shifts) + + instruction = ( + "Finish next week's roster. /app/assigned.csv holds assignments already agreed; keep all of them and fill " + "the rest so every rule in /app/RULES.md holds, using /app/staff.csv (';'-separated skills and unavailable " + "shifts) and /app/shifts.csv. Write the complete roster to /app/roster.csv with header shift_id,staff." + ) + return Built(instruction=instruction, files=files, + artifact=Artifact(path="roster.csv", kind="custom", verify=verify, + render=lambda: to_csv(HEADER, [list(r) for r in rows])), + notes={"oracle": oracle, "fixed": fixed}) + + +# ---------------------------------------------------------------- plan_courses + +SLOTS = ["mon9", "mon11", "tue9", "tue14", "wed10", "thu9", "thu14", "fri11"] + + +def build_courses(level: int, rng: random.Random) -> Built: + while True: + codes = [f"{rng.choice(['MAT', 'BIO', 'CHE', 'PHY', 'STA'])}{rng.randint(100, 399)}" for _ in range(10)] + if len(set(codes)) < 10: + continue + done = set(rng.sample(codes, 3)) + courses = {} + for c in codes: + others = [x for x in codes if x != c] + courses[c] = {"credits": rng.choice([3, 4, 5]), "slot": rng.choice(SLOTS), + "prereq": sorted(rng.sample(others, rng.choice([0, 0, 1]))), "offered": rng.random() < 0.85} + required = [c for c in codes if c not in done and courses[c]["offered"]][:1] + lo, hi = 12, 17 + + def ok(sel): + sel = list(sel) + if any(c in done or not courses[c]["offered"] for c in sel): + return False + if any(not set(courses[c]["prereq"]) <= done for c in sel): + return False + if len({courses[c]["slot"] for c in sel}) != len(sel): + return False + return lo <= sum(courses[c]["credits"] for c in sel) <= hi and set(required) <= set(sel) + + options = [c for c in codes if c not in done] + valid = [sel for r in range(2, 6) for sel in itertools.combinations(options, r) if ok(sel)] + blocked = any(not set(courses[c]["prereq"]) <= done for c in options) + if 1 <= len(valid) <= 12 and blocked: + break + files = {"courses.csv": to_csv(["code", "credits", "slot", "prerequisites", "offered"], + [[c, v["credits"], v["slot"], ";".join(v["prereq"]), "yes" if v["offered"] else "no"] + for c, v in courses.items()]), + "transcript.txt": "Completed:\n" + "\n".join(sorted(done)) + "\n", + "PLAN_RULES.md": (f"- Take every course in required.txt.\n- Only courses offered this term that you have not " + f"completed.\n- Every prerequisite must already be completed (not taken this term).\n- No two " + f"courses in the same slot.\n- Total credits between {lo} and {hi} inclusive.\n"), + "required.txt": "\n".join(required) + "\n"} + + def verify(app: str) -> bool: + got = load_json(app, "plan.json") + if not isinstance(got, dict) or set(got) != {"courses"} or not isinstance(got["courses"], list): + return False + sel = got["courses"] + return all(isinstance(c, str) and c in courses for c in sel) and len(set(sel)) == len(sel) and ok(sel) + + instruction = ( + "Choose this term's courses from /app/courses.csv for a student whose completed courses are in " + "/app/transcript.txt, following every rule in /app/PLAN_RULES.md. Write /app/plan.json as {\"courses\": " + "[codes]}. Any selection that satisfies every rule is accepted." + ) + return Built(instruction=instruction, files=files, + artifact=Artifact(path="plan.json", kind="custom", verify=verify, + render=lambda: json.dumps({"courses": list(valid[0])}) + "\n"), + notes={"valid_selections": len(valid)}) + + +# ---------------------------------------------------------------- plan_disks + +def build_disks(level: int, rng: random.Random) -> Built: + while True: + cap = rng.choice([100, 120, 150]) + files_ = {f"{rng.choice(['raw', 'img', 'log', 'db'])}_{i}.tar": rng.randint(15, cap - 10) for i in range(8)} + names = list(files_) + best = None + for disks in range(1, 6): + for assign in itertools.product(range(disks), repeat=len(names)): + if len(set(assign)) != disks: + continue + load = [0] * disks + for n, d in zip(names, assign): + load[d] += files_[n] + if max(load) <= cap: + best = (disks, assign) + break + if best: + break + greedy, bins = 0, [] + for n in sorted(names, key=lambda n: files_[n]): # smallest first, first fit + for b in bins: + if sum(files_[x] for x in b) + files_[n] <= cap: + b.append(n) + break + else: + bins.append([n]) + if best and len(bins) > best[0]: + break + need, assign = best + oracle = {} + for n, d in zip(names, assign): + oracle.setdefault(f"disk{d + 1}", []).append(n) + files = {"archives.csv": to_csv(["file", "size_gb"], [[n, s] for n, s in files_.items()]), + "README.txt": f"Each backup disk holds {cap} GB. A file cannot be split across disks.\n"} + + def verify(app: str) -> bool: + got = load_json(app, "disks.json") + if not isinstance(got, dict) or len(got) != need: + return False + placed = [] + for disk, items in got.items(): + if not isinstance(items, list) or not items or any(i not in files_ for i in items): + return False + if sum(files_[i] for i in items) > cap: + return False + placed += items + return sorted(placed) == sorted(names) + + instruction = ( + "Pack the archive files in /app/archives.csv onto as few backup disks as possible (capacity in " + "/app/README.txt). Write /app/disks.json as {disk name: [file names]} with one entry per disk used; every " + "file exactly once." + ) + return Built(instruction=instruction, files=files, + artifact=Artifact(path="disks.json", kind="custom", verify=verify, + render=lambda: json.dumps(oracle) + "\n"), + notes={"disks_needed": need}) + + +# ---------------------------------------------------------------- plan_delivery + +DAYS = ["mon", "tue", "wed", "thu", "fri"] + + +def build_delivery(level: int, rng: random.Random) -> Built: + while True: + cap = {d: rng.choice([300, 400, 500]) for d in DAYS} + orders, plan, load = [], {}, {d: 0 for d in DAYS} + for i in range(10): + day = rng.choice(DAYS) + w = rng.randint(40, 180) + if load[day] + w > cap[day]: + continue + load[day] += w + deadline = DAYS[rng.randint(DAYS.index(day), 4)] + closed = sorted(rng.sample([d for d in DAYS if d != day], rng.randint(0, 2))) + oid = f"D{300 + i}" + orders.append({"id": oid, "kg": w, "deadline": deadline, "closed": closed}) + plan[oid] = day + if len(orders) < 8: + continue + # The easy answer (each order on its earliest open day) must overload some day. + early = {d: 0 for d in DAYS} + for o in orders: + first = next(d for d in DAYS if d not in o["closed"]) + early[first] += o["kg"] + if any(early[d] > cap[d] for d in DAYS): + break + files = {"orders.csv": to_csv(["order", "weight_kg", "deliver_by", "customer_closed"], + [[o["id"], o["kg"], o["deadline"], ";".join(o["closed"])] for o in orders]), + "van.json": json.dumps({"capacity_kg_per_day": cap}, indent=1) + "\n"} + by = {o["id"]: o for o in orders} + + def verify(app: str) -> bool: + got = load_csv(app, "delivery_plan.csv") + if got is None or got[0] != ["order", "day"] or len(got[1]) != len(orders): + return False + load_ = {d: 0 for d in DAYS} + seen = set() + for r in got[1]: + o, d = by.get(r["order"]), r["day"] + if o is None or r["order"] in seen or d not in DAYS or d in o["closed"] or DAYS.index(d) > DAYS.index(o["deadline"]): + return False + seen.add(r["order"]) + load_[d] += o["kg"] + return all(load_[d] <= cap[d] for d in DAYS) + + instruction = ( + "Plan this week's deliveries. Each order in /app/orders.csv must go out on one weekday (mon-fri) no later " + "than deliver_by and not on a day its customer is closed (';'-separated); the van's weight limit per day is " + "in /app/van.json. Write /app/delivery_plan.csv with header order,day. Any plan that follows every rule is accepted." + ) + return Built(instruction=instruction, files=files, + artifact=Artifact(path="delivery_plan.csv", kind="custom", verify=verify, + render=lambda: to_csv(["order", "day"], [[k, v] for k, v in plan.items()])), + notes={"oracle": plan}) + + +FAMILIES = [ + Family("plan_roster_fix", "office", "Correct a draft roster that breaks one rule", build_roster_fix, (1,)), + Family("plan_roster_fill", "office", "Complete a partly agreed roster", build_roster_fill, (1,)), + Family("plan_courses", "office", "Course selection under prerequisites, slots and credits", build_courses, (1,)), + Family("plan_disks", "software", "Pack archives onto the fewest disks", build_disks, (1,)), + Family("plan_delivery", "industrial", "Delivery days under deadlines, closures and capacity", build_delivery, (1,)), +] diff --git a/components/skillsdesk/upstream/terminal_desk/families/evidence.py b/components/skillsdesk/upstream/terminal_desk/families/evidence.py new file mode 100644 index 0000000000000000000000000000000000000000..6c71c98d28c0d8aa528a47e2d7b402140d5ee0d0 --- /dev/null +++ b/components/skillsdesk/upstream/terminal_desk/families/evidence.py @@ -0,0 +1,219 @@ +"""Find and combine evidence: read several files, join records by ID, report the exceptions.""" + +import datetime as dt +import json +import random + +from .base import Artifact, Built, Family +from .util import load_csv, load_json, to_csv + +# ---------------------------------------------------------------- ev_backorder (inventory) + +SKUS = ["BOLT-M6", "GASKET-40", "VALVE-12", "HOSE-3M", "CLAMP-20", "SEAL-8"] +WAREHOUSES = ["WH-EAST", "WH-WEST", "WH-NORTH"] + + +def _allocate(orders, stock, cancelled, by_time=True, receipts=(), receipts_at_start=False, aliases=None): + """Backordered order ids. Receipts become available at their arrival time (before an order + placed in the same minute) or, with receipts_at_start, before everything.""" + left = {w: dict(s) for w, s in stock.items()} + aliases = aliases or {} + events = [((("0000" if receipts_at_start else r["arrives"]), 0, ""), "receipt", r) for r in receipts] + seq = sorted(orders, key=lambda o: (o["placed"], o["id"])) if by_time else list(orders) + events += [((o["placed"], 1, o["id"]) if by_time else ("", 1, i), "order", o) for i, o in enumerate(seq)] + if by_time: + events.sort(key=lambda e: e[0]) + else: + events = [e for e in events if e[1] == "receipt"] + [e for e in events if e[1] == "order"] + back = [] + for _, kind, x in events: + if kind == "receipt": + left[x["wh"]][x["sku"]] = left[x["wh"]].get(x["sku"], 0) + x["qty"] + continue + if x["id"] in cancelled: + continue + sku = aliases.get(x["sku"], x["sku"]) + have = left[x["wh"]].get(sku, 0) + if have >= x["qty"]: + left[x["wh"]][sku] = have - x["qty"] + else: + back.append(x["id"]) + return sorted(back) + + +def _stamp(rng): + return f"2026-03-{rng.randint(2, 6):02d} {rng.randint(8, 17):02d}:{rng.choice([0, 15, 30, 45]):02d}" + + +def build_backorder(level: int, rng: random.Random) -> Built: + """L1: orders, stock, cancellations. L2 adds stock receipts that arrive during the week and + orders written with legacy SKU codes that map to current codes.""" + while True: + whs = rng.sample(WAREHOUSES, 2) + skus = rng.sample(SKUS, 4) + stock = {w: {s: rng.randint(4, 14) for s in skus} for w in whs} + legacy = {f"OLD-{s.split('-')[0][:3]}{rng.randint(10, 99)}": s for s in rng.sample(skus, 2)} if level >= 2 else {} + by_new = {v: k for k, v in legacy.items()} + orders = [] + for i in range(14): + # Draw order matches the pilot (L1) exactly; L2's extra draws come after. + o = {"id": f"O-{1001 + i}", "placed": _stamp(rng), "wh": rng.choice(whs), + "sku": rng.choice(skus), "qty": rng.randint(2, 9)} + if level >= 2 and o["sku"] in by_new and rng.random() < 0.6: + o["sku"] = by_new[o["sku"]] + orders.append(o) + rng.shuffle(orders) + cancelled = set(rng.sample([o["id"] for o in orders], 2)) + receipts = [] + if level >= 2: + for _ in range(3): + receipts.append({"wh": rng.choice(whs), "sku": rng.choice(skus), "qty": rng.randint(4, 10), + "arrives": _stamp(rng)}) + want = _allocate(orders, stock, cancelled, receipts=receipts, aliases=legacy) + naive = [ + _allocate(orders, stock, cancelled, by_time=False, receipts=receipts, aliases=legacy), + _allocate(orders, stock, set(), receipts=receipts, aliases=legacy), + ] + if level >= 2: + naive += [ + _allocate(orders, stock, cancelled, aliases=legacy), # ignores receipts + _allocate(orders, stock, cancelled, receipts=receipts, receipts_at_start=True, aliases=legacy), + _allocate(orders, stock, cancelled, receipts=receipts), # ignores legacy codes + ] + if 2 <= len(want) <= (5 if level == 1 else 6) and all(n != want for n in naive): + break + orders_csv = to_csv(["order_id", "placed", "warehouse", "sku", "qty"], + [[o["id"], o["placed"], o["wh"], o["sku"], o["qty"]] for o in orders]) + policy = ( + "# Allocation policy\n\n" + "- Orders are allocated in the order they were placed: earliest `placed` first, ties broken by order_id.\n" + "- Cancelled orders (listed in cancellations.txt) are ignored and take no stock.\n" + "- An order ships only if its warehouse still holds its full quantity of that SKU; there are no partial\n" + " shipments. Otherwise the order is backordered and takes nothing.\n" + "- Stock never moves between warehouses.\n" + ) + files = { + "orders.csv": orders_csv, + "stock.json": json.dumps(stock, indent=1) + "\n", + "cancellations.txt": "\n".join(sorted(cancelled)) + "\n", + } + if level >= 2: + policy += ( + "- Stock in receipts.csv becomes available at its `arrives` time; an order placed in the same minute\n" + " can use it, an earlier order cannot.\n" + "- Some orders still use retired SKU codes; sku_aliases.csv maps each to its current code.\n" + ) + files["receipts.csv"] = to_csv(["warehouse", "sku", "qty", "arrives"], + [[r["wh"], r["sku"], r["qty"], r["arrives"]] for r in receipts]) + files["sku_aliases.csv"] = to_csv(["old_sku", "current_sku"], [[k, v] for k, v in legacy.items()]) + files["POLICY.md"] = policy + + def verify(app: str) -> bool: + got = load_json(app, "backorders.json") + if not isinstance(got, dict) or set(got) != {"backordered"} or not isinstance(got["backordered"], list): + return False + items = got["backordered"] + return all(isinstance(x, str) for x in items) and len(items) == len(set(items)) and sorted(items) == want + + sources = ("opening stock per warehouse in /app/stock.json and cancellations in /app/cancellations.txt" + if level == 1 else + "opening stock in /app/stock.json, deliveries in /app/receipts.csv, cancellations in " + "/app/cancellations.txt and SKU renames in /app/sku_aliases.csv") + instruction = ( + f"Work out which orders are backordered today. The orders are in /app/orders.csv, {sources}; follow " + "the rules in /app/POLICY.md. Write /app/backorders.json as {\"backordered\": [order ids]} listing every " + "backordered order id, sorted ascending, and nothing else." + ) + return Built( + instruction=instruction, + files=files, + artifact=Artifact(path="backorders.json", kind="custom", verify=verify, + render=lambda: json.dumps({"backordered": want}) + "\n"), + notes={"expected": want}, + ) + + +# ---------------------------------------------------------------- ev_calibration (lab) + +def _d(day: int) -> str: + return (dt.date(2026, 1, 1) + dt.timedelta(days=day)).isoformat() + + +def build_calibration(level: int, rng: random.Random) -> Built: + while True: + insts = [f"SPEC-{n:02d}" for n in rng.sample(range(1, 40), 5)] + windows = [] # (inst, from_day, to_day, status) + bare = insts[-1] # never calibrated + for inst in insts[:-1]: + start = rng.randint(0, 20) + for _ in range(rng.randint(1, 2)): + length = rng.randint(25, 45) + windows.append((inst, start, start + length, "active")) + start = start + length + rng.randint(3, 12) + revoked = rng.choice(range(len(windows))) + windows[revoked] = windows[revoked][:3] + ("revoked",) + runs = [] + for i in range(15): + inst = rng.choice(insts) + own = [w for w in windows if w[0] == inst] + pick = rng.random() + if own and pick < 0.25: + w = rng.choice(own) + day = rng.choice([w[1], w[2]]) # boundary day + elif own and pick < 0.45: + w = rng.choice(own) + day = w[2] + rng.randint(1, 3) # just after a window + else: + day = rng.randint(0, 110) + runs.append((f"S-{301 + i}", inst, day)) + + def valid(inst, day): + return any(w[0] == inst and w[3] == "active" and w[1] <= day <= w[2] for w in windows) + + bad = [(s, inst, _d(day)) for s, inst, day in runs if not valid(inst, day)] + boundary_ok = any(valid(inst, day) and any(w[0] == inst and day in (w[1], w[2]) for w in windows) + for _, inst, day in runs) + on_revoked = any(windows[revoked][0] == inst and windows[revoked][1] <= day <= windows[revoked][2] + for _, inst, day in runs) + on_bare = any(inst == bare for _, inst, _ in runs) + if 3 <= len(bad) <= 7 and boundary_ok and on_revoked and on_bare: + break + rng.shuffle(windows) + models = {i: rng.choice(["UV-2600", "FTIR-4100", "NIR-900"]) for i in insts} + files = { + "instruments.csv": to_csv(["instrument_id", "model"], [[i, models[i]] for i in sorted(insts)]), + "calibrations.csv": to_csv(["instrument_id", "valid_from", "valid_to", "status"], + [[w[0], _d(w[1]), _d(w[2]), w[3]] for w in windows]), + "runs.csv": to_csv(["sample_id", "instrument_id", "run_date", "absorbance"], + [[s, inst, _d(day), f"{rng.uniform(0.05, 1.9):.3f}"] for s, inst, day in runs]), + } + header = ["sample_id", "instrument_id", "run_date"] + want = {tuple(r) for r in bad} + + def verify(app: str) -> bool: + got = load_csv(app, "invalid_runs.csv") + if got is None or got[0] != header: + return False + rows = [tuple(r.get(h, "") for h in header) for r in got[1]] + return len(rows) == len(set(rows)) and set(rows) == want + + instruction = ( + "QA needs the sample runs that were measured on an instrument without a valid calibration. Runs are in " + "/app/runs.csv and calibration records in /app/calibrations.csv. A run is valid only when its run_date " + "falls inside an active calibration window of the same instrument (valid_from and valid_to inclusive). " + "Write every invalid run to /app/invalid_runs.csv with header sample_id,instrument_id,run_date (one row " + "per run, any order)." + ) + return Built( + instruction=instruction, + files=files, + artifact=Artifact(path="invalid_runs.csv", kind="custom", verify=verify, + render=lambda: to_csv(header, [list(r) for r in sorted(want)])), + notes={"expected": sorted(want)}, + ) + + +FAMILIES = [ + Family("ev_backorder", "office", "Backordered orders from orders, stock and cancellations", build_backorder, (1, 2)), + Family("ev_calibration", "science", "Runs outside a valid instrument calibration", build_calibration, (1,)), +] diff --git a/components/skillsdesk/upstream/terminal_desk/families/evidence2.py b/components/skillsdesk/upstream/terminal_desk/families/evidence2.py new file mode 100644 index 0000000000000000000000000000000000000000..d2e61a7e0b7009bc70228d65aa7fa358f57cfe14 --- /dev/null +++ b/components/skillsdesk/upstream/terminal_desk/families/evidence2.py @@ -0,0 +1,291 @@ +"""Find and combine evidence, second batch: partial deliveries, badge access with inherited zones, +duplicate customers, bank reconciliation, and the first release that fixed each issue.""" + +import json +import random + +from .base import Artifact, Built, Family +from .util import json_equal, load_csv, load_json, to_csv + +# ---------------------------------------------------------------- ev_deliveries + +def build_deliveries(level: int, rng: random.Random) -> Built: + while True: + pos = {} + for i in range(7): + po = f"PO-{rng.randint(100, 999)}{i}" + pos[po] = {f"PART-{rng.randint(10, 99)}": rng.randint(5, 40) for _ in range(rng.randint(1, 3))} + deliveries, got = [], {po: {p: 0 for p in lines} for po, lines in pos.items()} + for _ in range(14): + po = rng.choice(list(pos)) + part = rng.choice(list(pos[po])) + qty = rng.randint(1, pos[po][part]) + status = rng.choice(["received", "received", "received", "rejected"]) + deliveries.append([f"DN{rng.randint(1000, 9999)}", po.lower() if rng.random() < 0.2 else po, part, qty, status]) + if status == "received": + got[po][part] += qty + want = {} + for po, lines in pos.items(): + short = {p: q - min(q, got[po][p]) for p, q in lines.items() if got[po][p] < q} + if short: + want[po] = dict(sorted(short.items())) + over = any(got[po][p] > q for po, lines in pos.items() for p, q in lines.items()) + if 2 <= len(want) <= 6 and len(want) < len(pos) and not over: + break + po_rows = [[po, p, q] for po, lines in pos.items() for p, q in lines.items()] + rng.shuffle(po_rows) + rng.shuffle(deliveries) + files = {"purchase_orders.csv": to_csv(["po", "part", "qty_ordered"], po_rows), + "delivery_notes.csv": to_csv(["note", "po", "part", "qty", "status"], deliveries)} + + def verify(app: str) -> bool: + return json_equal(load_json(app, "outstanding.json"), want) + + instruction = ( + "Find what is still outstanding on the purchase orders in /app/purchase_orders.csv given the deliveries in " + "/app/delivery_notes.csv (PO numbers may be lower-case; only status received counts). Write " + "/app/outstanding.json as {po: {part: qty still missing}} for every PO with anything missing; leave fully " + "delivered POs and parts out." + ) + return Built(instruction=instruction, files=files, + artifact=Artifact(path="outstanding.json", kind="custom", verify=verify, + render=lambda: json.dumps(want) + "\n"), + notes={"expected": want}) + + +# ---------------------------------------------------------------- ev_badges + +ZONES = ["lobby", "lab", "server", "vault", "roof", "dock"] + + +def build_badges(level: int, rng: random.Random) -> Built: + while True: + zones = rng.sample(ZONES, 5) + roles = {"visitor": {zones[0]}, "staff": {zones[0], zones[1]}, "engineer": {zones[2]}, "security": {zones[3]}} + inherits = {"engineer": "staff", "security": "staff"} + + def allowed(role): + out = set(roles[role]) + while role in inherits: + role = inherits[role] + out |= roles[role] + return out + + people = {f"B{rng.randint(1000, 9999)}": rng.choice(list(roles)) for _ in range(6)} + swipes, bad = [], [] + for i in range(16): + badge = rng.choice(list(people) + ["B0000"]) + zone = rng.choice(zones) + t = f"2026-05-14T{8 + i // 2:02d}:{rng.randint(0, 59):02d}" + swipes.append([t, badge, zone]) + if badge not in people or zone not in allowed(people[badge]): + bad.append([t, badge, zone]) + inherited_ok = any(b in people and inherits.get(people[b]) and z in roles["staff"] and z not in roles[people[b]] + for _, b, z in swipes) + if 3 <= len(bad) <= 8 and inherited_ok: + break + files = {"badges.csv": to_csv(["badge", "role"], [[b, r] for b, r in people.items()]), + "roles.json": json.dumps({"zones": {r: sorted(z) for r, z in roles.items()}, "inherits": inherits}, indent=1) + "\n", + "swipes.csv": to_csv(["time", "badge", "zone"], swipes)} + header = ["time", "badge", "zone"] + want = {tuple(r) for r in bad} + + def verify(app: str) -> bool: + got = load_csv(app, "violations.csv") + if got is None or got[0] != header: + return False + rows = [tuple(r[h] for h in header) for r in got[1]] + return len(rows) == len(set(rows)) and set(rows) == want + + instruction = ( + "List badge swipes into zones the badge holder may not enter. /app/badges.csv maps badges to roles; " + "/app/roles.json gives each role's zones and which role it inherits from (a role may enter its own zones " + "and all zones of the roles it inherits, transitively); unknown badges may enter nothing. Write " + "/app/violations.csv with header time,badge,zone, one row per offending swipe." + ) + return Built(instruction=instruction, files=files, + artifact=Artifact(path="violations.csv", kind="custom", verify=verify, + render=lambda: to_csv(header, [list(r) for r in sorted(want)])), + notes={"expected": sorted(want)}) + + +# ---------------------------------------------------------------- ev_dupes + +FIRST = ["Maria", "John", "Aisha", "Wei", "Pablo", "Sara", "Kofi", "Lena"] +LAST = ["Garcia", "Smith", "Khan", "Zhang", "Ruiz", "Berg", "Mensah", "Novak"] + + +def build_dupes(level: int, rng: random.Random) -> Built: + while True: + rows, owner = [], {} + people = [(f, l) for f, l in zip(rng.sample(FIRST, 6), rng.sample(LAST, 6))] + n = 0 + for f, l in people: + email = f"{f[0].lower()}.{l.lower()}@mail.example" + phone = f"555{rng.randint(1000000, 9999999)}" + for k in range(rng.choice([1, 1, 2, 3])): + n += 1 + cid = f"C{100 + n}" + e = rng.choice([email, email.upper(), f" {email}"]) if k == 0 or rng.random() < 0.6 else "" + ph = rng.choice([phone, f"({phone[:3]}) {phone[3:6]}-{phone[6:]}", f"{phone[:3]}.{phone[3:6]}.{phone[6:]}"]) + if e == "" and rng.random() < 0.3: + ph = "" + rows.append([cid, f"{f} {l}", e, ph]) + owner[cid] = (email if e else None, phone if ph else None) + # Same person = same normalised email, or same phone digits (transitively). + parent = {c: c for c in owner} + + def find(c): + while parent[c] != c: + c = parent[c] + return c + + for a in owner: + for b in owner: + if a < b and ((owner[a][0] and owner[a][0] == owner[b][0]) or (owner[a][1] and owner[a][1] == owner[b][1])): + parent[find(b)] = find(a) + groups = {} + for c in owner: + groups.setdefault(find(c), []).append(c) + want = sorted(sorted(g, key=lambda c: int(c[1:])) for g in groups.values() if len(g) > 1) + via_phone = any(len(g) > 1 and len({owner[c][0] for c in g if owner[c][0]}) <= 1 and + any(owner[c][0] is None for c in g) for g in groups.values()) + if 2 <= len(want) <= 5 and via_phone: + break + rng.shuffle(rows) + files = {"customers.csv": to_csv(["customer_id", "name", "email", "phone"], rows)} + + def verify(app: str) -> bool: + got = load_json(app, "duplicates.json") + if not isinstance(got, dict) or set(got) != {"groups"} or not isinstance(got["groups"], list): + return False + try: + norm = sorted(sorted(g, key=lambda c: int(c[1:])) for g in got["groups"]) + except (TypeError, ValueError, IndexError): + return False + return norm == want + + instruction = ( + "Find duplicate customers in /app/customers.csv. Two records are the same customer if their emails match " + "(ignoring case and surrounding spaces) or their phone numbers have the same digits; this is transitive. " + "Blank emails or phones match nothing. Write /app/duplicates.json as {\"groups\": [[customer ids], ...]} " + "with every group of two or more records." + ) + return Built(instruction=instruction, files=files, + artifact=Artifact(path="duplicates.json", kind="custom", verify=verify, + render=lambda: json.dumps({"groups": want}) + "\n"), + notes={"expected": want}) + + +# ---------------------------------------------------------------- ev_bankrec + +def build_bankrec(level: int, rng: random.Random) -> Built: + while True: + ledger, bank = [], [] + for i in range(10): + amt = rng.choice([-1, 1]) * rng.randint(500, 250000) + day = rng.randint(1, 26) + ledger.append([f"L{i + 1:02d}", f"2026-08-{day:02d}", amt]) + r = rng.random() + if r < 0.7: + bank.append([f"BK{rng.randint(100, 999)}{i}", f"2026-08-{min(28, day + rng.randint(0, 2)):02d}", amt]) + elif r < 0.85: + bank.append([f"BK{rng.randint(100, 999)}{i}", f"2026-08-{min(28, day + rng.randint(4, 6)):02d}", amt]) + for j in range(2): + bank.append([f"BKX{j}", f"2026-08-{rng.randint(1, 28):02d}", rng.choice([-1, 1]) * rng.randint(500, 9000)]) + rng.shuffle(bank) + # Match each ledger entry, in ledger order, to the earliest unmatched bank line with the same amount + # dated 0-3 days after it. + used, unmatched_l = set(), [] + for lid, ld, amt in ledger: + cands = sorted((bd, bid) for bid, bd, ba in bank if bid not in used and ba == amt and 0 <= int(bd[-2:]) - int(ld[-2:]) <= 3) + if cands: + used.add(cands[0][1]) + else: + unmatched_l.append(lid) + unmatched_b = sorted(bid for bid, _, _ in bank if bid not in used) + # A ledger entry whose bank line exists but was booked too late must be present. + late = any(lid in unmatched_l and any(ba == amt and int(bd[-2:]) - int(ld[-2:]) > 3 for _, bd, ba in bank) + for lid, ld, amt in ledger) + if late and 1 <= len(unmatched_l) <= 5 and len(unmatched_b) >= 2: + break + fmt = lambda c: f"{c / 100:.2f}" # noqa: E731 + files = {"ledger.csv": to_csv(["entry", "date", "amount"], [[a, b, fmt(c)] for a, b, c in ledger]), + "statement.csv": to_csv(["line", "booked", "amount"], [[a, b, fmt(c)] for a, b, c in bank])} + want = {"unmatched_ledger": sorted(unmatched_l), "unmatched_bank": unmatched_b} + + def verify(app: str) -> bool: + return json_equal(load_json(app, "reconciliation.json"), want) + + instruction = ( + "Reconcile /app/ledger.csv with the bank /app/statement.csv. Take ledger entries in file order; match each " + "to the earliest-booked unmatched statement line with exactly the same amount booked 0 to 3 days after the " + "ledger date. Write /app/reconciliation.json as {\"unmatched_ledger\": [entry ids], \"unmatched_bank\": " + "[line ids]}, both sorted." + ) + return Built(instruction=instruction, files=files, + artifact=Artifact(path="reconciliation.json", kind="custom", verify=verify, + render=lambda: json.dumps(want) + "\n"), + notes={"expected": want}) + + +# ---------------------------------------------------------------- ev_fixedin + +def _ver(v: str) -> tuple: + return tuple(int(x) for x in v.split(".")) + + +def build_fixedin(level: int, rng: random.Random) -> Built: + while True: + versions = [] + major, minor, patch = 1, rng.randint(2, 8), 0 + for _ in range(6): + r = rng.random() + if r < 0.5: + patch += 1 + elif r < 0.85: + minor, patch = minor + 1, 0 + else: + major, minor, patch = major + 1, 0, 0 + versions.append(f"{major}.{minor}.{patch}") + issues = [f"ISS-{rng.randint(100, 999)}" for _ in range(8)] + notes, first = {}, {} + for v in versions: + fixed = rng.sample(issues, rng.randint(1, 3)) + notes[v] = fixed + for iss in fixed: + if iss not in first or _ver(v) < _ver(first[iss]): + first[iss] = v + asked = rng.sample(issues, 5) + want = {iss: first.get(iss) for iss in asked} + reopened = sum(1 for i in asked if sum(i in f for f in notes.values()) > 1) + lexical = {i: min((v for v in versions if i in notes[v]), default=None) for i in asked} + if reopened and None in want.values() and lexical != want: + break + files = {"issues.txt": "\n".join(asked) + "\n"} + for v in rng.sample(versions, len(versions)): + lines = [f"# Release {v}", "", "## Fixed"] + [f"- {i}: {rng.choice(['crash on save', 'slow export', 'typo in menu', 'login loop'])}" + for i in notes[v]] + files[f"changelog/{v}.md"] = "\n".join(lines) + "\n" + + def verify(app: str) -> bool: + return json_equal(load_json(app, "fixed_in.json"), want) + + instruction = ( + "For each issue in /app/issues.txt, find the earliest release whose notes in /app/changelog/ list it as " + "fixed (an issue can appear in several releases; compare versions numerically, so 1.10.0 is after 1.9.2). " + "Write /app/fixed_in.json as {issue: version} with null for issues never fixed." + ) + return Built(instruction=instruction, files=files, + artifact=Artifact(path="fixed_in.json", kind="custom", verify=verify, + render=lambda: json.dumps(want) + "\n"), + notes={"expected": want}) + + +FAMILIES = [ + Family("ev_deliveries", "industrial", "Outstanding quantities on purchase orders", build_deliveries, (1,)), + Family("ev_badges", "security", "Badge swipes outside inherited zone rights", build_badges, (1,)), + Family("ev_dupes", "office", "Duplicate customers by email or phone, transitively", build_dupes, (1,)), + Family("ev_bankrec", "finance", "Ledger to bank statement reconciliation", build_bankrec, (1,)), + Family("ev_fixedin", "software", "First release that fixed each issue", build_fixedin, (1,)), +] diff --git a/components/dnakhla/upstream/terminal_desk/families/software.py b/components/skillsdesk/upstream/terminal_desk/families/repair.py similarity index 62% rename from components/dnakhla/upstream/terminal_desk/families/software.py rename to components/skillsdesk/upstream/terminal_desk/families/repair.py index 9ec1fc55119e6608e1a75deed0d5489660b01d1d..49a7f318285dae38ce34555cab1d39559ae46be8 100644 --- a/components/dnakhla/upstream/terminal_desk/families/software.py +++ b/components/skillsdesk/upstream/terminal_desk/families/repair.py @@ -1,6 +1,10 @@ -"""Software engineering: repair a small module against hidden tests; resolve package versions.""" +"""Repair and verify: fix code against a specification, a failing test and hidden checks. + +fix_toolkit is adapted from Terminal Desk v2's sw_fix (dnakhla, Apache-2.0; see NOTICE): the +grader runs hidden cases against the edited module as nobody, on a copy. fix_report gives a broken +report script; the grader runs the repaired script on a second, hidden input. +""" -import itertools import json import os import random @@ -9,8 +13,9 @@ import tempfile from ..core import shell from .base import Artifact, Built, Family +from .util import json_equal, load_json, read_artifact, to_csv -# ---------------------------------------------------------------- sw_fix +# ---------------------------------------------------------------- fix_toolkit FUNCS = { "median": { @@ -172,7 +177,7 @@ def _differs(good, bad, args) -> bool: def build_fix(level: int, rng: random.Random) -> Built: - n_funcs, n_bugs = {1: (3, 1), 2: (4, 2), 3: (5, 2)}[level] + n_funcs, n_bugs = 4, 2 names = rng.sample(sorted(FUNCS), n_funcs) buggy = set(rng.sample(names, n_bugs)) shown = rng.choice(sorted(buggy)) # the one bug with a failing visible test @@ -223,16 +228,13 @@ def build_fix(level: int, rng: random.Random) -> Built: test_lines += ["", 'if __name__ == "__main__":', " unittest.main()", ""] readme = ( "toolkit.py feeds the nightly reports. Each function's docstring is its specification.\n" - "Run the tests from /work with: python3 -m unittest discover -s tests -v\n" + "Run the tests from /app with: python3 -m unittest discover -s tests -v\n" ) - if level >= 2: - readme += "The visible tests are incomplete: a function can be wrong and still pass them.\n" + readme += "The visible tests are incomplete: a function can be wrong and still pass them.\n" def verify(app: str) -> bool: - from ..core.grading import read_artifact - - source = read_artifact(app, "src/toolkit.py") # lstat-guarded: a planted link is not followed - if source is None: + data = read_artifact(app, "src/toolkit.py") # regular file only, no symlinks + if data is None: return False tmp = tempfile.mkdtemp(prefix="tdchk-") try: @@ -240,7 +242,7 @@ def build_fix(level: int, rng: random.Random) -> Built: src_dir = os.path.join(tmp, "src") os.mkdir(src_dir) with open(os.path.join(src_dir, "toolkit.py"), "wb") as fh: - fh.write(source) + fh.write(data) with open(os.path.join(tmp, "harness.py"), "w") as fh: fh.write(HARNESS) shell.give_to_nobody(tmp) @@ -269,120 +271,156 @@ def build_fix(level: int, rng: random.Random) -> Built: ) -# ---------------------------------------------------------------- sw_deps -PKG_NAMES = ["acorn", "birch", "cedar", "dahlia", "ember", "fennel", "garnet", "hazel"] +# ---------------------------------------------------------------- fix_report -def _vkey(v: str) -> tuple: - return tuple(int(p) for p in v.split(".")) +REGIONS = ["north", "south", "coast", "valley", "metro"] +REPORT_PY = '''"""Summarise shipments per region. Usage: python3 report.py """ -def _versions(rng: random.Random, n: int) -> list[str]: - out, major, minor = [], 1, 0 - for _ in range(n): - out.append(f"{major}.{minor}") - if rng.random() < 0.3: - major, minor = major + 1, 0 - else: - minor += rng.randint(1, 2) - return out +import csv +import json +import sys + + +def main(src, dst): + totals = {} + with open(src, newline="") as fh: + for row in csv.DictReader(fh): + if row["status"] == "Void": + continue + region = row["region"] + cost = float(row["cost"]) + weight = float(row["weight_kg"]) + t = totals.setdefault(region, {"shipments": 0, "cost": 0.0, "weight": 0.0}) + t["shipments"] += 1 + t["cost"] += cost + t["weight"] += weight + out = {} + for region, t in totals.items(): + out[region] = { + "shipments": t["shipments"], + "total_cost": round(t["cost"], 2), + "cost_per_kg": round(t["cost"] / t["shipments"], 3), + } + with open(dst, "w") as fh: + json.dump(out, fh, indent=1, sort_keys=True) + + +if __name__ == "__main__": + main(sys.argv[1], sys.argv[2]) +''' + +REPORT_FIXED = (REPORT_PY.replace('row["status"] == "Void"', 'row["status"].strip().lower() == "void"') + .replace('float(row["cost"])', 'float(row["cost"].replace("$", "").replace(",", ""))') + .replace('t["cost"] / t["shipments"]', 't["cost"] / t["weight"]')) + +SPEC = """# Shipment report + +report.py summarises a shipments CSV per region: + + python3 report.py data/shipments.csv out/summary.json +Input columns: shipment_id, region, weight_kg, cost, status. +- cost is in dollars and may be written like "$1,234.50". +- Rows whose status is void (any capitalisation) are cancelled and must be left out entirely. -def _constraint(rng: random.Random, versions: list[str]) -> tuple: - """(lo inclusive or None, hi exclusive or None), never empty over versions.""" - i, j = sorted(rng.sample(range(len(versions) + 1), 2)) - lo = versions[i] if i > 0 else None - hi = versions[j] if j < len(versions) else None - if lo is None and hi is None: - lo = versions[1] - return lo, hi - - -def _fmt(name: str, c: tuple) -> str: - lo, hi = c - parts = ([f">={lo}"] if lo else []) + ([f"<{hi}"] if hi else []) - return name + ",".join(parts) - - -def _ok(v: str, c: tuple) -> bool: - lo, hi = c - return (lo is None or _vkey(v) >= _vkey(lo)) and (hi is None or _vkey(v) < _vkey(hi)) - - -def build_deps(level: int, rng: random.Random) -> Built: - n_pkg, n_ver = {1: (3, 3), 2: (5, 4), 3: (6, 3)}[level] - while True: - pkgs = sorted(rng.sample(PKG_NAMES, n_pkg)) - vers = {p: _versions(rng, n_ver) for p in pkgs} - reqs = {} - for p in pkgs: - for v in vers[p]: - others = [q for q in pkgs if q != p and rng.random() < {1: 0.45, 2: 0.4, 3: 0.22}[level]] - reqs[(p, v)] = {q: _constraint(rng, vers[q]) for q in others} - root = {p: _constraint(rng, vers[p]) for p in pkgs if rng.random() < 0.5} - order = rng.sample(pkgs, n_pkg) - - def solve(yanked): - valid = [] - for combo in itertools.product(*(vers[p] for p in pkgs)): - pick = dict(zip(pkgs, combo)) - if any((p, v) in yanked for p, v in pick.items()): - continue - if not all(_ok(pick[p], c) for p, c in root.items()): - continue - if all(_ok(pick[q], c) for p in pkgs for q, c in reqs[(p, pick[p])].items()): - valid.append(pick) - best = max(valid, key=lambda pk: tuple(_vkey(pk[p]) for p in order)) if valid else None - return valid, best - - yanked = set() - valid, best = solve(yanked) - if level == 3 and best: - # Yank a release the unyanked optimum would pick, so yanked.txt matters. - target = rng.choice(pkgs) - yanked = {(target, best[target])} | {(p, rng.choice(vers[p])) for p in rng.sample(pkgs, 2)} - valid, best = solve(yanked) - if len(valid) < 2 or best == {p: vers[p][-1] for p in pkgs}: +Output: a JSON object keyed by region; each value is + {"shipments": count of shipments, "total_cost": summed cost rounded to 2 decimals, + "cost_per_kg": summed cost divided by summed weight_kg, rounded to 3 decimals} + +Finance reported that the nightly job crashes and that its earlier numbers looked wrong. +""" + + +def _shipments(rng: random.Random, n: int): + regions = rng.sample(REGIONS, 3) + rows = [] + for i in range(n): + cost = round(rng.uniform(40, 4200), 2) + cost_txt = rng.choice([f"{cost:.2f}", f"${cost:,.2f}", f"${cost:,.2f}", f"{cost:,.2f}"]) + status = rng.choice(["delivered", "delivered", "in_transit", "void", "VOID", "Void"]) if i % 3 == 0 else "delivered" + rows.append([f"SH-{rng.randint(1000, 9999)}", regions[i % 3], f"{rng.uniform(0.5, 120):.1f}", cost_txt, status]) + if not any(r[4].lower() == "void" for r in rows): + rows[0][4] = "void" + if not any("," in r[3] for r in rows): + rows[1][3] = "$1,250.00" + rng.shuffle(rows) + return rows + + +def _summary(rows) -> dict: + totals = {} + for sid, region, weight, cost, status in rows: + if status.strip().lower() == "void": continue - break - lines = [] - for p in pkgs: - lines.append(p) - for v in vers[p]: - r = reqs[(p, v)] - need = "; ".join(_fmt(q, c) for q, c in sorted(r.items())) or "(no requirements)" - lines.append(f" {v}: {need}") - app = ( - "The app installs every package in index.txt, one version each.\n" - f"App constraints: {'; '.join(_fmt(p, c) for p, c in sorted(root.items())) or '(none)'}\n" - f"Preference order: {', '.join(order)}\n" - ) - files = {"index.txt": "\n".join(lines) + "\n", "app.txt": app} - if yanked: - files["yanked.txt"] = ( - "These releases were yanked and must not be installed:\n" - + "\n".join(f"{p} {v}" for p, v in sorted(yanked)) - + "\n" - ) + t = totals.setdefault(region, [0, 0.0, 0.0]) + t[0] += 1 + t[1] += float(cost.replace("$", "").replace(",", "")) + t[2] += float(weight) + return {r: {"shipments": t[0], "total_cost": round(t[1], 2), "cost_per_kg": round(t[1] / t[2], 3)} + for r, t in totals.items()} + + +SHIP_HEADER = ["shipment_id", "region", "weight_kg", "cost", "status"] + + +def build_report(level: int, rng: random.Random) -> Built: + rows = _shipments(rng, 12) + hidden_rows = _shipments(rng, 15) + want = _summary(rows) + hidden_want = _summary(hidden_rows) + hidden_csv = to_csv(SHIP_HEADER, hidden_rows) + files = {"report.py": REPORT_PY, "README.md": SPEC, "data/shipments.csv": to_csv(SHIP_HEADER, rows)} + + def run_script(app: str): + script = read_artifact(app, "report.py") + if script is None: + return None + tmp = tempfile.mkdtemp(prefix="tdrep-") + try: + os.chmod(tmp, 0o755) + with open(os.path.join(tmp, "report.py"), "wb") as fh: + fh.write(script) + with open(os.path.join(tmp, "in.csv"), "w") as fh: + fh.write(hidden_csv) + shell.give_to_nobody(tmp) + shell.run(["python3", "-I", "report.py", "in.csv", "out.json"], tmp) + return load_json(tmp, "out.json") + finally: + shell.kill_nobody() + shutil.rmtree(tmp, ignore_errors=True) + + def same(got, expected) -> bool: + if not isinstance(got, dict) or set(got) != set(expected): + return False + for region, e in expected.items(): + g = got[region] + if not isinstance(g, dict) or set(g) != set(e) or not json_equal(g["shipments"], e["shipments"]): + return False + if not json_equal(g["total_cost"], float(e["total_cost"]), 0.005): + return False + if not json_equal(g["cost_per_kg"], float(e["cost_per_kg"]), 0.0005): + return False + return True + + def verify(app: str) -> bool: + return same(load_json(app, "out/summary.json"), want) and same(run_script(app), hidden_want) + instruction = ( - "index.txt lists every package with its versions and what each version requires, and app.txt gives the " - "app constraints and a preference order. Pick one version of every package so the app constraints and " - "the requirements of every picked version all hold. '>=X' means at least X, ' 1.9). Among all valid picks, " - "take the highest version of the first package in the preference order, then of the second, and so on." - + (" Never pick a release listed in yanked.txt." if yanked else "") - + " Write /app/lock.txt with one name==version line per package, for example acorn==1.2, and nothing else." - ) - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="lock.txt", kind="lines", expected=[f"{p}=={best[p]}" for p in pkgs]), - notes={"valid_count": len(valid)}, + "The nightly shipment report in /app/report.py is broken. /app/README.md is its specification. Repair " + "/app/report.py so it follows the specification for any input of that format, then run it on " + "/app/data/shipments.csv to write /app/out/summary.json. The grader checks out/summary.json and also runs " + "your report.py on a different shipments file." ) + return Built(instruction=instruction, files=files, + artifact=Artifact(path="out/summary.json", kind="custom", verify=verify, + render=lambda: json.dumps(want, indent=1, sort_keys=True) + "\n"), + notes={"expected": want, "oracle_files": {"report.py": REPORT_FIXED}}) FAMILIES = [ - Family("sw_fix", "software engineering", "Repair a module against hidden tests", build_fix), - Family("sw_deps", "software engineering", "Resolve package versions", build_deps), + Family("fix_toolkit", "software", "Repair a helper module against hidden tests", build_fix, (1,)), + Family("fix_report", "office", "Repair a broken report script and rerun it", build_report, (1,)), ] diff --git a/components/skillsdesk/upstream/terminal_desk/families/repair2.py b/components/skillsdesk/upstream/terminal_desk/families/repair2.py new file mode 100644 index 0000000000000000000000000000000000000000..a6777158841c3b5a4b6e0b30bdedf7cce0d818ba --- /dev/null +++ b/components/skillsdesk/upstream/terminal_desk/families/repair2.py @@ -0,0 +1,431 @@ +"""Repair and verify, second batch. Four modules graded on hidden cases (pagination, log parsing, +unit conversion, business days) and two scripts rerun on hidden input (deduplication, merging two +sorted exports). Hidden runs happen as nobody on a copy.""" + +import datetime as dt +import json +import random + +from .base import Artifact, Built, Family +from .util import json_equal, load_csv, read_artifact, run_hidden, to_csv + +HARNESS = r''' +import json, sys +sys.path.insert(0, ".") +cases = json.load(open("cases.json")) +try: + mod = __import__(sys.argv[1]) +except BaseException as exc: + print("@@OUT@@" + json.dumps({"import_error": type(exc).__name__})) + raise SystemExit(0) +out = [] +for fn, args in cases: + try: + out.append(getattr(mod, fn)(*args)) + except BaseException as exc: + out.append({"error": type(exc).__name__}) +print("@@OUT@@" + json.dumps(out, default=repr)) +''' + + +def _close(got, want) -> bool: + """Exact structure; floats within a relative 1e-9 (implementations may order operations differently).""" + if isinstance(want, float) and not isinstance(got, bool) and isinstance(got, (int, float)): + return abs(got - want) <= 1e-9 * max(1.0, abs(want)) + if isinstance(want, list): + return isinstance(got, list) and len(got) == len(want) and all(_close(g, w) for g, w in zip(got, want)) + if isinstance(want, dict): + return isinstance(got, dict) and set(got) == set(want) and all(_close(got[k], want[k]) for k in want) + return json_equal(got, want) + + +def _module_task(module: str, broken: str, fixed: str, cases: list, tests: str, instruction: str) -> Built: + ns: dict = {} + exec(fixed, ns) # noqa: S102 - our own reference implementation + want = [] + for fn, args in cases: + try: + want.append(ns[fn](*args)) + except Exception as exc: # the specification says which inputs raise + want.append({"error": type(exc).__name__}) + want = json.loads(json.dumps(want, default=repr)) + path = f"{module}.py" + + def verify(app: str) -> bool: + src = read_artifact(app, path) + if src is None: + return False + text, _ = run_hidden({path: src, "cases.json": json.dumps(cases), "h.py": HARNESS}, + ["python3", "-I", "h.py", module], []) + lines = [ln for ln in text.splitlines() if ln.startswith("@@OUT@@")] + return bool(lines) and _close(json.loads(lines[-1][7:]), want) + + return Built(instruction=instruction, files={path: broken, f"test_{module}.py": tests}, + artifact=Artifact(path=path, kind="custom", verify=verify, render=lambda: fixed), + notes={"oracle_files": {path: fixed}}) + + +# ---------------------------------------------------------------- fix_paginate + +PAGINATE_FIXED = '''"""Pagination helpers. Pages are numbered from 1.""" + + +def page_count(total, per_page): + """Number of pages needed for total items, per_page per page; 0 items need 0 pages.""" + return (total + per_page - 1) // per_page + + +def page(items, number, per_page): + """The items on page `number`; an empty list for a page past the end. number < 1 raises ValueError.""" + if number < 1: + raise ValueError("pages start at 1") + start = (number - 1) * per_page + return items[start:start + per_page] +''' + +PAGINATE_BROKEN = PAGINATE_FIXED.replace("return (total + per_page - 1) // per_page", "return total // per_page + 1") \ + .replace("start = (number - 1) * per_page", "start = number * per_page - per_page + 1") + + +def build_paginate(level: int, rng: random.Random) -> Built: + cases = [["page_count", [0, 10]], ["page_count", [10, 10]], ["page", [list(range(5)), 0, 2]]] + for _ in range(30): + n, per = rng.randint(0, 40), rng.randint(1, 9) + cases.append(["page_count", [n, per]] if rng.random() < 0.4 else + ["page", [list(range(n)), rng.randint(1, n // per + 2), per]]) + tests = ("import unittest\nfrom paginate import page_count, page\n\n\nclass T(unittest.TestCase):\n" + " def test_count(self):\n self.assertEqual(page_count(25, 10), 3)\n\n\n" + "if __name__ == '__main__':\n unittest.main()\n") + return _module_task("paginate", PAGINATE_BROKEN, PAGINATE_FIXED, cases, tests, + "Users report missing and duplicated rows between pages. Fix /app/paginate.py in place so both " + "functions follow their docstrings (keep names and signatures). /app/test_paginate.py is " + "incomplete; the grader runs hidden cases, including edge cases.") + + +# ---------------------------------------------------------------- fix_logline + +LOGLINE_FIXED = r'''"""Parse one access-log line: + [