Datasets:
kreatix-code-plan v0.1.0: verified Python data, card, generator
Browse filesFiles changed (9)
- .gitattributes+1
- README.mdAdded+216
- assets/code-plan-themes.pngAdded
- data/test.jsonlAdded
- data/train.jsonlAdded+3
- generator/GENERATE.mdAdded+22
- generator/build_plan.pyAdded+431
- samples.mdAdded
- stats.jsonAdded+83
57 unmodified lines58596057 unmodified lines# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -text57 unmodified lines5859606157 unmodified lines# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -textdata/train.jsonl filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216---
license: apache-2.0
language:
- en
- fi
pretty_name: Kreatix Code Plan
size_categories:
- 1K<n<10K
task_categories:
- text-generation
tags:
- code
- python
- planning
- software-design
- testing
- reasoning
- multi-turn
- finnish
- synthetic
- procedurally-generated
- verified
configs:
- config_name: default
data_files:
- split: train
path: data/train.jsonl
- split: test
path: data/test.jsonl
---
# Kreatix Code Plan
**2,165 conversations in English and Finnish where the assistant plans a Python module before writing it. Each
project has 2 or 3 hard parts. The plan covers the layout and signatures, the algorithm, key points and complexity
of each part, the edge cases, a test plan with exact expected values, and a build order. The implementation then
follows the plan, and its self-test was run and passed.**
Projects use the 40 problem families of Kreatix Code Hard, grouped by theme: a scheduling toolkit, a route planner, a text library, a calculator core, an
in-memory API layer (cache, rate limiter, versioned store), budget math, and grid tools for a game.
Three conversation shapes:
| Mode | Conversation |
|---|---|
| plan | the user asks for a plan only; the reply is the plan |
| plan + code | one reply: the plan, then the full module and its test run |
| two turns | the plan; the user approves ("Looks good. Implement it."); then the module and its test run |
Made by [KreatixLabs](https://huggingface.co/KreatixLabs). Every row is built by a program: no language model wrote
any text or code in this dataset.

## What it looks like
**User**
````text
I need a small text-processing library in Python: a single module, `textkit.py`, with the following parts.
1. **Balanced brackets.** Return True if every `(`, `[` and `{` in `s` is closed by the matching bracket in the right order, and False otherwise. Other characters are ignored.
2. **Weighted edit distance.** Turn string `a` into string `b`. Inserting a character costs 2, deleting one costs 2, and replacing one character with a different one costs 3. Return the minimum total cost.
Assume large inputs: each part needs a properly efficient algorithm.
Don't code yet. Plan it first: structure, algorithms with their complexity, edge cases, a test plan with expected values, and the order you'd build it in.
````
**Assistant**
````text
## Plan
**Module layout** (`textkit.py`)
```python
def valid_brackets(s: str) -> bool: ...
def edit_cost(a: str, b: str) -> int: ...
```
The parts are independent of each other, so each one gets its own function or class and its own tests; nothing is shared except the module's imports. Imports: none, only built-ins.
**1. `valid_brackets`** (Balanced brackets)
- Approach: A stack of open brackets: a closer must match the top; the stack must be empty at the end.
- Key points:
- A stack (or a counter for one bracket type) tracks what is still open.
- Process left to right; decide immediately when a closer arrives.
- At the end, anything still open matters too.
- Complexity: O(n) time, O(n) space.
- Edge cases: empty string, only closers, interleaved types like '([)]'.
**2. `edit_cost`** (Weighted edit distance)
- Approach: Classic edit-distance DP with the three costs, keeping only the previous row. Because a replacement costs 3, it can beat a delete plus an insert.
- Key points:
- dp[i][j] = cost to turn a[:i] into b[:j].
- Transitions: delete a[i-1], insert b[j-1], or keep/replace the last characters.
- Base row and column are pure inserts and deletes.
- Only the previous row is needed: O(len(b)) memory.
- Complexity: O(len(a) · len(b)) time, O(len(b)) space.
**Test plan**
- `valid_brackets('}bb)b}')` → `False` (basic case)
- `valid_brackets(')(')` → `False` (edge case)
- `valid_brackets('(')` → `False` (edge case)
- `edit_cost('bbd', 'bd')` → `2` (basic case)
- `edit_cost('', '')` → `0` (edge case)
- `edit_cost('abc', '')` → `6` (edge case)
**Build order**
1. Write `valid_brackets` first: it is the simplest part.
2. Finish with `edit_cost`, the hardest part (it needs the most care).
3. Finally put all the tests under `if __name__ == "__main__":` so `python textkit.py` checks everything.
````
**User**
````text
OK, implement it exactly like that.
````
**Assistant**
````text
```python
"""A small text-processing library: valid_brackets, edit_cost."""
def valid_brackets(s: str) -> bool:
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stack
def edit_cost(a: str, b: str) -> int:
INS, DEL, SUB = 2, 2, 3
prev = [j * INS for j in range(len(b) + 1)]
for i in range(1, len(a) + 1):
cur = [i * DEL] + [0] * len(b)
for j in range(1, len(b) + 1):
keep = prev[j - 1] + (0 if a[i - 1] == b[j - 1] else SUB)
cur[j] = min(keep, prev[j] + DEL, cur[j - 1] + INS)
prev = cur
return prev[len(b)]
if __name__ == "__main__":
assert not valid_brackets('}bb)b}')
assert not valid_brackets(')(')
assert not valid_brackets('(')
assert edit_cost('bbd', 'bd') == 2
assert edit_cost('', '') == 0
assert edit_cost('abc', '') == 6
print("all 6 tests passed")
```
Running the file:
```
$ python textkit.py
all 6 tests passed
```
All 6 tests from the plan pass, covering the basic and edge cases of every part.
| Part | Complexity |
|---|---|
| `valid_brackets` | O(n) time, O(n) space |
| `edit_cost` | O(len(a) · len(b)) time, O(len(b)) space |
````
`meta`: `{"kind": "code.plan.text", "lang": "en", "generator": "kreatix-code-plan", "version": "0.1.0", "mode": "multi", "parts": ["brackets", "edit_distance"], "entries": ["valid_brackets", "edit_cost"], "problem_ids": ["9719044729f6", "e47365121fe9"], "difficulty": 2, "n_tests": 6, "checked_by": "each part: reference == brute-force oracle + large-input time limit; combined module self-test run; parts re-checked from the module"}`
## How it was checked
1. Every part is a problem from [Kreatix Code Hard](https://huggingface.co/datasets/KreatixLabs/kreatix-code-hard):
its solution agrees with an independent brute-force solver on every test input and passes a large-input time
limit.
2. The test plan's expected values are those verified outputs.
3. The module in the reply was run as written. It is kept only if:
- it printed the success line shown in the reply;
- every signature in the plan is defined in the module (checked through Python's AST);
- each part, called from the combined module, still returns the verified results.
## Size and repetition
| Split | Rows | en | fi |
|---|---|---|---|
| train | 1,865 | 1,320 | 545 |
| test | 300 | 205 | 95 |
About 3.2M tokens in total.
Each combination of reference solutions appears in at most one project. Parts do repeat across projects, since there
are 124 distinct solutions in all. `meta.problem_ids` lists them per row.
**Test split:** every test project includes a part from one of five families that never appear in train
(two-colouring, decode ways, next greater element, trapped water / container, running median).
`stats.json` has the counts per theme and mode; `samples.md` shows examples in full.
## Limitations
- **Independent parts.** The parts of a project do not call each other, so the plans teach structure, choice of
algorithm, edge cases, testing and build order, not interface design between modules.
- **Templates.** Plans follow one structure with varied wording. The Finnish text is awaiting review by native
speakers. Code identifiers and comments are in English in both languages.
- **Python only**, standard library only.
## License
Apache-2.0.123version https://git-lfs.github.com/spec/v1oid sha256:da77fd64f29e94b27081289839127ad7ac341dd57d96d368df6c143361303791size 1146393612345678910111213141516171819202122# Rebuilding kreatix-code-plan v0.1.0
Uses the problem generator of kreatix-code-hard, which must sit next to this folder
(`../kreatix-code-hard/generator/codegen`). Python 3.10+ only.
```bash
python generator/build_plan.py --candidates 7000 --workers 8 # data/train.jsonl (<= 5,000) + data/test.jsonl (<= 300)
python ../common/validate.py data/train.jsonl data/test.jsonl
python ../common/samples_stats.py kreatix-code-plan --n 21 --family-depth 3 # from the parent folder
```
- A project is 2 or 3 verified problems from one theme (`THEMES` in `build_plan.py`), all in one language.
- The plan is built from each problem's approach, key points, complexity and edge cases. Its test plan lists real
inputs with the verified expected outputs.
- The implementation is the parts' reference solutions in one module, imports merged, with the plan's tests as a
self-test under `if __name__ == "__main__":`. A row is kept only if:
- running the module prints the success line shown in the reply;
- every planned signature is defined at the module's top level (AST check);
- each part, called from the combined module, still returns the verified results on its inputs.
- Splits: about 8% of candidate projects are built as test projects; each includes a part from a family in
`codegen/base.py: HELDOUT`, and train projects never do. Each combination of solutions appears once.
- Seeds: candidate jobs use seeds 5,000,000+.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431"""Build kreatix-code-plan: plan a multi-part Python module before coding it, then implement it.
Each row is a small "project": 2-3 hard, verified problems from the kreatix-code-hard generator (same codegen package)
grouped under a theme (scheduling, routing, text, ...). The assistant writes a plan (module layout with signatures,
algorithm, key points and complexity per part, edge cases, a test plan with concrete expected values, build order)
and, depending on the mode, the implementation as one module with a self-test.
Checks per row:
- every part's reference solution equals its independent brute-force oracle and meets the large-input time limit;
- the combined module runs, its self-test prints the success line shown in the reply;
- every planned signature is defined in the module (AST), and every part, called from the combined module, still
returns the verified results on its test inputs (catches clashes between merged parts).
Splits: test projects contain at least one part from the families in codegen.base.HELDOUT, train projects none.
Each combination of reference solutions appears at most once.
python generator/build_plan.py --candidates 7000 --workers 8
"""
from __future__ import annotations
import argparse
import ast
import json
import os
import random
import re
import sys
from collections import Counter
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
CODEGEN = os.path.join(os.path.dirname(ROOT), "kreatix-code-hard", "generator")
sys.path.insert(0, CODEGEN)
from codegen import FAMILIES, HELDOUT, fmt_call, problem_id, verify # noqa: E402
from codegen.select import generate, select, write # noqa: E402
from codegen.render import complexity # noqa: E402
from codegen.runner import RunError, run_calls, run_script # noqa: E402
GEN, VERSION = "kreatix-code-plan", "0.1.0"
THEMES = {
"scheduling": {"module": "scheduling", "fams": ["merge_intervals", "meeting_rooms", "topo_order", "rate_limiter", "interval_greedy", "search_answer",
"bipartite"],
"en": "a scheduling toolkit for a booking app", "fi": "ajanvaraussovelluksen aikataulutyökalut"},
"routing": {"module": "routing", "fams": ["cheapest_path", "count_islands", "grid_paths", "robot_walk", "union_find", "dijkstra"],
"en": "a route-planning module for a delivery map", "fi": "toimituskartan reitinsuunnittelumoduuli"},
"text": {"module": "textkit", "fams": ["rle", "top_k_words", "brackets", "edit_distance", "longest_window", "palindromes",
"word_break", "common_sequence", "decode_ways"],
"en": "a small text-processing library", "fi": "pieni tekstinkäsittelykirjasto"},
"calc": {"module": "calc_core", "fams": ["expr_eval", "brackets", "primes_range", "subarray_count", "decode_ways"],
"en": "the core of a calculator service", "fi": "laskinpalvelun ydin"},
"backend": {"module": "memlayer", "fams": ["lru_cache", "rate_limiter", "time_map", "top_k_words", "prefix_counter", "range_sum",
"window_extreme", "running_median"],
"en": "the in-memory layer of an API backend", "fi": "API-taustapalvelun muistikerros"},
"numbers": {"module": "budget_math", "fams": ["knapsack", "coin_change", "lis", "primes_range", "stock_profit", "inversions",
"subarray_count", "next_greater"],
"en": "number utilities for a budgeting tool", "fi": "budjetointityökalun numeeriset apufunktiot"},
"grid": {"module": "gridtools", "fams": ["spiral", "count_islands", "grid_paths", "robot_walk", "histogram", "water"],
"en": "grid utilities for a tile-based game", "fi": "ruutupohjaisen pelin ruudukkotyökalut"},
}
T = {
"en": {
"intro": ["I'm building {theme} in Python, as one module `{module}.py`. It needs these parts:",
"I need {theme} in Python: a single module, `{module}.py`, with the following parts.",
"Project: {theme}. Everything goes in one Python module, `{module}.py`. Parts:"],
"scale": ["Inputs can be large, so every part has to be efficient.",
"This will run on large inputs, so naive solutions are not acceptable.",
"Assume large inputs: each part needs a properly efficient algorithm."],
"ask_plan": ["Before writing any code, give me a plan: the module layout with signatures, the algorithm and "
"complexity of each part, the edge cases, and the tests you would write.",
"Don't code yet. Plan it first: structure, algorithms with their complexity, edge cases, a test "
"plan with expected values, and the order you'd build it in.",
"Write a design plan for this module (no implementation yet): signatures, approach per part, "
"complexity, tricky cases and tests."],
"ask_both": ["Plan it first (layout, algorithms, complexity, edge cases, tests), then implement the whole "
"module with a self-test.",
"Start with a short design plan, then write the complete module including tests that run when the "
"file is executed.",
"Think through the design before coding: give the plan, then the implementation and its tests."],
"go": ["Looks good. Implement it.", "Great plan, go ahead and write the module.",
"Agreed. Now write the code, with the tests from your plan as a self-test.",
"OK, implement it exactly like that."],
"plan": "## Plan", "layout": "**Module layout** (`{module}.py`)", "approach": "Approach",
"key": "Key points", "cx": "Complexity", "edge": "Edge cases", "tests": "**Test plan**",
"order": "**Build order**", "impl": "## Implementation", "run": "Running the file:",
"basic": "basic case", "edge_t": "edge case", "seq": "call sequence",
"indep": "The parts are independent of each other, so each one gets its own function or class and its own "
"tests; nothing is shared except the module's imports.",
"deps": "Imports: {imps}.", "nodeps": "Imports: none, only built-ins.",
"build": ["Write `{name}` first: it is the simplest part.",
"Then `{name}`, and run its tests before moving on.",
"Finish with `{name}`, the hardest part ({why})."],
"build_mid": "Then `{name}`, and run its tests before moving on.",
"selftest": "Finally put all the tests under `if __name__ == \"__main__\":` so `python {module}.py` checks "
"everything.",
"ok": "all {n} tests passed",
"after": "All {n} tests from the plan pass, covering the basic and edge cases of every part.",
"summary": "| Part | Complexity |\n|---|---|",
"think": ["{k} independent parts: {names}.", "Hardest: `{hard}`. {hard_key}",
"Build the easiest part first, test each part before the next.",
"Each part gets a basic test plus edge-case tests with exact expected values."],
"hard_why": "it needs the most care",
"docstring": "{Theme}: {names}.",
},
"fi": {
"intro": ["Rakennan Pythonilla {theme}, yhtenä moduulina `{module}.py`. Siihen tarvitaan nämä osat:",
"Tarvitsen Pythonilla {theme}: yksi moduuli, `{module}.py`, jossa on seuraavat osat.",
"Projekti: {theme}. Kaikki menee yhteen Python-moduuliin, `{module}.py`. Osat:"],
"scale": ["Syötteet voivat olla suuria, joten jokaisen osan on oltava tehokas.",
"Tätä ajetaan suurilla syötteillä, joten naiivit ratkaisut eivät kelpaa.",
"Oleta suuret syötteet: jokainen osa tarvitsee kunnolla tehokkaan algoritmin."],
"ask_plan": ["Ennen kuin kirjoitat koodia, tee suunnitelma: moduulin rakenne ja allekirjoitukset, kunkin osan "
"algoritmi ja vaativuus, reunatapaukset ja testit, jotka kirjoittaisit.",
"Älä koodaa vielä. Suunnittele ensin: rakenne, algoritmit vaativuuksineen, reunatapaukset, "
"testisuunnitelma odotettuine arvoineen ja toteutusjärjestys.",
"Kirjoita tälle moduulille suunnitelma (ei vielä toteutusta): allekirjoitukset, lähestymistapa "
"osittain, vaativuus, hankalat tapaukset ja testit."],
"ask_both": ["Suunnittele ensin (rakenne, algoritmit, vaativuus, reunatapaukset, testit) ja toteuta sitten "
"koko moduuli itsetestin kanssa.",
"Aloita lyhyellä suunnitelmalla ja kirjoita sitten koko moduuli testeineen, jotka ajetaan, kun "
"tiedosto suoritetaan.",
"Mieti rakenne ennen koodausta: anna suunnitelma ja sitten toteutus testeineen."],
"go": ["Hyvältä näyttää. Toteuta se.", "Hyvä suunnitelma, kirjoita moduuli.",
"Sovittu. Kirjoita nyt koodi ja suunnitelman testit itsetestiksi.", "OK, toteuta juuri noin."],
"plan": "## Suunnitelma", "layout": "**Moduulin rakenne** (`{module}.py`)", "approach": "Lähestymistapa",
"key": "Tärkeää", "cx": "Vaativuus", "edge": "Reunatapaukset", "tests": "**Testisuunnitelma**",
"order": "**Toteutusjärjestys**", "impl": "## Toteutus", "run": "Tiedoston ajo:",
"basic": "perustapaus", "edge_t": "reunatapaus", "seq": "kutsusarja",
"indep": "Osat ovat toisistaan riippumattomia, joten kukin saa oman funktion tai luokan ja omat testit; "
"yhteistä on vain moduulin importit.",
"deps": "Importit: {imps}.", "nodeps": "Importit: ei yhtään, vain sisäänrakennetut.",
"build": ["Kirjoita ensin `{name}`: se on yksinkertaisin osa.",
"Sitten `{name}`, ja aja sen testit ennen kuin jatkat.",
"Lopuksi `{name}`, vaikein osa ({why})."],
"build_mid": "Sitten `{name}`, ja aja sen testit ennen kuin jatkat.",
"selftest": "Lopuksi kaikki testit lohkoon `if __name__ == \"__main__\":`, jolloin `python {module}.py` "
"tarkistaa kaiken.",
"ok": "all {n} tests passed",
"after": "Kaikki suunnitelman {n} testiä menevät läpi, ja ne kattavat jokaisen osan perus- ja reunatapaukset.",
"summary": "| Osa | Vaativuus |\n|---|---|",
"think": ["{k} toisistaan riippumatonta osaa: {names}.", "Vaikein: `{hard}`. {hard_key}",
"Rakennetaan helpoin osa ensin ja testataan jokainen osa ennen seuraavaa.",
"Jokainen osa saa perustestin ja reunatapaustestit tarkkoine odotusarvoineen."],
"hard_why": "se vaatii eniten huolellisuutta",
"docstring": "{Theme}: {names}.",
},
}
EDGE_PREFIX = ("edge cases:", "reunatapaukset:")
def title(p):
return p.statement.splitlines()[0].strip().strip("*").strip()
def task_text(p):
return p.statement.split("\n\n", 1)[-1].strip()
def split_plan(p):
keys, edges = [], []
for s in p.plan:
if s.lower().startswith(EDGE_PREFIX):
edges.append(s.split(":", 1)[1].strip())
else:
keys.append(s)
return keys, edges
def strip_imports(src):
imps, body = [], []
for line in src.splitlines():
if line.startswith(("import ", "from ")) and not body:
imps.append(line)
elif body or line.strip():
body.append(line)
return imps, "\n".join(body).rstrip()
def var_name(entry):
words = re.findall(r"[A-Z][a-z]*", entry)
return (words[-1] if words else entry).lower()
def sig_stub(p):
sig = p.signature.rstrip()
return sig + " ..." if p.kind == "function" and sig.endswith(":") else sig
def pick_tests(p, rng):
"""(lines of self-test code, list of (display, expected display, label)) for one part."""
lines, shown = [], []
if p.kind == "function":
calls = [(c, "basic") for c in p.small[:1]] + [(c, "edge_t") for c in rng.sample(p.edge, min(2, len(p.edge)))]
for c, label in calls:
exp, call = p.results[json.dumps(c)], fmt_call(p.entry, c)
lines.append(f"assert {call}" if exp is True else f"assert not {call}" if exp is False
else f"assert {call} == {exp!r}")
shown.append((call, repr(exp), label))
return lines, shown
call = min(p.edge, key=lambda c: len(c["ops"])) if p.edge else p.small[0]
var = var_name(p.entry)
outs = p.results[json.dumps(call)]
init = f"{var} = {p.entry}(" + ", ".join(repr(a) for a in call["init"]) + ")"
lines.append(init)
seq = [init]
for op, out in list(zip(call["ops"], outs))[:8]:
expr = f"{var}.{op[0]}(" + ", ".join(repr(a) for a in op[1:]) + ")"
if out is None:
lines.append(expr)
seq.append(expr)
else:
lines.append(f"assert {expr}" if out is True else f"assert not {expr}" if out is False
else f"assert {expr} == {out!r}")
seq.append(f"{expr} -> {out!r}")
shown.append(("; ".join(seq), None, "seq"))
return lines, shown
def n_asserts(lines):
return sum(1 for ln in lines if ln.startswith("assert"))
def make_project(rng, lang, want_test):
"""Train projects use no held-out family; test projects include at least one."""
if want_test:
theme_key = rng.choice([k for k, v in THEMES.items() if HELDOUT & set(v["fams"])])
else:
theme_key = rng.choice(list(THEMES))
th = THEMES[theme_key]
k = rng.choices([2, 3], [0.45, 0.55])[0]
normal = [f for f in th["fams"] if f not in HELDOUT]
if want_test:
held = rng.choice(sorted(HELDOUT & set(th["fams"])))
fams = [held] + rng.sample([f for f in th["fams"] if f != held], k - 1)
rng.shuffle(fams)
else:
fams = rng.sample(normal, k)
parts = []
for fam in fams:
p = FAMILIES[fam][0](rng, lang)
ok, why = verify(p)
if not ok:
return None, f"unverified {fam}"
parts.append(p)
entries = [p.entry for p in parts]
if len(set(entries)) != len(entries):
return None, "entry clash"
return (theme_key, th, parts), None
def build_module(th, parts, tests, lang, names):
t = T[lang]
imps, bodies = [], []
for p in parts:
i, b = strip_imports(p.solution)
imps += i
bodies.append(b)
plain = sorted({i for i in imps if i.startswith("import ")})
froms = sorted({i for i in imps if i.startswith("from ")})
theme = th[lang]
doc = '"""' + t["docstring"].format(Theme=theme[0].upper() + theme[1:], names=", ".join(names)) + '"""'
head = [doc, ""] + plain + froms
src = "\n".join(head).rstrip() + "\n\n\n" + "\n\n\n".join(bodies) + "\n\n\n"
n = sum(n_asserts(ls) for ls in tests)
main = ['if __name__ == "__main__":']
for ls in tests:
main += [" " + ln for ln in ls] + [""]
main.append(f' print("{t["ok"].format(n=n)}")')
return src + "\n".join(main) + "\n", plain + froms, n
def check_module(src, parts, expect_line):
code, out = run_script(src, timeout=30)
if code != 0 or out.strip() != expect_line:
return f"self-test failed: {out.strip()[-80:]}"
tree = ast.parse(src)
defined = {n.name for n in tree.body if isinstance(n, (ast.FunctionDef, ast.ClassDef))}
for p in parts:
if p.entry not in defined:
return f"missing {p.entry}"
calls = (p.small + p.edge)[:12]
try:
res, _ = run_calls(src, p.entry, calls, p.kind, timeout=20)
except RunError as e:
return f"combined run error {str(e)[:40]}"
for c, r in zip(calls, res):
if r.get("ok", object()) != p.results[json.dumps(c)]:
return f"combined result differs for {p.entry}"
return None
def plan_text(th, parts, shown_tests, imports, lang, rng, think):
t = T[lang]
module = th["module"]
names = [p.entry for p in parts]
order = sorted(range(len(parts)), key=lambda i: (parts[i].difficulty, i))
hard = parts[order[-1]]
out = []
if think:
hk, _ = split_plan(hard)
th_lines = [t["think"][0].format(k=len(parts), names=", ".join(f"`{n}`" for n in names)),
t["think"][1].format(hard=hard.entry, hard_key=hk[0] if hk else ""),
t["think"][2], t["think"][3]]
out.append("<think>\n" + "\n".join(f"- {s}" for s in th_lines) + "\n</think>")
out.append(t["plan"])
layout = "\n\n".join(sig_stub(p) for p in parts)
deps = t["deps"].format(imps=", ".join(f"`{i}`" for i in imports)) if imports else t["nodeps"]
out.append(t["layout"].format(module=module) + f"\n```python\n{layout}\n```\n{t['indep']} {deps}")
for idx, p in enumerate(parts, 1):
keys, edges = split_plan(p)
block = [f"**{idx}. `{p.entry}`** ({title(p)})", f"- {t['approach']}: {p.approach}"]
if keys:
block.append(f"- {t['key']}:\n" + "\n".join(f" - {s}" for s in keys))
block.append(f"- {t['cx']}: {complexity(p)}.")
if edges:
block.append(f"- {t['edge']}: {edges[0]}")
out.append("\n".join(block))
tl = [t["tests"]]
for p, shown in zip(parts, shown_tests):
for disp, exp, label in shown:
if exp is None:
tl.append(f"- `{disp}` ({t[label]})")
else:
tl.append(f"- `{disp}` → `{exp}` ({t[label]})")
out.append("\n".join(tl))
steps = []
for j, i in enumerate(order):
name = parts[i].entry
if j == 0:
steps.append(t["build"][0].format(name=name))
elif j == len(order) - 1:
steps.append(t["build"][2].format(name=name, why=t["hard_why"]))
else:
steps.append(t["build_mid"].format(name=name))
steps.append(t["selftest"].format(module=module))
out.append(t["order"] + "\n" + "\n".join(f"{j}. {s}" for j, s in enumerate(steps, 1)))
return "\n\n".join(out)
def impl_text(th, parts, src, n, out_line, lang):
t = T[lang]
summary = t["summary"] + "\n" + "\n".join(f"| `{p.entry}` | {complexity(p)} |" for p in parts)
return "\n\n".join([f"```python\n{src.rstrip()}\n```",
f"{t['run']}\n```\n$ python {th['module']}.py\n{out_line}\n```",
t["after"].format(n=n), summary])
def user_text(th, parts, lang, rng, mode):
t = T[lang]
lines = [rng.choice(t["intro"]).format(theme=th[lang], module=th["module"]), ""]
for i, p in enumerate(parts, 1):
lines.append(f"{i}. **{title(p)}.** {task_text(p)}")
lines += ["", rng.choice(t["scale"]), rng.choice(t["ask_plan"] if mode in ("plan", "multi") else t["ask_both"])]
return "\n".join(lines)
def make_rows(args):
seed, n, langs = args
rng = random.Random(seed)
rows, drops = [], Counter()
while len(rows) < n:
lang = rng.choices(list(langs), list(langs.values()))[0]
want_test = rng.random() < 0.08
proj, why = make_project(rng, lang, want_test)
if proj is None:
drops[why] += 1
continue
theme_key, th, parts = proj
mode = rng.choices(["plan", "both", "multi"], [0.35, 0.35, 0.30])[0]
tests, shown = zip(*[pick_tests(p, rng) for p in parts])
names = [p.entry for p in parts]
src, imports, n_t = build_module(th, parts, tests, lang, names)
out_line = T[lang]["ok"].format(n=n_t)
err = check_module(src, parts, out_line)
if err:
drops[err[:50]] += 1
continue
think = rng.random() < 0.5
plan = plan_text(th, parts, shown, imports, lang, rng, think)
user = user_text(th, parts, lang, rng, mode)
impl = impl_text(th, parts, src, n_t, out_line, lang)
if mode == "plan":
msgs = [{"role": "user", "content": user}, {"role": "assistant", "content": plan}]
elif mode == "both":
msgs = [{"role": "user", "content": user},
{"role": "assistant", "content": plan + "\n\n" + T[lang]["impl"] + "\n\n" + impl}]
else:
msgs = [{"role": "user", "content": user}, {"role": "assistant", "content": plan},
{"role": "user", "content": rng.choice(T[lang]["go"])}, {"role": "assistant", "content": impl}]
rows.append({"messages": msgs,
"meta": {"kind": f"code.plan.{theme_key}", "lang": lang, "generator": GEN, "version": VERSION,
"mode": mode, "parts": [p.family for p in parts], "entries": names,
"problem_ids": [problem_id(p) for p in parts],
"split": "test" if want_test else "train",
"difficulty": max(p.difficulty for p in parts), "n_tests": n_t,
"checked_by": "each part: reference == brute-force oracle + large-input time limit; "
"combined module self-test run; parts re-checked from the module"}})
return rows, drops
def main():
try:
sys.stdout.reconfigure(encoding="utf-8")
except AttributeError:
pass
ap = argparse.ArgumentParser()
ap.add_argument("--candidates", type=int, default=7000)
ap.add_argument("--train-max", type=int, default=5000)
ap.add_argument("--test-max", type=int, default=300)
ap.add_argument("--workers", type=int, default=4)
ap.add_argument("--langs", default="en=0.7,fi=0.3")
ap.add_argument("--out", default=os.path.join(ROOT, "data"))
a = ap.parse_args()
langs = {k: float(v) for k, v in (p.split("=") for p in a.langs.split(","))}
rows, drops = generate(make_rows, a.candidates, a.workers, langs, 5_000_000)
out, sel = select(rows, lambda r: tuple(sorted(r["meta"]["problem_ids"])), lambda r: r["meta"]["kind"],
{"train": (1, 10**9, a.train_max), "test": (1, 10**9, a.test_max)})
for split in ("test", "train"):
rs = out[split]
write(a.out, "codeplan", split, rs)
print(f"{split}: {len(rs):,} rows; langs {dict(Counter(r['meta']['lang'] for r in rs))}", flush=True)
print(f" themes {dict(Counter(r['meta']['kind'].split('.')[2] for r in rs).most_common())}", flush=True)
print(f" modes {dict(Counter(r['meta']['mode'] for r in rs))}", flush=True)
print(f" families used {len({f for r in rs for f in r['meta']['parts']})}", flush=True)
print(f"candidates {len(rows):,}; generation drops {dict(drops.most_common(6))}; selection {dict(sel)}", flush=True)
if __name__ == "__main__":
main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283{
"validator": {
"files": {
"kreatix-code-plan\\data\\test.jsonl": {
"rows": 300,
"langs": {
"en": 205,
"fi": 95
},
"kinds": {
"code": 300
},
"chars": 1602375,
"max_chars": 8421,
"tool_calls": 0,
"rows_with_think": 164,
"images": 0,
"dup_prompts": 0,
"dup_ids": 0,
"codename_rows": 0,
"kreatix_mention_rows": 0,
"errors": 0,
"approx_tokens": 445104
},
"kreatix-code-plan\\data\\train.jsonl": {
"rows": 1865,
"langs": {
"en": 1320,
"fi": 545
},
"kinds": {
"code": 1865
},
"chars": 10012653,
"max_chars": 8872,
"tool_calls": 0,
"rows_with_think": 933,
"images": 0,
"dup_prompts": 0,
"dup_ids": 0,
"codename_rows": 0,
"kreatix_mention_rows": 0,
"errors": 0,
"approx_tokens": 2781292
}
},
"warnings": [],
"errors": 0
},
"counts": {
"train": {
"rows": 1865,
"langs": {
"en": 1320,
"fi": 545
},
"kinds": {
"code.plan.text": 578,
"code.plan.numbers": 291,
"code.plan.backend": 284,
"code.plan.scheduling": 250,
"code.plan.routing": 247,
"code.plan.grid": 178,
"code.plan.calc": 37
}
},
"test": {
"rows": 300,
"langs": {
"en": 205,
"fi": 95
},
"kinds": {
"code.plan.text": 67,
"code.plan.numbers": 53,
"code.plan.backend": 50,
"code.plan.grid": 49,
"code.plan.scheduling": 45,
"code.plan.calc": 36
}
}
}
}.gitattributes+1
README.mdAdded+216
assets/code-plan-themes.pngAdded

Large File Pointer Details
- SHA256: 8ae09c3c4e6ff51203346c4a95e252f90b3b2681b24e8c5d0b6dfbf0416a03ed
- Pointer size: 130 Bytes
- Size of remote file: 45.1 kB
data/test.jsonlAdded
data/train.jsonlAdded+3
generator/GENERATE.mdAdded+22
generator/build_plan.pyAdded+431
samples.mdAdded
stats.jsonAdded+83