Use newline-only headers and semantic browser grading (0.5.0)
Browse filesNo trailing indentation in prompts; preserve fenced body whitespace and Python helpers. Accept semantic HTML attribute/text equivalents; browser behavior and parser syntax are reported independently. Add diagnostic hidden-test pass rate; primary all-tests-required macro score unchanged. Fixed 350 data/test/reference files unchanged. Live browser validation still outstanding.
Files changed (15)
- README.md+22-8
- SHA256SUMS+14-12
- completion.py+11-8
- examples/base-prompts.json+23-23
- examples/local-test-report.json+4-3
- generation_settings.py+1-1
- manifest.json+1-1
- metrics.py+8-1
- pyproject.toml+1-1
- runners/common.py+12-7
- runners/semantic.pyAdded+40
- sandbox/supervisor.py+2-2
- sandbox/worker.py+22-15
- tests/test_completion.py+16-4
- tests/test_semantic.pyAdded+53
24 unmodified lines2526272829303153 unmodified lines858687888990913 unmodified lines959697989910010123 unmodified lines12512612712812913013112 unmodified lines1441451461471481491501 unmodified line15215315415515615715815916016116216316424 unmodified lines---# SmolScriptAn original execution-based benchmark of basic programming for 25M–350M parameter language models. Evaluator **0.4.0**, **350 default examples** (fixed dataset edition 0.3.0), nine languages, MIT license.**Release status: execution-unverified candidate.** All 350 default records have been generated and statically validated. No complete reference execution run or model baseline is claimed. The authoring environment has no Docker/Podman daemon; all 350 default reference solutions and their negative controls still require execution in the supplied sandbox image. See `validation_report.json` for the machine-readable audit. Do not treat this candidate as a validated leaderboard release until `python validate.py` succeeds.53 unmodified linespython evaluate.py --model HuggingFaceTB/SmolLM2-135M --language python rust --difficulty easy --output subset.json```One fixed completion prompt (`smolscript-base-completion-v2`), one generation, seed 0, greedy decoding, no beam search, and versioned task budgets from 96 to 256 tokens. Starting batch size is 64, with automatic CUDA OOM backoff. Prompts are grouped by token budget and length; KV caching and supported last-token logits optimizations are enabled. Progress is reported between batches, avoiding per-token GPU-to-CPU synchronization. The same completion template is used for base and instruction models; no model-specific chat template is applied. The model revision resolves to an immutable commit and is retained on resume. Use `--revision SHA` for an explicit pin. Prompts contain task comments, the input domain, supplied standard-library imports, web fixtures/base styles where needed, and a function/markup prefix. Models continue the supplied source directly. References, public examples, hidden tests, and expected answers are never sent to the model.Existing files require `--resume`. Settings, dataset/runner hashes, image ID and selected IDs must match. Completed task results are checkpointed atomically; a generated response is saved before execution, so an execution interruption can reuse it. Partial runs never receive a full score. Use one process per output path (a file lock enforces this). Context overflow is an explicit failure; input prompts are never silently truncated.3 unmodified linespython evaluate.py --predictions predictions.jsonl --output results.json```Externally supplied predictions use complete source code (raw code or a single fenced code block). Model inference stores raw continuations and deterministically assembles the supplied prefix before scoring. Multiple or unfinished fences are rejected. Function tasks receive fixed stdin/stdout wrappers. Compiled languages compile once per task, then run a fresh process per test. HTML is parsed with html5lib and checked in Chromium with document scripts disabled. CSS is parsed with tinycss2 and tested against a fixed fixture at the specified widths. Browser tests assert DOM/computed styles and geometry, without image similarity.## Metrics23 unmodified linesThe language budgets (before a 32-token moderate-task allowance, capped at 256) are Python 128, JavaScript 192, HTML 160, CSS 96, C++ 224, C 256, Lua 160, C# 256, Rust 256. They depend only on language/difficulty, never reference solutions. `--max-new-tokens N` overrides these budgets for a separately recorded experiment; `--batch-size N` overrides the default 64. A response that hits its cap is scored as generated; incorrect or incomplete code still fails the normal execution tests. Generation statistics include token-limit completions, OOM retries, final batch size, elapsed generation time and measured token throughput.Example: `python evaluate.py --model HuggingFaceTB/SmolLM2-135M --batch-size 64 --output results-v030.json`. Generated batches are checkpointed before execution, and resume skips their inference. Numerical batching differences can change greedy outputs for near-tied logits. This release reduces the task count from 1,000 to 350 and retains the fast decoding budgets introduced in 0.2.0. Its scores must not be merged with earlier editions. Template IDs are `smolscript-0.4.0` and `cognirank2-v4`; use a new output path. No GPU throughput speedup is claimed without a measured run.## Browser timeout handling12 unmodified linesThe Modal path first checks runtime availability and a trusted CSS computed-style/distractor probe, before model generation. Worker processes use explicit subprocess UID/GID settings and private writable HOME/XDG/TMP directories; no Python pre-exec callback is used in the threaded launcher. These changes preserve the fixed 350-example dataset and scoring definition. End-to-end Modal browser verification is still required; local tests cover the injection protocol, diagnostic fields, preflight failure and watchdog behavior.## Base-model completion protocol (0.4.0)The same completion template is used for every model, including instruction models. There is no chat wrapper, conversational instruction block, worked solution, reference implementation, test input, expected answer, or answer-dependent repair. Example prompt ending:1 unmodified line# Starting with n, double it, then take the last decimal digit of its absolute value. Return the result.# Integer n from -120 to 120.def solve(n):```The model continues at the indented body. Python headers omit type annotations. JavaScript, C, C++, C#, Rust and Lua receive their function/method openings (including the C# class), and applicable supplied imports. HTML receives a task comment followed by `<`; CSS receives its fixture/context and task as a CSS comment. `examples/base-prompts.json` contains an example for each language. `completion.py` is the authoritative prompt and assembly implementation.The supplied prefix is attached to the generated continuation. Answer-independent lexical scope extraction keeps the first completed function/class body and discards trailing prose. Python uses indentation tokens; braced languages count delimiters while ignoring ordinary strings/comments (and supported regex/raw/verbatim strings); Lua counts block keywords. These are constrained completion delimiters, not general language parsers. Syntax and behavior are still checked inside the sandbox. Missing delimiters, malformed indentation, expressions, and return values are never repaired, and no closing suffix is invented. Complete entry-point definitions emitted from scratch, including a single fenced code block, are accepted as deterministic formatting alternatives.Raw continuations and assembled `evaluated_code` are saved separately. The standalone `--predictions` path continues to accept complete code and bypasses the completion prefix. All 350 supplied reference bodies roundtrip through assembly (Python body AST equality, other languages source equality); this is a static assembly check, not complete runtime validation. Full isolated reference execution and a new KLM benchmark run remain outstanding.Use a **new output path** for `smolscript-0.4.0` / `cognirank2-v4`. Dataset edition/selection 0.3.0 remains fixed; only the evaluation prompt/assembly protocol changes. Old scores are not comparable and must be rerun for leaderboard comparisons. Token budgets, deterministic greedy decoding, batch size 64, eight isolated Modal scoring workers, tests and weights remain the same.24 unmodified lines2526272829303153 unmodified lines858687888990913 unmodified lines959697989910010123 unmodified lines12512612712812913013112 unmodified lines1441451461471481491501 unmodified line15215315415515615715815916016116216316416516616716816917017117217317417517617717824 unmodified lines---# SmolScriptAn original execution-based benchmark of basic programming for 25M–350M parameter language models. Evaluator **0.5.0**, **350 default examples** (fixed dataset edition 0.3.0), nine languages, MIT license.**Release status: execution-unverified candidate.** All 350 default records have been generated and statically validated. No complete reference execution run or model baseline is claimed. The authoring environment has no Docker/Podman daemon; all 350 default reference solutions and their negative controls still require execution in the supplied sandbox image. See `validation_report.json` for the machine-readable audit. Do not treat this candidate as a validated leaderboard release until `python validate.py` succeeds.53 unmodified linespython evaluate.py --model HuggingFaceTB/SmolLM2-135M --language python rust --difficulty easy --output subset.json```One fixed completion prompt (`smolscript-base-completion-v3`), one generation, seed 0, greedy decoding, no beam search, and versioned task budgets from 96 to 256 tokens. Starting batch size is 64, with automatic CUDA OOM backoff. Prompts are grouped by token budget and length; KV caching and supported last-token logits optimizations are enabled. Progress is reported between batches, avoiding per-token GPU-to-CPU synchronization. The same completion template is used for base and instruction models; no model-specific chat template is applied. The model revision resolves to an immutable commit and is retained on resume. Use `--revision SHA` for an explicit pin. Prompts contain task comments, the input domain, supplied standard-library imports, web fixtures/base styles where needed, and a function/markup prefix. Models continue the supplied source directly. References, public examples, hidden tests, and expected answers are never sent to the model.Existing files require `--resume`. Settings, dataset/runner hashes, image ID and selected IDs must match. Completed task results are checkpointed atomically; a generated response is saved before execution, so an execution interruption can reuse it. Partial runs never receive a full score. Use one process per output path (a file lock enforces this). Context overflow is an explicit failure; input prompts are never silently truncated.3 unmodified linespython evaluate.py --predictions predictions.jsonl --output results.json```Externally supplied predictions use complete source code (raw code or a single fenced code block). Model inference stores raw continuations and deterministically assembles the supplied prefix before scoring. Multiple or unfinished fences are rejected. Function tasks receive fixed stdin/stdout wrappers. Compiled languages compile once per task, then run a fresh process per test. HTML is parsed with html5lib and checked in Chromium with document scripts disabled. CSS syntax is reported with tinycss2 and behavior is tested against a fixed fixture at the specified widths. Browser tests assert DOM/computed styles and geometry, without image similarity.## Metrics23 unmodified linesThe language budgets (before a 32-token moderate-task allowance, capped at 256) are Python 128, JavaScript 192, HTML 160, CSS 96, C++ 224, C 256, Lua 160, C# 256, Rust 256. They depend only on language/difficulty, never reference solutions. `--max-new-tokens N` overrides these budgets for a separately recorded experiment; `--batch-size N` overrides the default 64. A response that hits its cap is scored as generated; incorrect or incomplete code still fails the normal execution tests. Generation statistics include token-limit completions, OOM retries, final batch size, elapsed generation time and measured token throughput.Example: `python evaluate.py --model HuggingFaceTB/SmolLM2-135M --batch-size 64 --output results-v030.json`. Generated batches are checkpointed before execution, and resume skips their inference. Numerical batching differences can change greedy outputs for near-tied logits. This release reduces the task count from 1,000 to 350 and retains the fast decoding budgets introduced in 0.2.0. Its scores must not be merged with earlier editions. Template IDs are `smolscript-0.5.0` and `cognirank2-v5`; use a new output path. No GPU throughput speedup is claimed without a measured run.## Browser timeout handling12 unmodified linesThe Modal path first checks runtime availability and a trusted CSS computed-style/distractor probe, before model generation. Worker processes use explicit subprocess UID/GID settings and private writable HOME/XDG/TMP directories; no Python pre-exec callback is used in the threaded launcher. These changes preserve the fixed 350-example dataset and scoring definition. End-to-end Modal browser verification is still required; local tests cover the injection protocol, diagnostic fields, preflight failure and watchdog behavior.## Base-model completion protocol (0.5.0)The same completion template is used for every model, including instruction models. There is no chat wrapper, conversational instruction block, worked solution, reference implementation, test input, expected answer, or answer-dependent repair. Example prompt ending:1 unmodified line# Starting with n, double it, then take the last decimal digit of its absolute value. Return the result.# Integer n from -120 to 120.def solve(n):```The prompt ends immediately after the header newline, with no trailing spaces or tabs. The model supplies its own body indentation. Python headers omit type annotations. JavaScript, C, C++, C#, Rust and Lua receive their function/method openings (including the C# class), and applicable supplied imports. HTML receives a task comment followed by `<`; CSS receives its fixture/context and task as a CSS comment. `examples/base-prompts.json` contains an example for each language. `completion.py` is the authoritative prompt and assembly implementation.The supplied prefix is attached to the generated continuation. Answer-independent lexical scope extraction keeps the first completed function/class body and discards trailing prose. Python uses indentation tokens; braced languages count delimiters while ignoring ordinary strings/comments (and supported regex/raw/verbatim strings); Lua counts block keywords. These are constrained completion delimiters, not general language parsers. Syntax and behavior are still checked inside the sandbox. Missing delimiters, malformed indentation, expressions, and return values are never repaired, and no closing suffix is invented. Complete entry-point definitions emitted from scratch, including a single fenced code block, are accepted as deterministic formatting alternatives.Raw continuations and assembled `evaluated_code` are saved separately. The standalone `--predictions` path continues to accept complete code and bypasses the completion prefix. All 350 supplied reference bodies roundtrip through assembly (Python body AST equality, other languages source equality); this is a static assembly check, not complete runtime validation. Full isolated reference execution and a new KLM benchmark run remain outstanding.Use a **new output path** for `smolscript-0.5.0` / `cognirank2-v5`. Dataset edition/selection 0.3.0 remains fixed; only the evaluation prompt/assembly protocol changes. Old scores are not comparable and must be rerun for leaderboard comparisons. Token budgets, deterministic greedy decoding, batch size 64, eight isolated Modal scoring workers, tests and weights remain the same.## Behavioral equivalence (0.5.0)Correctness is determined by the executable tests, never by source similarity. Newline-only function openings now leave indentation generation to the model. Fenced body completions preserve indentation, and valid Python source with module-level helper functions is retained.HTML checks accept semantic equivalents: case-insensitive enumerated attribute values (`method="POST"`/`"post"`, `dir="RTL"`/`"rtl"`), equivalent hidden/boolean states, numeric attribute representations, and class-token ordering. Required elements, nesting, targets and content still matter. URL, ID, name and ordinary text values are not indiscriminately lowercased. Attribute lookup errors and missing required attributes still fail.For ordinary HTML text, collapsible ASCII whitespace is normalized; preformatted text retains significant whitespace, and `pre-line` preserves line breaks. Extra inline spans with the same text can satisfy the same text check. JavaScript string outputs and programming string tasks retain exact observable content. CSS compares computed styles, so equivalent selectors, shorthands and color notations can pass when they produce all required styles and leave distractors unchanged.HTML/CSS syntax reporting is now independent of behavioral testing: the native browser may recover from a parsing issue and still satisfy every assertion. Such a task can pass behavior while Syntax Success reports false. Full HTML documents and fragments are parsed in the appropriate mode. JavaScript syntax failures still prevent execution. No model source is rewritten to repair errors.The optional `hidden_test_pass_rate` diagnostic averages test-pass fractions per task and then macro-averages across languages. It shows partial functional success. The official SmolScript Score remains all-tests-required Pass@1, macro-averaged across nine languages; this diagnostic does not affect CogniRank weights. It does not award credit for comments describing a solution that was not implemented.These scoring/format changes require a new output path (`smolscript-0.5.0`, `cognirank2-v5`). All 350 tasks, reference implementations and hidden test files remain byte-identical. The local equivalence controls use observation fixtures and a mocked browser; full real-browser reference validation remains outstanding.
1234562 unmodified lines91011121314151617181920212223242526272829303132333435366 unmodified lines4344454647484950515253ff73ee904edc9381bd1ea24847e41c6176aec22ba4b63321e8354562f24ba5ce .gitignore8719af4397a8387b8f04140613943545f8ecd90f06529dcab9e68a94927d13fe LICENSEed646bff1e37aaa95e039cabd8a3d58ed18485179de096e37f5ddf7a7223966e README.md2447d09ae445094c1ae59df644b46e3ca2f4cc64de630966b94bd5db8b8bf0ac archive/v0.1.0/hidden.jsonl1926bca1b0c6b2244554577135a9c3c305b18fd834c654803b4e8480fff0d3d9 archive/v0.1.0/smolscript.jsonl7bf25948750648aa036bdf277cfd7c38597c98aa06131e805628b9055a7938d9 archive/v0.1.0/smolscript.parquet2 unmodified lines1c17c3515e86e2c4bc25c84b45b9f086c87efd98e1d75a7f4b42772b9d88176e archive/v0.2.0/smolscript.jsonl358eae399dac7564ea5fb8753734f189aea3932994a22779d543bdcce847e050 archive/v0.2.0/smolscript.parquet34c7244ea9160ba090e7c3bc1802ca68cc882f8ee9c29736ea8529d499977677 archive/v0.2.0/solutions.jsonl7a057672dbe866e2b8dca92c8fc2a8baf35547831666d41309f20cc09c96344e completion.py9f9798909d3ab3631a457de1bc7e573c546ed3f3b0f78e6bcb82780e280b37b3 data/smolscript.jsonlad56c7186df28d84a23912a7fa2ec28b6762240a33b7b2a49412ce5b47319862 data/smolscript.parquet0eaebae91f30afdebb84183619620f3eb73257ba3ab7c09572f0a982c5c99cd6 evaluate.py9ee4551be1a573d2bb94f41935f94028ab538d3b6e4ba957d6bf9a9076fefd67 examples/base-prompts.json3c1e0c66200ec31a08d316a012ac30456c06c90521360db8a150a3a56357e255 examples/local-test-report.json713855348ffc53f49b03a0df47b67294fe2d3593054636eec12b9f184fb3534e examples/result-format.jsonaf0da7e2ef72cb6ac992aac4a83ddfe200e2512b5e26209882b403cb2b48ea4a generation_settings.pye3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 generators/__init__.py8f14ca3a1a122d0d4ab34420e0c5493299166554aa296ec503af3e53e1847485 generators/build.pye1cf493b995f15470c56c097b73e7403ae06f74f5d12cbb3a43ce522514d8577 generators/code.py60be0a7ac6fcd3dfd8b663fc19af189aba3acfdd923219dc6cc1972033380240 generators/specs.pyc800d0237c7f4342fb636b6e54f15616a9547406f165e7ad7f96965cd6b9a4d1 generators/subset.pyae6a8d5109035027b71df7eb7297e7c0b811a4a98c649e1729a3fe2a2c09c5bf generators/web.py8a834a5d375b4fa14d9b1416d47056e0533c8338401aff505e98767349e38673 manifest.json6bac32e6045f1788e8b68e96ff6ee41f1b2152cca1b17de24be405025f294930 metrics.pye00a185b961e80e1e1e86e6ddf97ec470d10e1c7b2bed44eb221af42a0eb6972 private_tests/hidden.jsonl8e37b2b9360b8283ef7f99a5702b5575d66c34e88e9d59c0f9631437fd30aa61 pyproject.tomld736311f2645f4bdc7bac3316d858788118af4d551290d3924299f96935bd886 references/solutions.jsonl5a3cb2a82cf3784c41fc9f9046fe6806d5bbe7ce8ae415a9ed1c373abcfe7826 runners/__init__.py965bc9e3dabfc3fba4b745994b43118c456be477edcc34a3ba929ebf39e19ce9 runners/c_runner.py2cd2ee3e805abfca108f19363a828ee38a46afb9d91773f68bdc08231449b68c runners/common.py17c846633f3730669790ee2f11fc93661648eedc950c96d47996d0db4514672b runners/cpp_runner.pye87545f911f6f25238b1f84ed0ac1602900676b77cb3dd5f1560cd62e0b931e4 runners/csharp_runner.py96e542ceb76e18759aa8f19fd87beef3612e535f7b9f04944a6bdf1e2fddffec runners/css_runner.py6 unmodified linesefabd7a4b829eb917116a2f51358a8fa8056370dbb57f6b6a9646c1cd342ffc5 runners/python_runner.py63514e35b2687742ea6453e15d089da5a6cb4ab57ca0100da6189b187511ecf7 runners/rust_runner.pyd9ebf5141e3c1928879865050bf3ad7773613084fe62a0ff7eac8d1ea69f8cc4 runners/sandbox.py53098a63b7d2053a4d8494c340e63d924646255c297d31e78c0025ef552c6cd6 sandbox/Dockerfile013cc442aa61d4b85f1986b111ea9adea5f9749bf0cef5176faa67963c900e7c sandbox/supervisor.py538b3c7176b678e6a2b2a55a52aaa2e4a03accc20b2d7d850ee67695f5ecdc9f sandbox/worker.pyf58268efbe40e27869f903e8b482b28e1e55213705be8c72e2fb6f5b0b95336c tests/test_completion.pyc155b14ce8fa94dd4a179c22e6ab13accadffcf3571f384d27985ba916cbf864 tests/test_core.py14f40a4b954c81dcf6cb8a2bdf361023e8cea36b54b31e40657f92f39433c124 tests/test_watchdog.pyffba2ed9eabec6186a7568ff0535c9733841b661f7c1e420770dbeb47d87dbae validate.py845d1ef1d45133e04908e1ff187281b9af9f4e48c2bec1994f91b1b191d5d563 validation_report.json1234562 unmodified lines91011121314151617181920212223242526272829303132333435366 unmodified lines43444546474849505152535455ff73ee904edc9381bd1ea24847e41c6176aec22ba4b63321e8354562f24ba5ce .gitignore8719af4397a8387b8f04140613943545f8ecd90f06529dcab9e68a94927d13fe LICENSE27c3710b398dde92dd98ff5632398ed85e954a31b8d94705b7a85a565d253966 README.md2447d09ae445094c1ae59df644b46e3ca2f4cc64de630966b94bd5db8b8bf0ac archive/v0.1.0/hidden.jsonl1926bca1b0c6b2244554577135a9c3c305b18fd834c654803b4e8480fff0d3d9 archive/v0.1.0/smolscript.jsonl7bf25948750648aa036bdf277cfd7c38597c98aa06131e805628b9055a7938d9 archive/v0.1.0/smolscript.parquet2 unmodified lines1c17c3515e86e2c4bc25c84b45b9f086c87efd98e1d75a7f4b42772b9d88176e archive/v0.2.0/smolscript.jsonl358eae399dac7564ea5fb8753734f189aea3932994a22779d543bdcce847e050 archive/v0.2.0/smolscript.parquet34c7244ea9160ba090e7c3bc1802ca68cc882f8ee9c29736ea8529d499977677 archive/v0.2.0/solutions.jsonlc88b809ee731ea2e98b3ff987bd95fd815ba473979a8bec61f37b5646be80dd0 completion.py9f9798909d3ab3631a457de1bc7e573c546ed3f3b0f78e6bcb82780e280b37b3 data/smolscript.jsonlad56c7186df28d84a23912a7fa2ec28b6762240a33b7b2a49412ce5b47319862 data/smolscript.parquet0eaebae91f30afdebb84183619620f3eb73257ba3ab7c09572f0a982c5c99cd6 evaluate.py90d902ef697281c2336a488b6b7ddb287e48ac10ed6a5bf2d5299da8d6d97450 examples/base-prompts.jsonc86d561ca339e05e75e1d55ec0cc8e11e88fb1d1d31853eacbb0ab1d622b5c2c examples/local-test-report.json713855348ffc53f49b03a0df47b67294fe2d3593054636eec12b9f184fb3534e examples/result-format.json63f1c72b12b69f075dd581081feb3950256ef8bfdc99c02721e7ce514a3c981f generation_settings.pye3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 generators/__init__.py8f14ca3a1a122d0d4ab34420e0c5493299166554aa296ec503af3e53e1847485 generators/build.pye1cf493b995f15470c56c097b73e7403ae06f74f5d12cbb3a43ce522514d8577 generators/code.py60be0a7ac6fcd3dfd8b663fc19af189aba3acfdd923219dc6cc1972033380240 generators/specs.pyc800d0237c7f4342fb636b6e54f15616a9547406f165e7ad7f96965cd6b9a4d1 generators/subset.pyae6a8d5109035027b71df7eb7297e7c0b811a4a98c649e1729a3fe2a2c09c5bf generators/web.py9c6439595a13166be57748d43264983ae19cb8ac0a73b7f929cab931e51c8d1d manifest.json873a82296884a7b6d17b942e61aa0fec515ccdb0da3cc43947b2dc2157b78bab metrics.pye00a185b961e80e1e1e86e6ddf97ec470d10e1c7b2bed44eb221af42a0eb6972 private_tests/hidden.jsonl26e3ba6e29aa21f7098662128f5973b110a138bb1019096cfcdf03a81032bebb pyproject.tomld736311f2645f4bdc7bac3316d858788118af4d551290d3924299f96935bd886 references/solutions.jsonl5a3cb2a82cf3784c41fc9f9046fe6806d5bbe7ce8ae415a9ed1c373abcfe7826 runners/__init__.py965bc9e3dabfc3fba4b745994b43118c456be477edcc34a3ba929ebf39e19ce9 runners/c_runner.py6e141f7d88826077366a1f22d96fdb483b9404484d7a763d95c34afe6abb54b6 runners/common.py17c846633f3730669790ee2f11fc93661648eedc950c96d47996d0db4514672b runners/cpp_runner.pye87545f911f6f25238b1f84ed0ac1602900676b77cb3dd5f1560cd62e0b931e4 runners/csharp_runner.py96e542ceb76e18759aa8f19fd87beef3612e535f7b9f04944a6bdf1e2fddffec runners/css_runner.py6 unmodified linesefabd7a4b829eb917116a2f51358a8fa8056370dbb57f6b6a9646c1cd342ffc5 runners/python_runner.py63514e35b2687742ea6453e15d089da5a6cb4ab57ca0100da6189b187511ecf7 runners/rust_runner.pyd9ebf5141e3c1928879865050bf3ad7773613084fe62a0ff7eac8d1ea69f8cc4 runners/sandbox.py57326ba34adabc061352dcc0ca703c7dcf0ec656df1d66254e3f21795991952a runners/semantic.py53098a63b7d2053a4d8494c340e63d924646255c297d31e78c0025ef552c6cd6 sandbox/Dockerfile179daec1a38a9d5eba0d37235cf1e8793ce8454f32e79220f0825ef62ff30c96 sandbox/supervisor.py053547265479e5e2781852cfb6a0612caa3c85a47b5ec56a59a6cda9d4aedc90 sandbox/worker.py8b3c872c1ee88d65e400b8712a27b184698f697fb52e1e87b9ed6eb7c0b433dd tests/test_completion.pyc155b14ce8fa94dd4a179c22e6ab13accadffcf3571f384d27985ba916cbf864 tests/test_core.py704facc31065766122bf57346d0ae063e1e3c708fc1f97747c23ca8810c8789b tests/test_semantic.py14f40a4b954c81dcf6cb8a2bdf361023e8cea36b54b31e40657f92f39433c124 tests/test_watchdog.pyffba2ed9eabec6186a7568ff0535c9733841b661f7c1e420770dbeb47d87dbae validate.py845d1ef1d45133e04908e1ff187281b9af9f4e48c2bec1994f91b1b191d5d563 validation_report.json
1 unmodified line23456789 unmodified lines1819202122232425262728108 unmodified lines13713813914014114214310 unmodified lines1541551561571581591601 unmodified lineimport ioimport reimport tokenizePROMPT_VERSION='smolscript-base-completion-v2'SIGNATURES={'python':{'scalar':'def solve(n):','string':'def solve(s):','array':'def solve(values):'},'javascript':{'scalar':'function solve(n)','string':'function solve(s)','array':'function solve(values)','dom':'function setup()'},9 unmodified linesif lang=='html':return '<'if lang=='css':return ''header=SIGNATURES[lang][kind]if lang=='python':return header+'\n 'if lang=='lua':return header+'\n 'if kind=='dom':return header+' {\n 'if lang=='csharp':return 'public class Solution {\n'+header+' {\n 'return header+' {\n 'def prompt(row):from runners.protocol import HEADERS108 unmodified linestext=continuationif text.lstrip().startswith('```'):from runners.common import extract_codetext=extract_code(text)expected=prefix(row)starts={'python':r'^def\s+solve\s*\(', 'javascript':r'^(?:async\s+)?function\s+(?:solve|setup)\s*\(',10 unmodified lineselif lang in starts and re.match(starts[lang],text.lstrip()):code=text.lstrip()elif lang=='html' and text.lstrip().startswith('<'):code=text.lstrip()else:code=expected+textif lang=='python' and not complete_python:code=code[:_python_end(code)]elif lang=='lua':code=code[:_lua_end(code)]elif lang not in ('html','css','python'):code=code[:_brace_end(code)]return code.rstrip()+'\n'1 unmodified line23456789 unmodified lines1819202122232425262728108 unmodified lines13713813914014114214310 unmodified lines1541551561571581591601611621631 unmodified lineimport ioimport reimport tokenizePROMPT_VERSION='smolscript-base-completion-v3'SIGNATURES={'python':{'scalar':'def solve(n):','string':'def solve(s):','array':'def solve(values):'},'javascript':{'scalar':'function solve(n)','string':'function solve(s)','array':'function solve(values)','dom':'function setup()'},9 unmodified linesif lang=='html':return '<'if lang=='css':return ''header=SIGNATURES[lang][kind]if lang=='python':return header+'\n'if lang=='lua':return header+'\n'if kind=='dom':return header+' {\n'if lang=='csharp':return 'public class Solution {\n'+header+' {\n'return header+' {\n'def prompt(row):from runners.protocol import HEADERS108 unmodified linestext=continuationif text.lstrip().startswith('```'):from runners.common import extract_codetext=extract_code(text,preserve_indentation=True)expected=prefix(row)starts={'python':r'^def\s+solve\s*\(', 'javascript':r'^(?:async\s+)?function\s+(?:solve|setup)\s*\(',10 unmodified lineselif lang in starts and re.match(starts[lang],text.lstrip()):code=text.lstrip()elif lang=='html' and text.lstrip().startswith('<'):code=text.lstrip()else:code=expected+textif lang=='python' and not complete_python:import asttry:ast.parse(code)except SyntaxError:code=code[:_python_end(code)]elif lang=='lua':code=code[:_lua_end(code)]elif lang not in ('html','css','python'):code=code[:_brace_end(code)]return code.rstrip()+'\n'
1 unmodified line2345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364651 unmodified line{"id": "smolscript-python-0015","language": "python","prompt_version": "smolscript-base-completion-v2","completion_prompt": "# Starting with n, double it, then take the last decimal digit of its absolute value. Return the result.\n# Integer n from -120 to 120.\ndef solve(n):\n ","supplied_prefix": "def solve(n):\n "},{"id": "smolscript-javascript-0010","language": "javascript","prompt_version": "smolscript-base-completion-v2","completion_prompt": "// Starting with ASCII string s, replace each run of spaces with one space, then keep the first floor(length/2) characters. Return the result.\n// ASCII s of at most 80 characters, without newlines.\nfunction solve(s) {\n ","supplied_prefix": "function solve(s) {\n "},{"id": "smolscript-html-0003","language": "html","prompt_version": "smolscript-base-completion-v2","completion_prompt": "<!-- Create an h1 heading reading Welcome. On its outer element, set right-to-left direction via dir. -->\n<","supplied_prefix": "<"},{"id": "smolscript-css-0010","language": "css","prompt_version": "smolscript-base-completion-v2","completion_prompt": "/* HTML fixture: <div id=\"scope\"><div id=\"target\" class=\"target\" data-kind=\"card\">Alpha<span>One</span><span>Two</span></div><div class=\"other\">Beta</div></div><div class=\"target\" id=\"outside\">Outside</div> Existing CSS: * { box-sizing: content-box; } .target,.other { border: 1px solid black; width:200px; height:80px; min-width:0; max-width:none; margin:0; padding:0; display:block; position:static; } Style every element with class target: set font-weight to 700. Leave other elements unchanged. */\n","supplied_prefix": ""},{"id": "smolscript-cpp-0003","language": "cpp","prompt_version": "smolscript-base-completion-v2","completion_prompt": "// Starting with n, clamp it to the inclusive range -5 to 5, then subtract it from ten. Return the result.\n// Integer n from -120 to 120.\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <cstdlib>\nlong long solve(long long n) {\n ","supplied_prefix": "long long solve(long long n) {\n "},{"id": "smolscript-c-0001","language": "c","prompt_version": "smolscript-base-completion-v2","completion_prompt": "// Starting with n, replace it with 1 if negative, otherwise 0, then add one. Return the result.\n// Integer n from -120 to 120.\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\nlong long solve(long long n) {\n ","supplied_prefix": "long long solve(long long n) {\n "},{"id": "smolscript-lua-0001","language": "lua","prompt_version": "smolscript-base-completion-v2","completion_prompt": "-- Starting with n, replace it with 1 if negative, otherwise 0, then add one. Return the result.\n-- Integer n from -120 to 120.\nfunction solve(n)\n ","supplied_prefix": "function solve(n)\n "},{"id": "smolscript-csharp-0003","language": "csharp","prompt_version": "smolscript-base-completion-v2","completion_prompt": "// Starting with n, clamp it to the inclusive range -5 to 5, then subtract it from ten. Return the result.\n// Integer n from -120 to 120.\nusing System;\nusing System.Linq;\nusing System.Collections.Generic;\npublic class Solution {\npublic static long Solve(long n) {\n ","supplied_prefix": "public class Solution {\npublic static long Solve(long n) {\n "},{"id": "smolscript-rust-0002","language": "rust","prompt_version": "smolscript-base-completion-v2","completion_prompt": "// Starting with ASCII string s, convert lowercase ASCII letters to uppercase, then convert uppercase ASCII letters to lowercase. Return the result.\n// ASCII s of at most 80 characters, without newlines.\nuse std::io::{self, Read};\nfn solve(mut s: String) -> String {\n ","supplied_prefix": "fn solve(mut s: String) -> String {\n "}]1 unmodified line2345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364651 unmodified line{"id": "smolscript-python-0015","language": "python","prompt_version": "smolscript-base-completion-v3","completion_prompt": "# Starting with n, double it, then take the last decimal digit of its absolute value. Return the result.\n# Integer n from -120 to 120.\ndef solve(n):\n","supplied_prefix": "def solve(n):\n"},{"id": "smolscript-javascript-0010","language": "javascript","prompt_version": "smolscript-base-completion-v3","completion_prompt": "// Starting with ASCII string s, replace each run of spaces with one space, then keep the first floor(length/2) characters. Return the result.\n// ASCII s of at most 80 characters, without newlines.\nfunction solve(s) {\n","supplied_prefix": "function solve(s) {\n"},{"id": "smolscript-html-0003","language": "html","prompt_version": "smolscript-base-completion-v3","completion_prompt": "<!-- Create an h1 heading reading Welcome. On its outer element, set right-to-left direction via dir. -->\n<","supplied_prefix": "<"},{"id": "smolscript-css-0010","language": "css","prompt_version": "smolscript-base-completion-v3","completion_prompt": "/* HTML fixture: <div id=\"scope\"><div id=\"target\" class=\"target\" data-kind=\"card\">Alpha<span>One</span><span>Two</span></div><div class=\"other\">Beta</div></div><div class=\"target\" id=\"outside\">Outside</div> Existing CSS: * { box-sizing: content-box; } .target,.other { border: 1px solid black; width:200px; height:80px; min-width:0; max-width:none; margin:0; padding:0; display:block; position:static; } Style every element with class target: set font-weight to 700. Leave other elements unchanged. */\n","supplied_prefix": ""},{"id": "smolscript-cpp-0003","language": "cpp","prompt_version": "smolscript-base-completion-v3","completion_prompt": "// Starting with n, clamp it to the inclusive range -5 to 5, then subtract it from ten. Return the result.\n// Integer n from -120 to 120.\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <cstdlib>\nlong long solve(long long n) {\n","supplied_prefix": "long long solve(long long n) {\n"},{"id": "smolscript-c-0001","language": "c","prompt_version": "smolscript-base-completion-v3","completion_prompt": "// Starting with n, replace it with 1 if negative, otherwise 0, then add one. Return the result.\n// Integer n from -120 to 120.\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\nlong long solve(long long n) {\n","supplied_prefix": "long long solve(long long n) {\n"},{"id": "smolscript-lua-0001","language": "lua","prompt_version": "smolscript-base-completion-v3","completion_prompt": "-- Starting with n, replace it with 1 if negative, otherwise 0, then add one. Return the result.\n-- Integer n from -120 to 120.\nfunction solve(n)\n","supplied_prefix": "function solve(n)\n"},{"id": "smolscript-csharp-0003","language": "csharp","prompt_version": "smolscript-base-completion-v3","completion_prompt": "// Starting with n, clamp it to the inclusive range -5 to 5, then subtract it from ten. Return the result.\n// Integer n from -120 to 120.\nusing System;\nusing System.Linq;\nusing System.Collections.Generic;\npublic class Solution {\npublic static long Solve(long n) {\n","supplied_prefix": "public class Solution {\npublic static long Solve(long n) {\n"},{"id": "smolscript-rust-0002","language": "rust","prompt_version": "smolscript-base-completion-v3","completion_prompt": "// Starting with ASCII string s, convert lowercase ASCII letters to uppercase, then convert uppercase ASCII letters to lowercase. Return the result.\n// ASCII s of at most 80 characters, without newlines.\nuse std::io::{self, Read};\nfn solve(mut s: String) -> String {\n","supplied_prefix": "fn solve(mut s: String) -> String {\n"}]
12345614 unmodified lines212223242526273 unmodified lines3132333435{"unit_tests": {"passed": 28,"command": "python -m unittest discover -s tests -q"},"python_reference_ast_parse": 44,14 unmodified lines"rust": 39},"blocked_reason": "Docker/Podman unavailable; full isolated reference and negative-control execution remains unverified.","model_baselines": "No 0.4.0 model baseline run","gpu_throughput_benchmark": "not run","watchdog_policy": "phase-watchdog-v1","watchdog_test_execution": "trusted synthetic workers; candidate generations not executed on host",3 unmodified lines"method": "Python body AST equality; other languages source equality","execution": false},"prompt_version": "smolscript-base-completion-v2"}12345614 unmodified lines212223242526273 unmodified lines313233343536{"unit_tests": {"passed": 34,"command": "python -m unittest discover -s tests -q"},"python_reference_ast_parse": 44,14 unmodified lines"rust": 39},"blocked_reason": "Docker/Podman unavailable; full isolated reference and negative-control execution remains unverified.","model_baselines": "No 0.5.0 model baseline run","gpu_throughput_benchmark": "not run","watchdog_policy": "phase-watchdog-v1","watchdog_test_execution": "trusted synthetic workers; candidate generations not executed on host",3 unmodified lines"method": "Python body AST equality; other languages source equality","execution": false},"prompt_version": "smolscript-base-completion-v3","equivalence_controls": "semantic attribute/text observations and mocked browser; no live browser execution"}
12345"""Versioned decoding policy; never reads references or hidden answers."""PROTOCOL='smolscript-0.4.0'DEFAULT_BATCH_SIZE=64MAX_NEW_TOKENS=25612345"""Versioned decoding policy; never reads references or hidden answers."""PROTOCOL='smolscript-0.5.0'DEFAULT_BATCH_SIZE=64MAX_NEW_TOKENS=256
12345{"evaluation_protocol": "smolscript-0.4.0","version": "smolscript-0.3.0","examples": 350,"languages": {12345{"evaluation_protocol": "smolscript-0.5.0","version": "smolscript-0.3.0","examples": 350,"languages": {
8 unmodified lines91011121314151617188 unmodified linesfor r in results:groups[r['language']].append(r)accuracy={lang:100*sum(bool(r['passed']) for r in group)/len(group) for lang,group in sorted(groups.items())}syntax={lang:100*sum(bool(r['syntax_success']) for r in group)/len(group) for lang,group in sorted(groups.items())}if full_run and set(groups)!=set(LANGUAGES):raise ValueError('Missing language')score=sum(accuracy.values())/len(accuracy)result={'scope':'full' if full_run else 'filtered','examples':len(results),'pass_at_1':score,'syntax_success':sum(syntax.values())/len(syntax),'per_language_accuracy':accuracy,'per_language_syntax_success':syntax,'micro_accuracy':100*sum(r['passed'] for r in results)/len(results)}result['smolscript_score' if full_run else 'filtered_macro_score']=scorereturn result8 unmodified lines9101112131415161718192021222324258 unmodified linesfor r in results:groups[r['language']].append(r)accuracy={lang:100*sum(bool(r['passed']) for r in group)/len(group) for lang,group in sorted(groups.items())}syntax={lang:100*sum(bool(r['syntax_success']) for r in group)/len(group) for lang,group in sorted(groups.items())}def fraction(row):tests=row.get('tests')if tests is None:return float(bool(row['passed']))return sum(bool(t['passed']) for t in tests)/len(tests) if tests else 0.0test_rates={lang:100*sum(fraction(r) for r in group)/len(group) for lang,group in sorted(groups.items())}if full_run and set(groups)!=set(LANGUAGES):raise ValueError('Missing language')score=sum(accuracy.values())/len(accuracy)result={'scope':'full' if full_run else 'filtered','examples':len(results),'pass_at_1':score,'syntax_success':sum(syntax.values())/len(syntax),'hidden_test_pass_rate':sum(test_rates.values())/len(test_rates),'per_language_test_pass_rate':test_rates,'per_language_accuracy':accuracy,'per_language_syntax_success':syntax,'micro_accuracy':100*sum(r['passed'] for r in results)/len(results)}result['smolscript_score' if full_run else 'filtered_macro_score']=scorereturn result
2 unmodified lines34567892 unmodified linesbuild-backend = "setuptools.build_meta"[project]name = "smolscript"version = "0.4.0"description = "A small-model multilingual execution benchmark"requires-python = ">=3.11"license = {text = "MIT"}2 unmodified lines34567892 unmodified linesbuild-backend = "setuptools.build_meta"[project]name = "smolscript"version = "0.5.0"description = "A small-model multilingual execution benchmark"requires-python = ">=3.11"license = {text = "MIT"}
1 unmodified line234567891011121324 unmodified lines38394041424344454647487 unmodified lines5657585960611 unmodified linefrom decimal import Decimal,InvalidOperationdef extract_code(text):text=text.strip()blocks=re.findall(r'```[^\n`]*\n(.*?)```',text,re.S)if len(blocks)==1:return blocks[0].strip()+'\n'if len(blocks)>1:raise ValueError('Multiple code blocks are ambiguous')if '```' in text:raise ValueError('Unclosed code fence')return text+'\n'24 unmodified linesclass BrowserRunner:def evaluate(self,row,code,hidden,sandbox):scenarios=[];expected=[]for t in hidden['tests']:widths=sorted(set(c.get('viewport',800) for c in t['checks']))for width in widths:checks=[c for c in t['checks'] if c.get('viewport',800)==width]# Deliberately do not send expected values into the sandbox.scenarios.append({'viewport':width,'steps':t.get('steps',[]),'checks':[{k:v for k,v in c.items() if k not in ('value','viewport')} for c in checks]})7 unmodified linesfor j,c in enumerate(checks):observed=actual['actual'][j] if actual and j<len(actual['actual']) else Nonetarget=actual['baseline'][j] if actual and c['kind']=='unchanged' else c.get('value',True)passed=bool(actual and not actual['error'] and j<len(actual['actual']) and observed==target)results.append({'scenario':i,'test':j,'passed':passed,'actual':observed,'error':actual['error'] if actual else 'syntax failure'})return {'syntax_success':response['syntax_success'],'passed':bool(results) and all(r['passed'] for r in results),'tests':results,'candidate_timeout':response.get('candidate_timeout',False)}1 unmodified line234567891011121314151624 unmodified lines414243444546474849505152537 unmodified lines6162636465661 unmodified linefrom decimal import Decimal,InvalidOperationdef extract_code(text,preserve_indentation=False):text=text.strip('\r\n') if preserve_indentation else text.strip()# Closing fences must occupy their own line; backticks inside a string are code.blocks=re.findall(r'^[ \t]*```[^\r\n`]*\r?\n(.*?)^[ \t]*```[ \t]*(?=\r?$)',text,re.S|re.M)if len(blocks)==1:body=blocks[0].rstrip('\r\n') if preserve_indentation else blocks[0].strip()return body+'\n'if len(blocks)>1:raise ValueError('Multiple code blocks are ambiguous')if re.search(r'^[ \t]*```',text,re.M):raise ValueError('Unclosed code fence')return text+'\n'24 unmodified linesclass BrowserRunner:def evaluate(self,row,code,hidden,sandbox):from runners.semantic import matchesscenarios=[];expected=[]for t in hidden['tests']:widths=sorted(set(c.get('viewport',800) for c in t['checks']))for width in widths:checks=[dict(c,kind='html_text') if row['language']=='html' and c['kind']=='text' else cfor c in t['checks'] if c.get('viewport',800)==width]# Deliberately do not send expected values into the sandbox.scenarios.append({'viewport':width,'steps':t.get('steps',[]),'checks':[{k:v for k,v in c.items() if k not in ('value','viewport')} for c in checks]})7 unmodified linesfor j,c in enumerate(checks):observed=actual['actual'][j] if actual and j<len(actual['actual']) else Nonetarget=actual['baseline'][j] if actual and c['kind']=='unchanged' else c.get('value',True)passed=bool(actual and not actual['error'] and j<len(actual['actual']) and matches(c,observed,target))results.append({'scenario':i,'test':j,'passed':passed,'actual':observed,'error':actual['error'] if actual else 'syntax failure'})return {'syntax_success':response['syntax_success'],'passed':bool(results) and all(r['passed'] for r in results),'tests':results,'candidate_timeout':response.get('candidate_timeout',False)}
12345678910111213141516171819202122232425262728293031323334353637383940"""Behavioral normalization for browser observations; never inspect solutions."""from decimal import Decimal,InvalidOperationimport reASCII_SPACE=re.compile(r'[ \t\r\n\f]+')BOOLEAN={'disabled','checked','selected','required','multiple','readonly','autofocus','open','reversed'}CASE_INSENSITIVE={'method','dir','type','contenteditable','lang','enctype','formmethod'}FLOATING={'max','min'}INTEGER={'rows','cols','tabindex','colspan','rowspan','width','height'}
def matches(check,observed,target): kind=check['kind'] if kind=='html_text': if not isinstance(observed,dict) or 'text' not in observed:return False text=observed['text'] if observed.get('white_space') in ('pre','pre-wrap','break-spaces'): return text.replace('\r\n','\n')==target.replace('\r\n','\n') if observed.get('white_space')=='pre-line': collapse=lambda s:'\n'.join(re.sub(r'[ \t\f]+',' ',line).strip() for line in s.replace('\r\n','\n').split('\n')) return collapse(text)==collapse(target) return ASCII_SPACE.sub(' ',text).strip()==ASCII_SPACE.sub(' ',target).strip() if kind!='attribute':return observed==target if observed is not None and not isinstance(observed,str):return False name=check['name'].lower() if name=='class':return set((observed or '').split())==set((target or '').split()) if name in BOOLEAN:return (observed is not None)==(target is not None) if name=='hidden': def state(v):return 'absent' if v is None else 'until-found' if v.lower()=='until-found' else 'hidden' return state(observed)==state(target) if observed is None or target is None:return observed==target if name in CASE_INSENSITIVE:return observed.lower()==target.lower() if name in INTEGER: a=re.match(r'^[ \t\r\n\f]*([+-]?[0-9]+)',observed) b=re.match(r'^[ \t\r\n\f]*([+-]?[0-9]+)',target) return bool(a and b and int(a.group(1))==int(b.group(1))) if name in FLOATING or (name=='value' and re.search(r'\b(?:progress|meter)\b',check.get('selector',''))): try: a,b=Decimal(observed),Decimal(target) if a.is_finite() and b.is_finite():return a==b except (InvalidOperation,TypeError,ValueError):pass return observed==target39 unmodified lines40414243444546474849505139 unmodified linesbrowser=payload.get('diagnostic') or payload.get('kind') in ('html','css','dom')limit=(candidate_seconds if candidate else startup_seconds) if browser else total_secondsif now-phase_started>limit or now-started>total_seconds:if candidate and state.get('syntax_success') is True:observations=list(state.get('observations',[]))for _ in range(len(payload.get('scenarios',[]))-len(observations)):observations.append({'actual':[],'baseline':[],'error':'CandidateTimeout: browser execution exceeded its wall-time limit'})return {'syntax_success':True,'observations':observations,'candidate_timeout':True}stderr.seek(0)detail=stderr.read(2000).decode('utf8','replace')raise RuntimeError('SmolScript worker timed out during browser/runtime setup; evaluation incomplete; '39 unmodified lines40414243444546474849505139 unmodified linesbrowser=payload.get('diagnostic') or payload.get('kind') in ('html','css','dom')limit=(candidate_seconds if candidate else startup_seconds) if browser else total_secondsif now-phase_started>limit or now-started>total_seconds:if candidate and isinstance(state.get('syntax_success'),bool):observations=list(state.get('observations',[]))for _ in range(len(payload.get('scenarios',[]))-len(observations)):observations.append({'actual':[],'baseline':[],'error':'CandidateTimeout: browser execution exceeded its wall-time limit'})return {'syntax_success':state['syntax_success'],'observations':observations,'candidate_timeout':True}stderr.seek(0)detail=stderr.read(2000).decode('utf8','replace')raise RuntimeError('SmolScript worker timed out during browser/runtime setup; evaluation incomplete; '
9 unmodified lines101112131415161718192046 unmodified lines67686970717217 unmodified lines9091929394959610 unmodified lines10710810911011111211311411511611711811912012112212312412512612712812913013113213313413510 unmodified lines1461471481491501511521531541551561571589 unmodified linesfrom protocol import COMMANDS,wrap_sourcedef publish_state(phase,observations=None,scenario=None,operation=None):path=os.environ.get('SMOLSCRIPT_WORKER_STATE')if not path:returntarget=Path(path);tmp=target.with_suffix('.tmp')tmp.write_text(json.dumps({'phase':phase,'syntax_success':True,'scenario':scenario,'operation':operation,'observations':observations or []}))tmp.replace(target)46 unmodified linesreturn kind==='layout_column' ? Math.abs(x.x-y.x)<1 && y.y>=x.bottom : Math.abs(x.y-y.y)<1 && y.x>=x.right; }''',kind)if kind=='exists':return loc.count()>0if loc.count()!=1:return {'error':'selector must resolve to exactly one element','count':loc.count()}if kind=='text':return loc.text_content()if kind=='attribute':return loc.get_attribute(check['name'])if kind=='value':return loc.input_value()17 unmodified lineskind=request['kind'];code=request['code']if kind=='html':import html5libparser=html5lib.HTMLParser();parser.parseFragment(code)syntax=not parser.errorselif kind=='css':import tinycss210 unmodified lineselse:Path('candidate.js').write_text(code)syntax=execute(['node','--check','candidate.js'],'',5)['exit_code']==0if not syntax:return {'syntax_success':False,'observations':[]}observations=[]publish_state('browser_startup',operation='playwright_driver')with sync_playwright() as p:# Container namespace, seccomp, uid, cgroups and disabled networking are# the mandatory boundary; no browser flag substitutes for that boundary.publish_state('browser_startup',operation='chromium_launch')b=p.chromium.launch(headless=True,timeout=20000,args=['--disable-dev-shm-usage'])try:for index,scenario in enumerate(request['scenarios']):publish_state('fixture_setup',observations,index,'new_page')page=b.new_page(viewport={'width':scenario.get('viewport',800),'height':600},java_script_enabled=kind=='dom')page.set_default_timeout(request['timeout_seconds']*1000)page.route('**/*',lambda route:route.abort())actual=[];baseline=[];error=Nonepublish_state('fixture_setup',observations,index,'fixture_document')page.set_content(request['fixture'],wait_until='domcontentloaded')if request.get('base_css'):publish_state('fixture_setup',observations,index,'base_css')inject_css(page,request['base_css'])publish_state('fixture_setup',observations,index,'baseline_observations')baseline=[observe(page,c) if c['kind']=='unchanged' else None for c in scenario['checks']]publish_state('candidate',observations,index,'candidate_execution')try:if kind=='html':page.set_content(code,wait_until='domcontentloaded')elif kind=='css':inject_css(page,code)10 unmodified linesactual=[observe(page,c) for c in scenario['checks']]except Exception as e:error=type(e).__name__+': '+str(e)[:500]observations.append({'actual':actual,'baseline':baseline,'error':error})publish_state('candidate',observations[:-1],index,'page_close')page.close()publish_state('fixture_setup',observations,index)finally:publish_state('browser_cleanup',observations)b.close()return {'syntax_success':True,'observations':observations}def main():9 unmodified lines101112131415161718192046 unmodified lines6768697071727317 unmodified lines91929394959697989910010110 unmodified lines11211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114210 unmodified lines1531541551561571581591601611621631641659 unmodified linesfrom protocol import COMMANDS,wrap_sourcedef publish_state(phase,observations=None,scenario=None,operation=None,syntax_success=True):path=os.environ.get('SMOLSCRIPT_WORKER_STATE')if not path:returntarget=Path(path);tmp=target.with_suffix('.tmp')tmp.write_text(json.dumps({'phase':phase,'syntax_success':syntax_success,'scenario':scenario,'operation':operation,'observations':observations or []}))tmp.replace(target)46 unmodified linesreturn kind==='layout_column' ? Math.abs(x.x-y.x)<1 && y.y>=x.bottom : Math.abs(x.y-y.y)<1 && y.x>=x.right; }''',kind)if kind=='exists':return loc.count()>0if loc.count()!=1:return {'error':'selector must resolve to exactly one element','count':loc.count()}if kind=='html_text':return loc.evaluate('(e)=>({text:e.textContent,white_space:getComputedStyle(e).whiteSpace})')if kind=='text':return loc.text_content()if kind=='attribute':return loc.get_attribute(check['name'])if kind=='value':return loc.input_value()17 unmodified lineskind=request['kind'];code=request['code']if kind=='html':import html5libimport reparser=html5lib.HTMLParser()document=re.match(r'(?is)\s*(?:<!--.*?-->\s*)*(?:<!doctype\s|<html(?:\s|>))',code)if document:parser.parse(code)else:parser.parseFragment(code)syntax=not parser.errorselif kind=='css':import tinycss210 unmodified lineselse:Path('candidate.js').write_text(code)syntax=execute(['node','--check','candidate.js'],'',5)['exit_code']==0if not syntax and kind=='dom':return {'syntax_success':False,'observations':[]}observations=[]def state(phase,observations=None,scenario=None,operation=None):publish_state(phase,observations,scenario,operation,syntax_success=syntax)state('browser_startup',operation='playwright_driver')with sync_playwright() as p:# Container namespace, seccomp, uid, cgroups and disabled networking are# the mandatory boundary; no browser flag substitutes for that boundary.state('browser_startup',operation='chromium_launch')b=p.chromium.launch(headless=True,timeout=20000,args=['--disable-dev-shm-usage'])try:for index,scenario in enumerate(request['scenarios']):state('fixture_setup',observations,index,'new_page')page=b.new_page(viewport={'width':scenario.get('viewport',800),'height':600},java_script_enabled=kind=='dom')page.set_default_timeout(request['timeout_seconds']*1000)page.route('**/*',lambda route:route.abort())actual=[];baseline=[];error=Nonestate('fixture_setup',observations,index,'fixture_document')page.set_content(request['fixture'],wait_until='domcontentloaded')if request.get('base_css'):state('fixture_setup',observations,index,'base_css')inject_css(page,request['base_css'])state('fixture_setup',observations,index,'baseline_observations')baseline=[observe(page,c) if c['kind']=='unchanged' else None for c in scenario['checks']]state('candidate',observations,index,'candidate_execution')try:if kind=='html':page.set_content(code,wait_until='domcontentloaded')elif kind=='css':inject_css(page,code)10 unmodified linesactual=[observe(page,c) for c in scenario['checks']]except Exception as e:error=type(e).__name__+': '+str(e)[:500]observations.append({'actual':actual,'baseline':baseline,'error':error})state('candidate',observations[:-1],index,'page_close')page.close()state('fixture_setup',observations,index)finally:state('browser_cleanup',observations)b.close()return {'syntax_success':syntax,'observations':observations}def main():
12 unmodified lines13141516171819202122232425261 unmodified line2829303132333417 unmodified lines525354555657585960616212 unmodified linesfor row in self.rows:text=prompt(row)self.assertTrue(text.endswith(prefix(row)))changed={**row,'reference_solution':'SECRET_REFERENCE','tests':[{'input':'SECRET_INPUT','expected':'SECRET_ANSWER'}]}self.assertEqual(prompt(changed),text)self.assertNotIn('Return code only',text)self.assertNotIn('function function',text)def test_python_has_no_type_annotation_boilerplate(self):row=next(r for r in self.rows if r['language']=='python')self.assertEqual(prefix(row),'def solve(n):\n ')text=assemble(row,'return abs(2*n)%10\n\nQuestion: explain this code')ast.parse(text);self.assertNotIn('Question:',text)def test_every_reference_body_roundtrips_without_solution_repairs(self):refs={r['id']:r['reference_solution'] for r in load(ROOT/'references/solutions.jsonl')}1 unmodified linelang=row['language'];ref=refs[row['id']]if lang=='html':tail=ref[1:]elif lang=='css':tail=refelif lang=='python':tail=ref.split('\n',1)[1][4:]else:self.assertTrue(ref.startswith(prefix(row)),row['id'])tail=ref[len(prefix(row)):]17 unmodified linesdef test_truncated_body_is_not_given_missing_braces(self):row=next(r for r in self.rows if r['language']=='javascript')self.assertFalse(assemble(row,'return 3;').rstrip().endswith('}'))def test_complete_function_and_fenced_output_are_accepted(self):row=next(r for r in self.rows if r['language']=='python')whole='def solve(n):\n return abs(n)\n'self.assertEqual(assemble(row,whole),whole)self.assertIn('return "```"',assemble(row,'return "```"'))self.assertEqual(assemble(row,'```python\n'+whole+'```'),whole)with self.assertRaises(ValueError):assemble(row,'```python\nreturn n')12 unmodified lines13141516171819202122232425262728291 unmodified line3132333435363717 unmodified lines555657585960616263646566676869707172737412 unmodified linesfor row in self.rows:text=prompt(row)self.assertTrue(text.endswith(prefix(row)))if row['language'] not in ('html','css'):self.assertTrue(prefix(row).endswith('\n'))self.assertFalse(text.endswith((' ', '\t')))changed={**row,'reference_solution':'SECRET_REFERENCE','tests':[{'input':'SECRET_INPUT','expected':'SECRET_ANSWER'}]}self.assertEqual(prompt(changed),text)self.assertNotIn('Return code only',text)self.assertNotIn('function function',text)def test_python_has_no_type_annotation_boilerplate(self):row=next(r for r in self.rows if r['language']=='python')self.assertEqual(prefix(row),'def solve(n):\n')text=assemble(row,' return abs(2*n)%10\n\nQuestion: explain this code')ast.parse(text);self.assertNotIn('Question:',text)def test_every_reference_body_roundtrips_without_solution_repairs(self):refs={r['id']:r['reference_solution'] for r in load(ROOT/'references/solutions.jsonl')}1 unmodified linelang=row['language'];ref=refs[row['id']]if lang=='html':tail=ref[1:]elif lang=='css':tail=refelif lang=='python':tail=ref.split('\n',1)[1]else:self.assertTrue(ref.startswith(prefix(row)),row['id'])tail=ref[len(prefix(row)):]17 unmodified linesdef test_truncated_body_is_not_given_missing_braces(self):row=next(r for r in self.rows if r['language']=='javascript')self.assertFalse(assemble(row,'return 3;').rstrip().endswith('}'))def test_python_continuation_can_define_a_module_helper(self):row=next(r for r in self.rows if r['language']=='python')body=' return double(n)\n\ndef double(x):\n return 2*x\n'code=assemble(row,body)self.assertEqual([node.name for node in ast.parse(code).body],['solve','double'])self.assertEqual(code,prefix(row)+body)def test_complete_function_and_fenced_output_are_accepted(self):row=next(r for r in self.rows if r['language']=='python')whole='def solve(n):\n return abs(n)\n'self.assertEqual(assemble(row,whole),whole)self.assertEqual(assemble(row,'```python\n return abs(n)\n```'),whole)self.assertIn('return "```"',assemble(row,'```python\n return "```"\n```'))self.assertIn('return "```"',assemble(row,' return "```"'))self.assertEqual(assemble(row,'```python\n'+whole+'```'),whole)with self.assertRaises(ValueError):assemble(row,'```python\nreturn n')
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253import importlib.utilfrom pathlib import Pathimport sysimport unittestROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT))from runners.semantic import matchesfrom metrics import aggregate
class SemanticTests(unittest.TestCase): def test_equivalent_attributes(self): for name,observed,expected in [('hidden','hidden',''),('hidden','HIDDEN',''),('method','POST','post'), ('dir','RTL','rtl'),('contenteditable','TRUE','true'),('type','BUTTON','button'), ('rows','03','3'),('max','10.0','10'),('class','b a','a b'),('class','',None)]: self.assertTrue(matches({'kind':'attribute','name':name},observed,expected),(name,observed)) def test_wrong_attributes_and_errors_rejected(self): for name,observed,expected in [('hidden',None,''),('hidden','until-found',''),('method','GET','post'), ('name','Email','email'),('href','/Help','/help'),('rows','4','3'),('class','a extra','a'),('lang',{'error':'missing'},'en'),('value','01','1'),('rows','1e1','10')]: self.assertFalse(matches({'kind':'attribute','name':name},observed,expected),(name,observed)) def test_html_visible_whitespace_and_inline_markup_text(self): c={'kind':'html_text'} self.assertTrue(matches(c,{'text':'\n Welcome\treader \n','white_space':'normal'},'Welcome reader')) self.assertFalse(matches(c,{'text':'Welcome stranger','white_space':'normal'},'Welcome reader')) self.assertFalse(matches(c,{'text':' x = 1 ','white_space':'pre'},'x = 1')) self.assertFalse(matches(c,{'text':'Hello\nreader','white_space':'pre-line'},'Hello reader')) self.assertTrue(matches({'kind':'attribute','name':'value','selector':'progress'},'4.0','4')) self.assertFalse(matches({'kind':'text'},' Ab 9 ','Ab 9')) def test_partial_credit_visible_without_claiming_solution(self): rows=[{'id':'x','language':'python','passed':False,'syntax_success':True, 'tests':[{'passed':True},{'passed':False}]}] result=aggregate(rows,['x'],full_run=False) self.assertEqual(result['filtered_macro_score'],0) self.assertEqual(result['hidden_test_pass_rate'],50) def test_browser_behavior_can_pass_with_recoverable_parser_errors(self): # Controlled fake browser: tests the worker's parse/behavior separation, # without executing generated code or launching a host browser. from unittest.mock import Mock,patch from types import SimpleNamespace import contextlib sys.path.insert(0,str(ROOT/'runners')) spec=importlib.util.spec_from_file_location('semantic_worker',ROOT/'sandbox/worker.py') worker=importlib.util.module_from_spec(spec);spec.loader.exec_module(worker) page=Mock();browser=Mock();browser.new_page.return_value=page @contextlib.contextmanager def playwright():yield SimpleNamespace(chromium=SimpleNamespace(launch=lambda **kw:browser)) modules={'playwright':SimpleNamespace(),'playwright.sync_api':SimpleNamespace(sync_playwright=playwright,TimeoutError=TimeoutError), 'tinycss2':SimpleNamespace(parse_stylesheet=lambda *a,**k:[SimpleNamespace(type='error')])} with patch.dict(sys.modules,modules),patch.object(worker,'observe',return_value='rgb(10, 20, 30)'): result=worker.browser({'kind':'css','code':'#x {color:rgb(10,20,30)} invalid;', 'fixture':'<p id="x">x</p>','timeout_seconds':3,'scenarios':[{'checks':[{'kind':'style','selector':'#x','property':'color'}]}]}) self.assertFalse(result['syntax_success']);self.assertIsNone(result['observations'][0]['error']) self.assertEqual(result['observations'][0]['actual'],['rgb(10, 20, 30)'])
if __name__=='__main__':unittest.main()README.md+22-8
SHA256SUMS+14-12
completion.py+11-8
examples/base-prompts.json+23-23
examples/local-test-report.json+4-3
generation_settings.py+1-1
manifest.json+1-1
metrics.py+8-1
pyproject.toml+1-1
runners/common.py+12-7
runners/semantic.pyAdded+40
sandbox/supervisor.py+2-2
sandbox/worker.py+22-15
tests/test_completion.py+16-4
tests/test_semantic.pyAdded+53