mo-trace 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
matrace/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """nbdev-style literate programming for marimo notebooks."""
2
+ __version__ = "0.1.0"
3
+ from .core import nb_export, nb_update, nb_test, nb_clean
matrace/cli.py ADDED
@@ -0,0 +1,151 @@
1
+ """Command line entry points: matrace (the guide), matrace-export, matrace-prepare, matrace-clean."""
2
+
3
+ import argparse, sys
4
+ from . import __version__
5
+ from .core import nb_clean, nb_export, nb_test, nb_update, clean_text
6
+
7
+ GUIDE = '''
8
+ matrace is nbdev for marimo notebooks: write code, docs and tests in a marimo
9
+ notebook; matrace turns chosen cells into a regular Python package and keeps
10
+ the two in sync.
11
+
12
+ SETUP
13
+ Add to your project's pyproject.toml:
14
+
15
+ [tool.matrace]
16
+ lib_path = "mypkg" # package to generate (default: [project].name)
17
+ nbs_path = "jobs" # where notebooks live (default: jobs)
18
+
19
+ IN A MARIMO NOTEBOOK
20
+ Directives are `#|` comments on the first lines of a cell:
21
+
22
+ #| default_exp core once per notebook (the setup cell is a good
23
+ place): `#| export` cells go to mypkg/core.py
24
+ #| export write this cell to the default module and list
25
+ its public names in __all__
26
+ #| export io.fmt write this cell to mypkg/io/fmt.py instead
27
+ #| exporti [module] export, but leave out of __all__
28
+ #| eval: false skip this cell when testing
29
+
30
+ Any cell without an export directive is a test: plain `assert`s next to
31
+ the code they check. They run with the notebook, never land in the package.
32
+
33
+ with app.setup:
34
+ #| default_exp core
35
+ import numpy as np
36
+
37
+ @app.cell
38
+ def _():
39
+ #| export
40
+ def norm(x): return x / np.linalg.norm(x)
41
+ return (norm,)
42
+
43
+ @app.cell
44
+ def _(norm):
45
+ assert norm(np.ones(4)).sum() == 2 # a test
46
+ return
47
+
48
+ Import your own package absolutely (`from mypkg.core import norm`) only
49
+ from *other* notebooks; within one notebook just use the name, since marimo
50
+ forbids defining a name twice. matrace adds the imports a module needs
51
+ (setup-cell imports, names exported to sibling modules) automatically.
52
+ Underscore names (`_tmp`) are cell-local in marimo: use them in tests.
53
+
54
+ IN THE CLI
55
+ matrace-export notebooks -> mypkg/*.py
56
+ matrace-export --update edits made in mypkg/*.py -> back into notebooks
57
+ matrace-prepare export, run all notebooks' tests in parallel
58
+ (one process each, cwd = notebook dir), clean;
59
+ exits 1 and names any failing notebook
60
+ matrace-clean normalize notebooks (marimo's canonical format,
61
+ no trailing whitespace) to keep diffs small
62
+ matrace-convert NB -o DIR replay a notebook as a Pi coding-agent rollout
63
+ and write it as Tinker training data (SFT and
64
+ on-policy distillation) for Inkling 2 Small;
65
+ needs `pip install "mo-trace[tinker]"`
66
+ Run any command with --help for its options.
67
+
68
+ Typical loop:
69
+ marimo edit jobs/00_core.py write code + tests
70
+ matrace-prepare before committing
71
+ # edited mypkg/core.py directly (IDE, refactor tool)? then:
72
+ matrace-export --update && matrace-prepare
73
+
74
+ Generated modules start with `# AUTOGENERATED! DO NOT EDIT!` and carry
75
+ `# %% ../jobs/00_core.py #3` markers mapping each block to its cell. Only
76
+ edit inside those blocks, and run --update before changing the notebook.
77
+
78
+ ORGANIZING NOTEBOOKS
79
+ jobs/
80
+ 00_core.py #| default_exp core foundations, no internal deps
81
+ 01_data.py #| default_exp data may `from mypkg.core import ...`
82
+ 02_model.py #| default_exp model
83
+ _scratch.py ignored: names starting with _ or . are skipped
84
+ sub/03_x.py subfolders work (recursive)
85
+ mypkg/ generated; commit it alongside the notebooks
86
+
87
+ - One notebook per module, numbered in dependency order, is the default.
88
+ - One notebook can also fan out into several files with `#| export <mod>`
89
+ (see examples/tinylm: one notebook -> data, tokenizer, model, train).
90
+ - Several notebooks may export into the same module; it is rebuilt whole.
91
+ - Keep notebooks fast: they are your test suite. Mark slow or interactive
92
+ cells `#| eval: false`.
93
+ - After reordering exported cells, run matrace-export before --update
94
+ (cells are matched by position; matrace refuses mismatched updates).
95
+ '''
96
+
97
+ def main_cli(argv=None):
98
+ p = argparse.ArgumentParser('matrace', description=f'matrace {__version__}: nbdev-style literate programming for '
99
+ 'marimo notebooks', epilog=GUIDE, formatter_class=argparse.RawDescriptionHelpFormatter)
100
+ p.add_argument('--version', action='version', version=__version__)
101
+ p.parse_args(argv)
102
+ p.print_help()
103
+
104
+ def export_cli(argv=None):
105
+ p = argparse.ArgumentParser('matrace-export', description='Export marimo notebooks to Python modules '
106
+ '(like nbdev-export), or with --update sync module edits back (like nbdev-update)')
107
+ p.add_argument('path', nargs='?', help='notebook or directory to export (default: nbs_path); '
108
+ 'with --update, a module or directory (default: lib_path)')
109
+ p.add_argument('--update', action='store_true', help='propagate edits in exported modules back to notebooks')
110
+ a = p.parse_args(argv)
111
+ for f in (nb_update if a.update else nb_export)(a.path): print(f'{"updated" if a.update else "exported"} {f}')
112
+
113
+ def clean_cli(argv=None):
114
+ p = argparse.ArgumentParser('matrace-clean', description='Normalize marimo notebooks to avoid merge conflicts')
115
+ p.add_argument('fname', nargs='?', help='notebook or directory to clean (default: nbs_path)')
116
+ p.add_argument('--stdin', action='store_true', help='clean a notebook read from stdin to stdout (git filter)')
117
+ a = p.parse_args(argv)
118
+ if a.stdin: return sys.stdout.write(clean_text(sys.stdin.read()))
119
+ for f in nb_clean(a.fname): print(f'cleaned {f}')
120
+
121
+ def convert_cli(argv=None):
122
+ p = argparse.ArgumentParser('matrace-convert', description='Replay a marimo notebook as a Pi coding-agent rollout '
123
+ '(real tool executions) and write it as Tinker training data for Inkling 2 Small: '
124
+ 'pi_session.jsonl, messages.json, sft.jsonl, opd_prompts.jsonl')
125
+ p.add_argument('notebook', help='marimo notebook inside a matrace project')
126
+ p.add_argument('-o', '--out', default='traces', help='output directory (default: traces)')
127
+ p.add_argument('--model', default='thinkingmachines/Inkling-2-Small', help='Tinker model whose renderer to use')
128
+ p.add_argument('--effort', type=float, default=0.0, help='Inkling thinking-effort conditioning in [0, 1). Reasoning '
129
+ 'comes only from the notebook\'s markdown and is usually short, so the default is 0')
130
+ p.add_argument('--cwd', default=None, help='working directory shown in the trace (default: /home/user/<project>)')
131
+ p.add_argument('--no-tinker', action='store_true', help='only write the Pi session and chat messages')
132
+ a = p.parse_args(argv)
133
+ tinker = not a.no_tinker
134
+ if tinker:
135
+ try: import tinker_cookbook # noqa: F401
136
+ except ImportError: sys.exit('matrace-convert: Tinker output needs `pip install "mo-trace[tinker]"` (or pass --no-tinker)')
137
+ from .convert import convert
138
+ ro, files = convert(a.notebook, a.out, model=a.model, effort=a.effort, cwd=a.cwd, tinker=tinker)
139
+ n = sum(m['role'] == 'assistant' for m in ro['messages'])
140
+ print(f'{a.notebook}: {n} assistant turns, {n - 1} tool calls')
141
+ for f in files: print(f'wrote {f}')
142
+
143
+ def prepare_cli(argv=None):
144
+ p = argparse.ArgumentParser('matrace-prepare', description='Export, test (in parallel) and clean notebooks')
145
+ p.add_argument('--n_workers', type=int, default=None, help='parallel test processes (default: min(cpus, 8))')
146
+ p.add_argument('--timing', action='store_true', help='print how long each notebook took')
147
+ p.add_argument('--timeout', type=float, default=None, help='seconds before a notebook test is killed')
148
+ a = p.parse_args(argv)
149
+ nb_export()
150
+ if not nb_test(n_workers=a.n_workers, timing=a.timing, timeout=a.timeout): sys.exit(1)
151
+ nb_clean()
matrace/convert.py ADDED
@@ -0,0 +1,380 @@
1
+ """matrace-convert: replay a marimo notebook as a Pi coding-agent rollout, then render it as Tinker training data.
2
+
3
+ The rollout is what Pi (https://github.com/earendil-works/pi-mono) would record if an agent built the notebook
4
+ step by step: explore the project, `write` the first cells, `edit` in each further exported cell plus its tests,
5
+ run `matrace-prepare` after every step, and finally check the generated package. Every tool call is actually
6
+ executed in a scratch copy of the project, so every tool result is real output.
7
+
8
+ Outputs (in `out_dir`):
9
+ pi_session.jsonl the rollout as a Pi v3 session file
10
+ messages.json the same conversation in OpenAI/tinker-cookbook message format, plus Pi's system prompt and tools
11
+ sft.jsonl one Tinker Datum (whole trajectory, loss on assistant tokens only) rendered for Inkling 2 Small
12
+ opd_prompts.jsonl one record per assistant turn: the prompt state, its tokens, the reference turn and the
13
+ workspace files at that point; for on-policy distillation (student samples, teacher scores)
14
+ """
15
+
16
+ import ast, hashlib, json, os, shutil, subprocess, sys, tempfile
17
+ from dataclasses import replace
18
+ from datetime import UTC, datetime
19
+ from pathlib import Path
20
+
21
+ from marimo._ast.codegen import generate_filecontents_from_ir
22
+ from marimo._ast.compiler import compile_cell
23
+
24
+ from .core import _EXPORTS, _md_text, _re_gen, get_config, read_nb
25
+
26
+ MODEL = 'thinkingmachines/Inkling-2-Small'
27
+
28
+ # ---------------------------------------------------------------- Pi harness (mirrors @earendil-works/pi-coding-agent 1.5.2)
29
+
30
+ PI_VERSION = '1.5.2'
31
+ PI_INSTALL = '/usr/local/lib/node_modules/@earendil-works/pi-coding-agent'
32
+ MAX_LINES, MAX_BYTES = 2000, 50 * 1024
33
+
34
+ def _obj(props, required): return {'type': 'object', 'properties': props, 'required': required}
35
+
36
+ TOOLS = [ # Pi's default tool set, in Pi's order, with its descriptions and parameter schemas
37
+ {'name': 'read', 'description': f'Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to {MAX_LINES} lines or {MAX_BYTES // 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.',
38
+ 'parameters': _obj({'path': {'type': 'string', 'description': 'Path to the file to read (relative or absolute)'},
39
+ 'offset': {'type': 'number', 'description': 'Line number to start reading from (1-indexed)'},
40
+ 'limit': {'type': 'number', 'description': 'Maximum number of lines to read'}}, ['path'])},
41
+ {'name': 'bash', 'description': f'Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last {MAX_LINES} lines or {MAX_BYTES // 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.',
42
+ 'parameters': _obj({'command': {'type': 'string', 'description': 'Shell command to execute'},
43
+ 'timeout': {'type': 'number', 'description': 'Timeout in seconds (optional, no default timeout)'}}, ['command'])},
44
+ {'name': 'edit', 'description': 'Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.',
45
+ 'parameters': _obj({'path': {'type': 'string', 'description': 'Path to the file to edit (relative or absolute)'},
46
+ 'edits': {'type': 'array', 'description': 'One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead.',
47
+ 'items': _obj({'oldText': {'type': 'string', 'description': 'Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call.'},
48
+ 'newText': {'type': 'string', 'description': 'Replacement text for this targeted edit.'}}, ['oldText', 'newText'])}}, ['path', 'edits'])},
49
+ {'name': 'write', 'description': "Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.",
50
+ 'parameters': _obj({'path': {'type': 'string', 'description': 'Path to the file to write (relative or absolute)'},
51
+ 'content': {'type': 'string', 'description': 'Content to write to the file'}}, ['path', 'content'])},
52
+ ]
53
+
54
+ def pi_system_prompt(cwd):
55
+ "Pi's default system prompt for the read/bash/edit/write tool set (see core/system-prompt.js)"
56
+ rules = ['Use bash for file operations like ls, rg, find', 'Use read to examine files instead of cat or sed.',
57
+ 'Use edit for targeted changes. Batch changes to one file in a single call.',
58
+ 'Each edits[].oldText must exactly and uniquely match the original file. Keep matches short and non-overlapping; merge nearby changes without including large unchanged regions.',
59
+ 'Use write only for new files or complete rewrites.', 'Be concise in your responses',
60
+ 'Show file paths clearly when working with files']
61
+ tools = ['- read: Read file contents', '- bash: Execute bash commands (ls, grep, find, etc.)',
62
+ '- edit: Make precise file edits with exact text replacement, including multiple disjoint edits in one call',
63
+ '- write: Create or overwrite files']
64
+ docs = f'''Pi documentation (read only when the user asks about the harness itself, its SDK, extensions, themes, skills, or TUI):
65
+ - Main documentation: {PI_INSTALL}/README.md
66
+ - Additional docs: {PI_INSTALL}/docs
67
+ - Examples: {PI_INSTALL}/examples (extensions, custom tools, SDK)
68
+ - When reading pi docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory
69
+ - When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), packages (docs/packages.md), environment variables (docs/environment-variables.md), MCP servers (docs/mcp.md), codemode scripts and non-LLM models such as classifiers and image models (docs/codemode.md)
70
+ - Before implementing harness changes, read the relevant docs and examples in full, following related cross-references.'''
71
+ sec = lambda name, body: f'<{name}>\n{body}\n</{name}>'
72
+ return '\n\n'.join(['You are a coding assistant running inside pi, a coding agent harness. Help users inspect files, run commands, and modify code.',
73
+ sec('tools', '\n'.join(tools) + '\n\nAdditional tools may be available.'),
74
+ sec('rules', '\n'.join(f'- {r}' for r in rules)), sec('docs', docs), sec('cwd', cwd)])
75
+
76
+ class Workspace:
77
+ "Pi's tools, executed for real in a scratch directory; `cwd` is the path the transcript shows instead"
78
+ def __init__(self, root, cwd): self.root, self.cwd = Path(root), cwd
79
+
80
+ def _clip(self, text):
81
+ lines = text.split('\n')
82
+ if len(lines) > MAX_LINES: text = '\n'.join(lines[-MAX_LINES:])
83
+ return text.encode()[-MAX_BYTES:].decode(errors='ignore')
84
+
85
+ def read(self, path):
86
+ return self._clip((self.root/path).read_text()), False
87
+
88
+ def write(self, path, content):
89
+ p = self.root/path
90
+ p.parent.mkdir(parents=True, exist_ok=True)
91
+ p.write_text(content)
92
+ return f'Successfully wrote to {path}', False
93
+
94
+ def edit(self, path, edits):
95
+ p = self.root/path
96
+ text = p.read_text()
97
+ for e in edits:
98
+ assert text.count(e['oldText']) == 1, f'oldText not unique in {path}: {e["oldText"]!r}'
99
+ text = text.replace(e['oldText'], e['newText'])
100
+ p.write_text(text)
101
+ return f'Successfully replaced {len(edits)} block(s) in {path}.', False
102
+
103
+ def bash(self, command):
104
+ env = {**os.environ, 'PATH': f'{Path(sys.executable).parent}{os.pathsep}{os.environ.get("PATH", "")}',
105
+ 'PYTHONDONTWRITEBYTECODE': '1'}
106
+ r = subprocess.run(command, shell=True, executable='/bin/bash', cwd=self.root, env=env, text=True,
107
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
108
+ out = self._clip(r.stdout.replace(str(self.root.resolve()), self.cwd).replace(str(self.root), self.cwd).rstrip('\n'))
109
+ if r.returncode: return f'{out}\n\nCommand exited with code {r.returncode}' if out else f'Command exited with code {r.returncode}', True
110
+ return out or '(no output)', False
111
+
112
+ # ---------------------------------------------------------------- planning: notebook -> steps
113
+
114
+ def _topo(cells, info):
115
+ "Cell indices in dataflow order, ties broken by position in the file"
116
+ owner = {n: c.idx for c in cells for n in info[c.idx].defs}
117
+ deps = {c.idx: {owner[n] for n in info[c.idx].refs if n in owner} - {c.idx} for c in cells}
118
+ done, order = set(), []
119
+ while len(order) < len(cells):
120
+ i = next((i for i in sorted(deps) if i not in done and deps[i] <= done), None)
121
+ if i is None: raise ValueError('notebook has a dependency cycle')
122
+ done.add(i); order.append(i)
123
+ return order
124
+
125
+ def plan(nb):
126
+ "Group the notebook's cells into agent steps: each exported cell, with its markdown before and its tests after"
127
+ _, ir, cells = read_nb(nb)
128
+ info = {c.idx: compile_cell(c.body, cell_id=str(c.idx)) for c in cells}
129
+ steps, cur, md = [], {'cells': [], 'md': [], 'exports': [], 'tests': []}, []
130
+ for i in _topo(cells, info):
131
+ c = cells[i]
132
+ if (t := _md_text(c.code)) is not None: md.append((i, t)); continue
133
+ exported = bool(_EXPORTS & c.dirs.keys())
134
+ if exported and cur['exports']:
135
+ steps.append(cur); cur = {'cells': [], 'md': [], 'exports': [], 'tests': []}
136
+ cur['cells'] += [j for j, _ in md] + [i]; cur['md'] += [t for _, t in md]; md = []
137
+ if exported: cur['exports'].append(i)
138
+ elif c.body.strip() and ir.cells[i].name != 'setup' and 'import marimo' not in c.body: cur['tests'].append(i)
139
+ cur['cells'] += [j for j, _ in md]; cur['md'] += [t for _, t in md]
140
+ steps.append(cur)
141
+ return ir, cells, info, steps
142
+
143
+ def _nb_text(ir, idxs, orig):
144
+ "Notebook source containing only cells `idxs`, serialized by marimo"
145
+ text = generate_filecontents_from_ir(replace(ir, cells=[ir.cells[i] for i in idxs]))
146
+ return _re_gen.sub(lambda _: m[0], text, count=1) if (m := _re_gen.search(orig)) else text
147
+
148
+ def _edit_for(old, new):
149
+ "Smallest Pi edit (unique oldText) turning `old` into `new`, or None if a rewrite is simpler"
150
+ p = 0
151
+ while p < min(len(old), len(new)) and old[p] == new[p]: p += 1
152
+ s = 0
153
+ while s < min(len(old), len(new)) - p and old[-1 - s] == new[-1 - s]: s += 1
154
+ a, b = old[p:len(old) - s], new[p:len(new) - s]
155
+ # back up to a line start, then grow a line at a time (forward, else backward) until oldText is non-empty and unique
156
+ while p and old[p - 1] != '\n': p -= 1; a, b = old[p] + a, new[p] + b
157
+ end = len(old) - s
158
+ while not a or old.count(a) != 1:
159
+ if end < len(old):
160
+ nxt = old.find('\n', end) + 1 or len(old)
161
+ a, b, end = a + old[end:nxt], b + old[end:nxt], nxt
162
+ elif p:
163
+ prv = old.rfind('\n', 0, p - 1) + 1
164
+ a, b, p = old[prv:p] + a, old[prv:p] + b, prv
165
+ else: return None
166
+ assert old.replace(a, b) == new
167
+ return {'oldText': a, 'newText': b}
168
+
169
+ def _api(cells, idxs):
170
+ "[(name, first docstring line)] for public top-level names in cells `idxs`"
171
+ res = []
172
+ for i in idxs:
173
+ for o in ast.parse(cells[i].body).body:
174
+ if isinstance(o, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) and not o.name.startswith('_'):
175
+ res.append((o.name, (ast.get_docstring(o) or '').split('\n')[0]))
176
+ elif isinstance(o, (ast.Assign, ast.AnnAssign)):
177
+ for t in (o.targets if isinstance(o, ast.Assign) else [o.target]):
178
+ res += [(n.id, '') for n in ast.walk(t) if isinstance(n, ast.Name) and not n.id.startswith('_')]
179
+ return res
180
+
181
+ def _module(c, default): return c.dirs[(_EXPORTS & c.dirs.keys()).pop()] or default
182
+
183
+ # ---------------------------------------------------------------- rollout
184
+
185
+ def rollout(nb, cwd=None):
186
+ "Replay notebook `nb` as a Pi rollout. Returns (system prompt, Pi messages, workspace snapshot before each assistant turn)"
187
+ nb = Path(nb).resolve()
188
+ cfg = get_config(nb)
189
+ orig = nb.read_text()
190
+ ir, cells, info, steps = plan(nb)
191
+ default = next((c.dirs['default_exp'] for c in cells if 'default_exp' in c.dirs), None)
192
+ nbrel, lib = nb.relative_to(cfg.root).as_posix(), cfg.lib_name
193
+ cwd = cwd or f'/home/user/{cfg.root.name}'
194
+ title = next((t for c in cells if (t := _md_text(c.code)) and t.startswith('# ')), '')
195
+ mods = {}
196
+ for st in steps:
197
+ for i in st['exports']: mods.setdefault(_module(cells[i], default), []).append(i)
198
+
199
+ lines = []
200
+ if title:
201
+ summ = next((l[2:].strip() for l in title.splitlines() if l.startswith('> ')), '')
202
+ lines.append(f'{title.splitlines()[0][2:]}' + (f': {summ}' if summ else '') + '\n')
203
+ lines.append(f'Build the `{lib}` package as a marimo notebook at `{nbrel}`, using matrace: cells marked '
204
+ f'`#| export <module>` are written to `{lib}/<module>.py`, and every other cell is a test.\n\nThe package should provide:')
205
+ for mod, idxs in mods.items():
206
+ api = ', '.join(f'`{n}`' + (f' ({d.rstrip(".")})' if d else '') for n, d in _api(cells, idxs))
207
+ lines.append(f'- `{lib}/{mod.replace(".", "/")}.py`: {api}')
208
+ lines.append('\nWrite tests as ordinary notebook cells next to the code they check, and finish with `matrace-prepare` passing.')
209
+ task = '\n'.join(lines)
210
+
211
+ tmp = Path(tempfile.mkdtemp(prefix='matrace_convert_'))
212
+ try:
213
+ for f in cfg.root.iterdir(): # the project as the agent finds it: top-level files only, no notebooks, no package
214
+ if f.is_file() and not f.name.startswith('.'): shutil.copy(f, tmp/f.name)
215
+ ws = Workspace(tmp, cwd)
216
+ msgs, snaps, ts = [], [], [1_767_225_600_000] # 2026-01-01T00:00:00Z, +1s per message: deterministic
217
+ def tick(): ts[0] += 1000; return ts[0]
218
+ def user(text): msgs.append({'role': 'user', 'content': text, 'timestamp': tick()})
219
+ def turn(text, tool=None, args=None, thinking=None):
220
+ snaps.append({p.relative_to(tmp).as_posix(): p.read_text() for p in sorted(tmp.rglob('*'))
221
+ if p.is_file() and '__pycache__' not in p.parts})
222
+ content = [{'type': 'thinking', 'thinking': thinking}] if thinking else []
223
+ if text: content.append({'type': 'text', 'text': text})
224
+ if tool is None:
225
+ msgs.append({'role': 'assistant', 'content': content, 'stopReason': 'stop', 'timestamp': tick()}); return
226
+ call_id = f'call_{len(msgs):03d}'
227
+ content.append({'type': 'toolCall', 'id': call_id, 'name': tool, 'arguments': args})
228
+ msgs.append({'role': 'assistant', 'content': content, 'stopReason': 'toolUse', 'timestamp': tick()})
229
+ out, err = getattr(ws, tool)(**args)
230
+ msgs.append({'role': 'toolResult', 'toolCallId': call_id, 'toolName': tool,
231
+ 'content': [{'type': 'text', 'text': out}], 'isError': err, 'timestamp': tick()})
232
+ return out, err
233
+
234
+ user(task)
235
+ turn("I'll look at the project first.", 'bash', {'command': 'find . -type f -not -path "./.*" | sort'})
236
+ for f in sorted(p.name for p in tmp.iterdir() if p.suffix in ('.toml', '.md', '.cfg', '.txt')):
237
+ turn('', 'read', {'path': f})
238
+ prefix, text = [], ''
239
+ for k, st in enumerate(steps):
240
+ prefix += st['cells']
241
+ new = _nb_text(ir, prefix, orig)
242
+ names = [n for i in st['exports'] for n, _ in _api(cells, [i])]
243
+ where = ', '.join(dict.fromkeys(f'`{lib}/{_module(cells[i], default).replace(".", "/")}.py`' for i in st['exports']))
244
+ think = '\n\n'.join(st['md']) # the notebook's markdown is the agent's reasoning for this step
245
+ say = (f'Adding {", ".join(f"`{n}`" for n in names)} for {where}' if names else 'Setting up the notebook') + \
246
+ (f', with {len(st["tests"])} test cell{"s" * (len(st["tests"]) > 1)}.' if st['tests'] else '.')
247
+ if k == 0 or not (e := _edit_for(text, new)): turn(say, 'write', {'path': nbrel, 'content': new}, think)
248
+ else: turn(say, 'edit', {'path': nbrel, 'edits': [e]}, think)
249
+ text = new
250
+ out, err = turn('', 'bash', {'command': 'matrace-prepare'})
251
+ if err: raise RuntimeError(f'step {k} of {nb.name} fails matrace-prepare:\n{out}')
252
+ mod_names = list(mods)
253
+ check = f'python -c "import importlib\nfor m in {mod_names!r}: print(m, importlib.import_module(\'{lib}.\' + m).__all__)"'
254
+ out, err = turn('All steps pass. Checking that the generated package imports cleanly.', 'bash', {'command': check})
255
+ if err: raise RuntimeError(f'generated package does not import:\n{out}')
256
+ summary = '\n'.join(f'- `{lib}/{m.replace(".", "/")}.py`: ' + ', '.join(f'`{n}`' for n, _ in _api(cells, idxs))
257
+ for m, idxs in mods.items())
258
+ turn(f'Done. `{nbrel}` builds the `{lib}` package with matrace, and `matrace-prepare` passes.\n\n{summary}')
259
+ final = (tmp/nbrel).read_text()
260
+ finally: shutil.rmtree(tmp, ignore_errors=True)
261
+ return {'system': pi_system_prompt(cwd), 'tools': TOOLS, 'messages': msgs, 'snapshots': snaps, 'cwd': cwd,
262
+ 'notebook': nbrel, 'final_notebook': final, 'source_sha256': hashlib.sha256(orig.encode()).hexdigest()}
263
+
264
+ # ---------------------------------------------------------------- formats
265
+
266
+ def to_pi_session(ro):
267
+ "The rollout as Pi v3 session JSONL lines (linear tree: each entry's parent is the previous one)"
268
+ iso = lambda ms: f'{datetime.fromtimestamp(ms / 1000, UTC):%Y-%m-%dT%H:%M:%S.000Z}'
269
+ sid = hashlib.sha256(ro['source_sha256'].encode()).hexdigest()
270
+ t0 = ro['messages'][0]['timestamp'] - 1000
271
+ lines = [{'type': 'session', 'version': 3, 'id': f'{sid[:8]}-{sid[8:12]}-{sid[12:16]}-{sid[16:20]}-{sid[20:32]}',
272
+ 'timestamp': iso(t0), 'cwd': ro['cwd']},
273
+ {'type': 'custom', 'id': sid[:8], 'parentId': None, 'timestamp': iso(t0), 'customType': 'matrace-convert',
274
+ 'data': {'source': ro['notebook'], 'sha256': ro['source_sha256'], 'pi_version': PI_VERSION,
275
+ 'note': 'synthetic rollout replayed from a marimo notebook; tool results are real executions'}}]
276
+ usage = {'input': 0, 'output': 0, 'cacheRead': 0, 'cacheWrite': 0, 'totalTokens': 0,
277
+ 'cost': {'input': 0, 'output': 0, 'cacheRead': 0, 'cacheWrite': 0, 'total': 0}}
278
+ for i, m in enumerate(ro['messages']):
279
+ if m['role'] == 'assistant': m = {**m, 'api': 'openai-completions', 'provider': 'matrace', 'model': 'notebook-replay', 'usage': usage}
280
+ eid = hashlib.sha256(f'{sid}{i}'.encode()).hexdigest()[:8]
281
+ lines.append({'type': 'message', 'id': eid, 'parentId': lines[-1]['id'], 'timestamp': iso(m['timestamp']), 'message': m})
282
+ return [json.dumps(l) for l in lines]
283
+
284
+ def to_chat(ro):
285
+ "The rollout in OpenAI / tinker-cookbook message format (tool calls as JSON-string arguments)"
286
+ out = []
287
+ for m in ro['messages']:
288
+ text = m['content'] if isinstance(m['content'], str) else '\n'.join(b['text'] for b in m['content'] if b['type'] == 'text')
289
+ if m['role'] == 'user': out.append({'role': 'user', 'content': text})
290
+ elif m['role'] == 'toolResult':
291
+ out.append({'role': 'tool', 'content': text, 'tool_call_id': m['toolCallId'], 'name': m['toolName']})
292
+ else:
293
+ thinking = [{'type': 'thinking', 'thinking': b['thinking']} for b in m['content'] if b['type'] == 'thinking']
294
+ msg = {'role': 'assistant', 'content': [*thinking, {'type': 'text', 'text': text}] if thinking else text}
295
+ calls = [b for b in m['content'] if b['type'] == 'toolCall']
296
+ if calls: msg['tool_calls'] = [{'id': b['id'], 'type': 'function', 'function': {
297
+ 'name': b['name'], 'arguments': json.dumps(b['arguments'])}} for b in calls]
298
+ out.append(msg)
299
+ return out
300
+
301
+ # ---------------------------------------------------------------- Tinker / Inkling 2 Small
302
+
303
+ def _renderer(model):
304
+ from tinker_cookbook import model_info
305
+ from tinker_cookbook.renderers import get_renderer
306
+ from tinker_cookbook.tokenizer_utils import get_tokenizer
307
+ return get_renderer(model_info.get_recommended_renderer_name(model), get_tokenizer(model))
308
+
309
+ def _cookbook_msgs(renderer, system, tools, chat):
310
+ from tinker_cookbook.renderers.base import ToolCall
311
+ msgs = renderer.create_conversation_prefix_with_tools(tools, system_prompt=system)
312
+ for m in chat:
313
+ m = dict(m)
314
+ if 'tool_calls' in m:
315
+ m['tool_calls'] = [ToolCall(id=c['id'], function=ToolCall.FunctionBody(**c['function'])) for c in m['tool_calls']]
316
+ msgs.append(m)
317
+ return msgs
318
+
319
+ def render(ro, model=MODEL, effort=0.0):
320
+ "Render the rollout for `model`: (sft record, opd prompt records)"
321
+ from tinker_cookbook.supervised.common import datum_from_model_input_weights
322
+ r = _renderer(model)
323
+ chat = to_chat(ro)
324
+ msgs = _cookbook_msgs(r, ro['system'], ro['tools'], chat)
325
+ n_pre = len(msgs) - len(chat)
326
+ mi, w = r.build_supervised_example(msgs, effort=effort)
327
+ d = datum_from_model_input_weights(mi, w, reduction='none')
328
+ tokens = d.model_input.to_ints()
329
+ sft = {'model': model, 'effort': effort, 'source': ro['notebook'], 'model_input': tokens,
330
+ 'loss_fn_inputs': {'target_tokens': d.loss_fn_inputs['target_tokens'].tolist(),
331
+ 'weights': d.loss_fn_inputs['weights'].tolist()}}
332
+ # Inkling 2 Small's tokenizer is shared with no other Tinker model, so a token-level teacher has to be Inkling 2
333
+ # Small too. The teacher gets privileged context instead: the same conversation, with the finished notebook in
334
+ # the task message. It scores the student's tokens knowing where the work should end up.
335
+ hint = (f'\n\nReference solution (shown only to you): the finished `{ro["notebook"]}` is\n'
336
+ f'```python\n{ro["final_notebook"]}```')
337
+ tmsgs = [*msgs[:n_pre], {**msgs[n_pre], 'content': msgs[n_pre]['content'] + hint}, *msgs[n_pre + 1:]]
338
+ opd, a = [], 0
339
+ for k, m in enumerate(chat):
340
+ if m['role'] != 'assistant': continue
341
+ prompt = r.build_generation_prompt(msgs[:n_pre + k], effort=effort).to_ints()
342
+ # Inkling's renderer frames messages independently, so each turn's prompt is a token prefix of the trajectory
343
+ assert tokens[:len(prompt)] == prompt, 'generation prompt is not a prefix of the SFT trajectory'
344
+ opd.append({'id': f'{ro["notebook"]}#turn{a}', 'model': model, 'effort': effort, 'prompt_tokens': prompt,
345
+ 'teacher_prompt_tokens': r.build_generation_prompt(tmsgs[:n_pre + k], effort=effort).to_ints(),
346
+ 'messages': chat[:k], 'reference': m, 'workspace': ro['snapshots'][a],
347
+ 'system': ro['system'], 'tools': ro['tools']})
348
+ a += 1
349
+ return sft, opd
350
+
351
+ def convert(nb, out_dir, model=MODEL, effort=0.0, cwd=None, tinker=True):
352
+ "Write Pi session, chat messages and (if tinker-cookbook is installed) SFT + OPD data for notebook `nb`"
353
+ out = Path(out_dir); out.mkdir(parents=True, exist_ok=True)
354
+ ro = rollout(nb, cwd)
355
+ (out/'pi_session.jsonl').write_text('\n'.join(to_pi_session(ro)) + '\n')
356
+ (out/'messages.json').write_text(json.dumps({'system': ro['system'], 'tools': ro['tools'], 'messages': to_chat(ro)}, indent=1))
357
+ written = [out/'pi_session.jsonl', out/'messages.json']
358
+ if tinker:
359
+ sft, opd = render(ro, model, effort)
360
+ (out/'sft.jsonl').write_text(json.dumps(sft) + '\n')
361
+ (out/'opd_prompts.jsonl').write_text(''.join(json.dumps(o) + '\n' for o in opd))
362
+ written += [out/'sft.jsonl', out/'opd_prompts.jsonl']
363
+ return ro, written
364
+
365
+ # ---------------------------------------------------------------- loading for training
366
+
367
+ def load_sft(path):
368
+ "Read sft.jsonl as a list of `tinker.types.Datum` (cross-entropy: target_tokens + 0/1 weights)"
369
+ from tinker import types
370
+ return [types.Datum(model_input=types.ModelInput.from_ints(d['model_input']), loss_fn_inputs=d['loss_fn_inputs'])
371
+ for d in map(json.loads, Path(path).read_text().splitlines())]
372
+
373
+ def opd_datum(prompt_tokens, sampled_tokens, sampled_logprobs, teacher_logprobs, kl_coef=1.0):
374
+ """RL datum for on-policy distillation: advantage = kl_coef * (teacher_logprob - student_logprob) per sampled token,
375
+ i.e. the negative per-token reverse KL, for the `importance_sampling` loss. Prompt positions are zero-masked."""
376
+ from tinker import types
377
+ full, n_prefix = list(prompt_tokens) + list(sampled_tokens), len(prompt_tokens) - 1
378
+ return types.Datum(model_input=types.ModelInput.from_ints(full[:-1]), loss_fn_inputs=dict(
379
+ target_tokens=full[1:], logprobs=[0.0] * n_prefix + list(sampled_logprobs),
380
+ advantages=[0.0] * n_prefix + [kl_coef * (t - s) for t, s in zip(teacher_logprobs, sampled_logprobs)]))
matrace/core.py ADDED
@@ -0,0 +1,338 @@
1
+ """nbdev's export / update / test / clean, for marimo notebooks."""
2
+
3
+ import ast, builtins, os, re, subprocess, sys, tempfile, time, tomllib, warnings
4
+ from concurrent.futures import ThreadPoolExecutor
5
+ from dataclasses import dataclass, replace
6
+ from itertools import dropwhile, takewhile
7
+ from pathlib import Path
8
+ from textwrap import TextWrapper, dedent
9
+
10
+ # marimo's own parser and serializer, so notebooks we rewrite look exactly like the editor's output.
11
+ # These are private APIs, hence the tight marimo pin in pyproject.toml.
12
+ from marimo._ast.codegen import generate_filecontents_from_ir
13
+ from marimo._ast.compiler import compile_cell
14
+ from marimo._ast.parse import parse_notebook
15
+
16
+ # ---------------------------------------------------------------- config
17
+
18
+ @dataclass
19
+ class Config:
20
+ root: Path
21
+ lib_path: Path
22
+ nbs_path: Path
23
+ @property
24
+ def lib_name(self): return self.lib_path.name
25
+
26
+ def get_config(path=None) -> Config:
27
+ "Read `[tool.matrace]` from the nearest pyproject.toml at or above `path`"
28
+ d = Path(path or '.').resolve()
29
+ if d.is_file(): d = d.parent
30
+ for p in [d, *d.parents]:
31
+ f = p/'pyproject.toml'
32
+ if not f.exists(): continue
33
+ cfg = tomllib.loads(f.read_text())
34
+ if 'matrace' not in cfg.get('tool', {}): continue
35
+ m = cfg['tool']['matrace']
36
+ lib = m.get('lib_path') or cfg.get('project', {}).get('name', '').replace('-', '_')
37
+ return Config(p, p/lib, p/m.get('nbs_path', 'jobs'))
38
+ raise SystemExit('matrace: no pyproject.toml with a [tool.matrace] table found')
39
+
40
+ # ---------------------------------------------------------------- notebooks
41
+
42
+ _re_dir = re.compile(r'^\s*#\|\s*([\w-]+):?\s*(.*?)\s*$')
43
+ _EXPORTS = {'export', 'exporti', 'exports'}
44
+
45
+ @dataclass
46
+ class Cell:
47
+ idx: int # position in the notebook (the setup cell counts); used as the cell id in `# %%` markers
48
+ code: str # full source, directives included
49
+ hdr: list # the leading `#|` directive lines
50
+ body: str # source without directives
51
+ dirs: dict # directive name -> argument string
52
+
53
+ def partition(code):
54
+ "Split leading `#|` directive lines from the rest of `code`"
55
+ lines = code.splitlines()
56
+ n = 0
57
+ while n < len(lines) and _re_dir.match(lines[n]): n += 1
58
+ dirs = dict(_re_dir.match(l).groups() for l in lines[:n])
59
+ return lines[:n], '\n'.join(lines[n:]).strip('\n'), dirs
60
+
61
+ def read_nb(path):
62
+ "Parse marimo notebook `path` into marimo's IR plus our `Cell` view of it"
63
+ text = Path(path).read_text()
64
+ ir = parse_notebook(text, str(path))
65
+ if ir is None or not ir.cells: raise ValueError(f'{path} is not a marimo notebook')
66
+ return text, ir, [Cell(i, c.code, *partition(c.code)) for i, c in enumerate(ir.cells)]
67
+
68
+ _re_gen = re.compile(r'^__generated_with = .*$', re.M)
69
+
70
+ def write_nb(path, ir, orig):
71
+ "Serialize `ir` with marimo's codegen, keeping the original `__generated_with`; write only if changed"
72
+ new = generate_filecontents_from_ir(ir)
73
+ if m := _re_gen.search(orig): new = _re_gen.sub(lambda _: m[0], new, count=1)
74
+ if new != orig: Path(path).write_text(new)
75
+ return new
76
+
77
+ def is_marimo(p): return 'marimo.App(' in Path(p).read_text()
78
+
79
+ def nbglob(path, default):
80
+ "Marimo notebooks in `path` (file or dir), skipping names starting with `_` or `.`, like nbdev"
81
+ path = Path(path or default)
82
+ if path.is_file(): return [path.resolve()]
83
+ return sorted(f.resolve() for f in path.rglob('*.py')
84
+ if not any(part[0] in '_.' for part in f.relative_to(path).parts) and is_marimo(f))
85
+
86
+ # ---------------------------------------------------------------- export
87
+
88
+ def _md_text(code):
89
+ "Text of a `mo.md(...)` markdown cell, else None"
90
+ try: body = ast.parse(code).body
91
+ except SyntaxError: return None
92
+ if len(body) == 1 and isinstance(body[0], ast.Expr) and isinstance(c := body[0].value, ast.Call) \
93
+ and getattr(c.func, 'attr', None) == 'md' and c.args and isinstance(c.args[0], ast.Constant) \
94
+ and isinstance(c.args[0].value, str):
95
+ return dedent(c.args[0].value).strip()
96
+
97
+ def _mod_doc(cells):
98
+ "Module docstring: the `> ` summary under the notebook's `# Title` markdown cell (as nbdev does)"
99
+ md = next((t for c in cells if (t := _md_text(c.code)) and t.startswith('# ')), None)
100
+ if not md: return ''
101
+ lines = takewhile(lambda l: l.startswith('> '), dropwhile(lambda l: not l.startswith('> '), md.splitlines()))
102
+ doc = '\n'.join(l.lstrip('> ').strip() for l in lines).strip()
103
+ if not doc: return ''
104
+ return f'{"r" if chr(92) in doc else ""}"""{doc}"""\n\n'
105
+
106
+ def _decor_id(d): return getattr(d, 'id', None) or getattr(getattr(d, 'func', None), 'id', '')
107
+
108
+ def make_all(codes):
109
+ "`__all__` for `codes`: public assignment targets, then public defs, then anything in `_all_` (nbdev's rule)"
110
+ targs, syms, extra = [], [], []
111
+ for code in codes:
112
+ for o in ast.parse(code).body:
113
+ if isinstance(o, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
114
+ if not any(_decor_id(d).startswith('patch') for d in o.decorator_list): syms.append(o.name)
115
+ elif isinstance(o, (ast.Assign, ast.AnnAssign, ast.AugAssign)):
116
+ ts = o.targets if isinstance(o, ast.Assign) else [o.target]
117
+ if getattr(ts[0], 'id', None) == '_all_':
118
+ extra += [getattr(e, 'value', getattr(e, 'id', None)) for e in o.value.elts]
119
+ for t in ts: targs += [getattr(e, 'id', None) for e in getattr(t, 'elts', [t])]
120
+ return list(dict.fromkeys([n for n in targs + syms if n and n[0] != '_'] + extra))
121
+
122
+ _re_from = re.compile(r'^(\s*from\s+)(\.*)([\w.]*)(\s+import\b)', re.M)
123
+
124
+ def to_relative(code, lib, pkg):
125
+ "Rewrite `from lib.x import y` as a relative import from package `pkg` (nbdev does the same)"
126
+ cur = pkg.split('.')
127
+ def f(m):
128
+ tgt = m[3].split('.')
129
+ if m[2] or tgt[0] != lib: return m[0]
130
+ n = 0
131
+ while n < min(len(tgt), len(cur)) and tgt[n] == cur[n]: n += 1
132
+ return m[1] + '.' * (len(cur) - n + 1) + '.'.join(tgt[n:]) + m[4]
133
+ return _re_from.sub(f, code)
134
+
135
+ def to_absolute(code, pkg):
136
+ "Inverse of `to_relative`, used when syncing module edits back into notebooks"
137
+ cur = pkg.split('.')
138
+ def f(m):
139
+ if not m[2]: return m[0]
140
+ base = cur[:len(cur) - len(m[2]) + 1]
141
+ return m[1] + '.'.join(base + ([m[3]] if m[3] else [])) + m[4]
142
+ return _re_from.sub(f, code)
143
+
144
+ def _import_stmt(d):
145
+ "Reconstruct the import statement that defines a name, from marimo's `ImportData`"
146
+ if d.import_level: return None
147
+ if d.imported_symbol:
148
+ mod, sym = d.imported_symbol.rsplit('.', 1)
149
+ return f'from {mod} import {sym}' + (f' as {d.definition}' if sym != d.definition else '')
150
+ return f'import {d.module}' + ('' if d.module.split('.')[0] == d.definition else f' as {d.definition}')
151
+
152
+ def _nb_exports(nb):
153
+ "Return [(module, cell, in_all)] for exported cells of `nb`, plus a name->import-line resolver"
154
+ _, _, cells = read_nb(nb)
155
+ default = next((c.dirs['default_exp'] for c in cells if 'default_exp' in c.dirs), None)
156
+ res = []
157
+ for c in cells:
158
+ kind = _EXPORTS & c.dirs.keys()
159
+ if not kind or not c.body.strip(): continue
160
+ kind = kind.pop()
161
+ mod = c.dirs[kind] or default
162
+ if not mod:
163
+ warnings.warn(f"{nb}: `#| {kind}` without a module and no `#| default_exp` cell; skipping notebook")
164
+ return [], {}, None
165
+ res.append((mod, c, kind != 'exporti'))
166
+ # Marimo forbids defining a name in two cells, so a cell exported to module B can't re-import what
167
+ # module A defines (nbdev notebooks just repeat the import). Use marimo's dataflow graph instead:
168
+ # every cell's defs and refs, so each module gets the imports it needs.
169
+ info = {c.idx: compile_cell(c.body, cell_id=str(c.idx)) for c in cells}
170
+ imports, owner = {}, {}
171
+ for c in cells:
172
+ for name, vds in info[c.idx].variable_data.items():
173
+ if vds[0].import_data and (s := _import_stmt(vds[0].import_data)): imports.setdefault(name, s)
174
+ for mod, c, _ in res:
175
+ for name in info[c.idx].defs: owner.setdefault(name, mod)
176
+ return res, {'imports': imports, 'owner': owner, 'info': info}, default
177
+
178
+ def _auto_imports(mod, cells, ctx, lib, pkg):
179
+ "Import lines module `mod` needs for names its cells reference but don't define"
180
+ if not ctx: return []
181
+ defs = set().union(*(ctx['info'][c.idx].defs for c in cells))
182
+ refs = set().union(*(ctx['info'][c.idx].refs for c in cells)) - defs - set(dir(builtins))
183
+ local = defs | {n for c in cells for n in _module_level_names(c.body)}
184
+ lines = []
185
+ for n in sorted(refs - local):
186
+ o = ctx['owner'].get(n)
187
+ if o == mod: continue
188
+ if n in ctx['imports']: lines.append(ctx['imports'][n]) # repeat the import itself
189
+ elif o: lines.append(f'from {lib}.{o} import {n}') # import from the module that defines it
190
+ lines = sorted(dict.fromkeys(lines), key=lambda l: (l.startswith(f'from {lib}.'), l))
191
+ return [to_relative(l, lib, pkg) for l in lines]
192
+
193
+ def _module_level_names(code):
194
+ "Names bound at the top level of `code`, including `_private` ones marimo keeps cell-local"
195
+ names = set()
196
+ for o in ast.parse(code).body:
197
+ if isinstance(o, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): names.add(o.name)
198
+ elif isinstance(o, (ast.Import, ast.ImportFrom)): names |= {(a.asname or a.name).split('.')[0] for a in o.names}
199
+ elif isinstance(o, (ast.Assign, ast.AnnAssign, ast.AugAssign)):
200
+ for t in (o.targets if isinstance(o, ast.Assign) else [o.target]):
201
+ names |= {n.id for n in ast.walk(t) if isinstance(n, ast.Name)}
202
+ return names
203
+
204
+ def nb_export(path=None):
205
+ "Export marimo notebooks in `path` (default: `nbs_path`) to modules in `lib_path`"
206
+ cfg = get_config(path)
207
+ targets = set(nbglob(path, cfg.nbs_path))
208
+ # Gather every notebook so a module fed by several notebooks is always rebuilt whole.
209
+ mods, ctxs, defaults = {}, {}, {}
210
+ for nb in nbglob(None, cfg.nbs_path):
211
+ exps, ctxs[nb], defaults[nb] = _nb_exports(nb)
212
+ for mod, c, in_all in exps: mods.setdefault(mod, []).append((nb, c, in_all))
213
+ written = []
214
+ for mod, items in mods.items():
215
+ if not targets & {nb for nb, _, _ in items}: continue
216
+ written.append(_write_module(cfg, mod, items, ctxs, defaults))
217
+ _add_init(cfg.lib_path)
218
+ return written
219
+
220
+ def _write_module(cfg, mod, items, ctxs, defaults):
221
+ fname = cfg.lib_path/(mod.replace('.', '/') + '.py')
222
+ fname.parent.mkdir(parents=True, exist_ok=True)
223
+ pkg = '.'.join([cfg.lib_name] + mod.split('.')[:-1])
224
+ rel = lambda nb: Path(os.path.relpath(nb, fname.parent)).as_posix()
225
+ main = next((nb for nb, _, _ in items if defaults[nb] == mod), items[0][0])
226
+ doc = _mod_doc(read_nb(main)[2]) if defaults[main] == mod else ''
227
+ alls = make_all([c.body for _, c, in_all in items if in_all])
228
+ all_str = '\n'.join(TextWrapper(width=120, subsequent_indent=' ' * 11, break_long_words=False).wrap(str(alls)))
229
+ out = [doc, f'# AUTOGENERATED! DO NOT EDIT! File to edit: {rel(main)}.', f'\n\n# %% auto #0\n__all__ = {all_str}']
230
+ imps = []
231
+ for nb in dict.fromkeys(nb for nb, _, _ in items):
232
+ imps += _auto_imports(mod, [c for n, c, _ in items if n == nb], ctxs[nb], cfg.lib_name, pkg)
233
+ if imps: out.append('\n\n# %% auto #1\n' + '\n'.join(dict.fromkeys(imps)))
234
+ for nb, c, _ in items: out.append(f'\n\n# %% {rel(nb)} #{c.idx}\n{to_relative(c.body, cfg.lib_name, pkg)}')
235
+ text = ''.join(out) + '\n'
236
+ if not fname.exists() or fname.read_text() != text: fname.write_text(text)
237
+ return fname
238
+
239
+ def _add_init(path):
240
+ "Add `__init__.py` to every directory under `path` holding python files, if missing (as nbdev does)"
241
+ if not path.exists(): return
242
+ for d in [path, *[p for p in path.rglob('*') if p.is_dir() and not p.name.startswith(('_', '.'))]]:
243
+ if any(d.glob('*.py')) and not (d/'__init__.py').exists(): (d/'__init__.py').touch()
244
+
245
+ # ---------------------------------------------------------------- update (module -> notebook)
246
+
247
+ _re_hdr = re.compile(r'^# %% (\S+) #(\S+)[ \t]*$', re.M)
248
+
249
+ def _py_cells(py):
250
+ "Yield (notebook path, cell idx, code) for each non-auto cell in exported module `py`"
251
+ text = py.read_text()
252
+ ms = list(_re_hdr.finditer(text))
253
+ for m, nxt in zip(ms, ms[1:] + [None]):
254
+ if m[1] == 'auto': continue
255
+ yield (py.parent/m[1]).resolve(), int(m[2]), text[m.end():nxt.start() if nxt else None].strip('\n')
256
+
257
+ def nb_update(path=None):
258
+ "Propagate edits in exported modules under `path` (default: `lib_path`) back to their notebooks"
259
+ cfg = get_config(path)
260
+ p = Path(path) if path else cfg.lib_path
261
+ pys = [p] if p.is_file() else sorted(p.rglob('*.py'))
262
+ edits = {}
263
+ for py in pys:
264
+ rel = py.resolve().relative_to(cfg.lib_path.resolve())
265
+ pkg = '.'.join([cfg.lib_name, *rel.parent.parts])
266
+ mod = '.'.join(rel.with_suffix('').parts)
267
+ for nb, idx, code in _py_cells(py): edits.setdefault(nb, {})[idx] = mod, to_absolute(code, pkg)
268
+ changed = []
269
+ for nb, cells in edits.items():
270
+ text, ir, view = read_nb(nb)
271
+ default = next((c.dirs['default_exp'] for c in view if 'default_exp' in c.dirs), None)
272
+ for idx, (mod, code) in cells.items():
273
+ kind = idx < len(view) and _EXPORTS & view[idx].dirs.keys()
274
+ # Marimo files carry no stable cell ids, so cells are addressed by position: verify it's still the same cell
275
+ if not kind or (view[idx].dirs[kind.pop()] or default) != mod:
276
+ raise ValueError(f'{nb}: cell #{idx} is not an exported cell of `{mod}`; the notebook changed since '
277
+ 'the last export. Re-run matrace-export, then make your edit again.')
278
+ if code != view[idx].body: ir.cells[idx].code = '\n'.join(view[idx].hdr + [code])
279
+ if write_nb(nb, ir, text) != text: changed.append(nb)
280
+ return changed
281
+
282
+ # ---------------------------------------------------------------- test
283
+
284
+ def _skipped(c): return c.dirs.get('eval', '').lower() in ('false', 'no', '0')
285
+
286
+ def test_nb(nb, timeout=None):
287
+ "Run notebook `nb` as a script (minus `#| eval: false` cells), in its own process and directory"
288
+ _, ir, cells = read_nb(nb)
289
+ tmp = None
290
+ if any(map(_skipped, cells)): # run a copy without the skipped cells; otherwise the notebook itself (exact line numbers)
291
+ src = generate_filecontents_from_ir(replace(ir, cells=[ir.cells[c.idx] for c in cells if not _skipped(c)]))
292
+ with tempfile.NamedTemporaryFile('w', dir=nb.parent, prefix=f'.matrace_{nb.stem}_', suffix='.py', delete=False) as f:
293
+ f.write(src)
294
+ tmp = f.name
295
+ start = time.time()
296
+ try:
297
+ r = subprocess.run([sys.executable, tmp or str(nb)], cwd=nb.parent, capture_output=True, text=True,
298
+ timeout=timeout, env={**os.environ, 'IN_TEST': '1'})
299
+ ok, err = r.returncode == 0, r.stderr
300
+ except subprocess.TimeoutExpired: ok, err = False, f'timed out after {timeout}s'
301
+ finally:
302
+ if tmp: os.unlink(tmp)
303
+ return ok, time.time() - start, err.replace(tmp, str(nb)) if tmp else err
304
+
305
+ def nb_test(path=None, n_workers=None, timing=False, timeout=None):
306
+ "Test notebooks in `path` in parallel, one process each; return True if all passed"
307
+ cfg = get_config(path)
308
+ files = nbglob(path, cfg.nbs_path)
309
+ if not files: print('No files were eligible for testing'); return True
310
+ if n_workers is None: n_workers = min(os.cpu_count() or 1, 8)
311
+ with ThreadPoolExecutor(max(n_workers, 1)) as ex: results = list(ex.map(lambda f: test_nb(f, timeout), files))
312
+ for f, (ok, _, err) in zip(files, results):
313
+ if not ok: sys.stderr.write(f'\n----- {f.name} -----\n{err}\n')
314
+ if timing:
315
+ for f, (_, t, _) in sorted(zip(files, results), key=lambda o: -o[1][1]): print(f'{f.name}: {t:.1f} secs')
316
+ if all(ok for ok, _, _ in results): print('Success.'); return True
317
+ failed = '\n\t'.join(f.name for f, (ok, _, _) in zip(files, results) if not ok)
318
+ sys.stderr.write(f"\nmatrace Tests Failed On The Following Notebooks:\n{'=' * 50}\n\t{failed}\n")
319
+ return False
320
+
321
+ # ---------------------------------------------------------------- clean
322
+
323
+ def clean_text(text, path='<marimo>'):
324
+ "Canonical marimo serialization of `text`, trailing whitespace stripped, `__generated_with` kept"
325
+ ir = parse_notebook(text, str(path))
326
+ for c in ir.cells: c.code = '\n'.join(l.rstrip() for l in c.code.splitlines()).strip('\n')
327
+ new = generate_filecontents_from_ir(ir)
328
+ if m := _re_gen.search(text): new = _re_gen.sub(lambda _: m[0], new, count=1)
329
+ return new
330
+
331
+ def nb_clean(path=None):
332
+ "Clean all marimo notebooks in `path` (default: `nbs_path`) to avoid merge conflicts; return those changed"
333
+ files = nbglob(path, get_config(path).nbs_path) if path is None or Path(path).is_dir() else [Path(path)]
334
+ changed = []
335
+ for f in files:
336
+ text = f.read_text()
337
+ if (new := clean_text(text, f)) != text: f.write_text(new); changed.append(f)
338
+ return changed
@@ -0,0 +1,153 @@
1
+ Metadata-Version: 2.5
2
+ Name: mo-trace
3
+ Version: 0.1.0
4
+ Summary: nbdev-style literate programming for marimo notebooks
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: >=3.11
7
+ Requires-Dist: marimo<0.26,>=0.25
8
+ Provides-Extra: tinker
9
+ Requires-Dist: tinker-cookbook>=0.6; extra == 'tinker'
10
+ Requires-Dist: tinker>=0.39; extra == 'tinker'
11
+ Requires-Dist: tml-renderers>=0.4; extra == 'tinker'
12
+ Description-Content-Type: text/markdown
13
+
14
+ # matrace
15
+
16
+ A minimal [nbdev](https://nbdev.fast.ai) for [marimo](https://marimo.io) notebooks. Write the code, its docs and its tests
17
+ in a marimo notebook. matrace turns the exported cells into a normal Python package and keeps the two in sync.
18
+
19
+ | matrace | nbdev equivalent | does |
20
+ |---|---|---|
21
+ | `matrace-export` | `nbdev-export` | notebook cells → modules in `lib_path` |
22
+ | `matrace-export --update` | `nbdev-update` | edits made in modules → back into the notebook cells |
23
+ | `matrace-prepare` | `nbdev-prepare` | export, run every notebook's tests in parallel, then clean |
24
+ | `matrace-clean` | `nbdev-clean` | normalize notebooks so diffs and merges stay clean |
25
+
26
+ Run `matrace --help` for a guide to using it in a notebook and the CLI, and to organizing notebooks.
27
+
28
+ ## Install
29
+
30
+ ```sh
31
+ pip install mo-trace # or: uv add --dev mo-trace (imported as `matrace`)
32
+ ```
33
+
34
+ Add a `[tool.matrace]` table to your project's `pyproject.toml`:
35
+
36
+ ```toml
37
+ [tool.matrace]
38
+ lib_path = "mypkg" # default: [project].name, with - replaced by _
39
+ nbs_path = "jobs" # default: jobs
40
+ ```
41
+
42
+ ## Writing notebooks
43
+
44
+ Directives are `#|` comments on the first lines of a cell. They work the same as in nbdev.
45
+
46
+ ```python
47
+ with app.setup:
48
+ #| default_exp core # where `#| export` cells go -> mypkg/core.py
49
+ import numpy as np
50
+
51
+ @app.cell
52
+ def _():
53
+ #| export # -> mypkg/core.py, listed in __all__
54
+ def norm(x): return x / np.linalg.norm(x)
55
+ return (norm,)
56
+
57
+ @app.cell
58
+ def _(norm):
59
+ #| export metrics.distance # choose the file for this cell -> mypkg/metrics/distance.py
60
+ def cosine(a, b): return norm(a) @ norm(b)
61
+ return (cosine,)
62
+
63
+ @app.cell
64
+ def _(cosine):
65
+ assert cosine(np.ones(3), np.ones(3)) == 1 # an ordinary cell is a test
66
+ return
67
+
68
+ @app.cell
69
+ def _():
70
+ #| eval: false # skipped by matrace-prepare
71
+ slow_benchmark()
72
+ return
73
+ ```
74
+
75
+ Supported directives: `default_exp`, `export [module]`, `exporti [module]` (exported but left out of `__all__`), `exports`, and
76
+ `eval: false`. matrace also follows nbdev for these details:
77
+ - `__all__` is built from the public names in exported cells, plus any names listed in `_all_`.
78
+ - `from mypkg.x import y` becomes a relative import in the generated module, and becomes absolute again when synced back.
79
+ - The module docstring comes from the `> summary` line under the notebook's `# Title` markdown cell.
80
+ - Notebooks whose names start with `_` or `.` are skipped.
81
+
82
+ ## Differences from nbdev (by design or necessity)
83
+
84
+ - **Imports across modules are generated for you.** Marimo forbids defining a name in more than one cell, so a cell exported
85
+ to `metrics/distance.py` cannot re-import `norm` the way an nbdev notebook would. matrace reads marimo's dataflow graph
86
+ instead. Each module gets an `# %% auto #1` block that imports what its cells use but don't define: import statements
87
+ from other cells, such as the setup cell, are copied, and names exported to other modules are imported from those modules.
88
+ - **`#| export other_module` can create a new file.** nbdev requires the target module to already exist.
89
+ - **Cells are identified by position.** Marimo files have no stable cell ids, so the `# %% ../jobs/nb.py #3` markers use the
90
+ cell's position. `--update` refuses to write if that cell is no longer an exported cell of the same module. Run
91
+ `matrace-export` again after reordering cells.
92
+ - **Tests run the notebook as a script**, `python nb.py`, one process per notebook, in the notebook's directory, with
93
+ `IN_TEST=1` set. Cells execute in marimo's dependency order.
94
+ - **Clean has less to remove.** Marimo files contain no outputs or execution counts. `matrace-clean` rewrites each notebook
95
+ in marimo's own canonical format and strips trailing whitespace. It keeps `__generated_with` unchanged, so upgrading marimo
96
+ doesn't change every notebook. `matrace-clean --stdin` works as a git filter.
97
+ - **Not included:** docs, README generation, `_modidx.py`, `llms.txt` and Quarto. `matrace-prepare` is export + test + clean.
98
+ - **Private marimo APIs.** matrace uses marimo's internal parser and code generator, so it pins `marimo>=0.25,<0.26`.
99
+
100
+ ## Example: a tiny language model from one notebook
101
+
102
+ [`examples/tinylm`](examples/tinylm) is a character-level bigram language model, the classic first language model. It
103
+ trains on a list of names, reports perplexity and samples new names. All of it is in [`jobs/tinylm.py`](examples/tinylm/jobs/tinylm.py).
104
+ Each cell picks its target file, giving `tinylm/{data,tokenizer,model,train}.py`. The tests sit next to the code they check.
105
+
106
+ ```sh
107
+ cd examples/tinylm
108
+ matrace-prepare # export, test, clean -> Success.
109
+ pip install . # or: pip install -e .
110
+ tinylm-train # {'train_ppl': 11.14, 'val_ppl': 11.58} + sampled names
111
+ marimo edit jobs/tinylm.py # keep developing in the notebook
112
+ ```
113
+
114
+ ## Training data: notebook → Pi rollout → Tinker (`matrace-convert`)
115
+
116
+ ```sh
117
+ pip install "mo-trace[tinker]"
118
+ matrace-convert examples/tinylm/jobs/tinylm.py -o traces
119
+ python examples/tinker_train.py traces # SFT, then on-policy distillation, on Tinker
120
+ ```
121
+
122
+ `matrace-convert` replays a notebook as a session of the [Pi](https://github.com/earendil-works/pi-mono) coding agent
123
+ building it. The replay uses Pi 1.5.2's system prompt, its `read`/`bash`/`edit`/`write` tool schemas and its result
124
+ strings. The agent explores the project, writes the first cells, then edits in each exported cell with its tests, in
125
+ marimo dependency order. It runs `matrace-prepare` after every step and finally checks that the package imports. Every tool
126
+ call runs for real in a scratch copy of the project, so tool results are real output. A notebook whose tests fail is
127
+ rejected. The output files are:
128
+
129
+ | file | contents |
130
+ |---|---|
131
+ | `pi_session.jsonl` | the rollout as a Pi v3 session file, with a `custom` entry recording its notebook source |
132
+ | `messages.json` | the same conversation in OpenAI / tinker-cookbook format, plus Pi's system prompt and tool specs |
133
+ | `sft.jsonl` | a Tinker `Datum` (`model_input`, `target_tokens`, 0/1 `weights`) of the whole trajectory, rendered with Inkling 2 Small's renderer. Only assistant tokens carry loss: reasoning, text, tool calls and end-of-turn |
134
+ | `opd_prompts.jsonl` | one starting state per assistant turn for on-policy distillation. Each has `prompt_tokens` (a token prefix of the trajectory), `teacher_prompt_tokens`, the reference turn, and the workspace files at that point |
135
+
136
+ Load the data with `matrace.convert.load_sft()`. `matrace.convert.opd_datum()` builds the `importance_sampling` datum,
137
+ with advantage = teacher logprob − student logprob for each sampled token.
138
+
139
+ Notes:
140
+ - **Teacher.** Inkling 2 Small's tokenizer isn't shared with any other Tinker model, Inkling v1 included. A token-level
141
+ teacher therefore has to be Inkling 2 Small as well. `teacher_prompt_tokens` gives it privileged context: the same
142
+ state, with the finished notebook in the task message. You can also use a stronger fine-tuned checkpoint.
143
+ - **Reasoning.** The markdown cells before each step become that turn's `thinking` block (Pi's and the cookbook's format),
144
+ which carries loss like the rest of the turn. A notebook with little prose gives little reasoning, so the default
145
+ thinking effort stays at 0 (`--effort`).
146
+ - **Ideal path only.** Traces don't yet include mistakes and recoveries. Distillation samples one turn per state; a
147
+ multi-turn version would run the student's tool calls in the record's `workspace` snapshot.
148
+
149
+ ## Development
150
+
151
+ ```sh
152
+ uv sync && uv run pytest # includes parity tests that run real nbdev on equivalent .ipynb notebooks
153
+ ```
@@ -0,0 +1,8 @@
1
+ matrace/__init__.py,sha256=KgDJ00_q-7XgEWD0sy6lANHlL1lQrJRn8PX9EL32FEA,141
2
+ matrace/cli.py,sha256=Q6kXoXjFqbc8SxpYKSDQ4yoWwvXtyzZjkvQV-jfzTtw,8125
3
+ matrace/convert.py,sha256=Ww3ODHX2ecX3OPwkc_kERXYwM85szZFNZ3KuN_n_BVk,25877
4
+ matrace/core.py,sha256=-PbaftjtRLe3tE5wCXYZ7Ifvb4-S5ek78dTIqbYVkrA,17174
5
+ mo_trace-0.1.0.dist-info/METADATA,sha256=TrG-bUFZHQeuLY5ASCxfJ_58rfmco9E2z19PzTaLLlg,8096
6
+ mo_trace-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ mo_trace-0.1.0.dist-info/entry_points.txt,sha256=zwskjE-1GY5A8joEOvAxFLFeYJFu6QcZHdebefGXi2s,211
8
+ mo_trace-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,6 @@
1
+ [console_scripts]
2
+ matrace = matrace.cli:main_cli
3
+ matrace-clean = matrace.cli:clean_cli
4
+ matrace-convert = matrace.cli:convert_cli
5
+ matrace-export = matrace.cli:export_cli
6
+ matrace-prepare = matrace.cli:prepare_cli