mo-trace 0.2.0__tar.gz → 0.3.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: mo-trace
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: nbdev-style literate programming for marimo notebooks
5
5
  License-Expression: Apache-2.0
6
6
  Requires-Python: >=3.11
@@ -111,15 +111,44 @@ tinylm-train # {'train_ppl': 11.14, 'val_ppl': 11.58} + sampled na
111
111
  marimo edit jobs/tinylm.py # keep developing in the notebook
112
112
  ```
113
113
 
114
- ## Training data: notebook → Pi rollout → Tinker (`motrace-convert`)
114
+ ## Training data: notebook ↔ agent trajectory (`motrace-convert`)
115
+
116
+ ```sh
117
+ motrace-convert # every notebook in nbs_path -> traces/<notebook>.jsonl
118
+ motrace-convert jobs/00_core.py -o all.jsonl # one notebook (or a directory) into one JSONL file
119
+ motrace-convert traces/00_core.jsonl -o nbs/ # back: trajectory -> nbs/00_core.py
120
+ motrace-convert t.json --to-notebook -o x.py # force the reverse direction for any file name
121
+ ```
122
+
123
+ `motrace-convert` turns each notebook into a trajectory of an agent writing it one cell at a time:
124
+
125
+ - a **narration cell** (a hidden cell holding only `mo.md(r"""...""")`) becomes the text of one assistant message;
126
+ - every other cell becomes a `run_cell` tool call (`code`, plus `name` for the setup cell or a reusable function, and
127
+ `hide_code`) on the message that carries the narration before it;
128
+ - the cell's output, recorded in the notebook's marimo session (`__marimo__/session/<name>.json`), becomes the tool
129
+ result. Outputs are matched by code hash, so a stale output is never attached to edited code; those cells get
130
+ `(output not recorded)`, and `metadata.outputs_recorded` counts the rest.
131
+
132
+ Each row is `{"messages", "tools", "metadata"}`: OpenAI-style chat messages and tool calls (tinker-cookbook's
133
+ `ToolCall` shape), tool specs as `{name, description, parameters}`, and metadata with the notebook path, app config
134
+ and file header (PEP 723 block, docstring). Converting a row back gives the notebook exactly as `motrace-clean` writes
135
+ it. Only `hide_code` survives as a cell option, so cells that set `disabled`, `column` etc. are rejected.
136
+ `--instruction FILE` sets the user turn (default: built from the first heading), `--session` picks another session
137
+ file, and `--max-output-chars` truncates tool results. In Python: `motrace.trajectory.to_trajectory(nb)`,
138
+ `to_notebook(row)`, and `training_messages(row, renderer)` for a tinker-cookbook renderer.
139
+
140
+ To keep trajectories next to the code, set `traces_path = "traces"` in `[tool.motrace]`: `motrace-prepare` then
141
+ converts every notebook before exporting.
142
+
143
+ ### Pi rollout → Tinker (`motrace-convert --pi`)
115
144
 
116
145
  ```sh
117
146
  pip install "mo-trace[tinker]"
118
- motrace-convert examples/tinylm/jobs/tinylm.py -o traces
147
+ motrace-convert examples/tinylm/jobs/tinylm.py --pi -o traces
119
148
  python examples/tinker_train.py traces # SFT, then on-policy distillation, on Tinker
120
149
  ```
121
150
 
122
- `motrace-convert` replays a notebook as a session of the [Pi](https://github.com/earendil-works/pi-mono) coding agent
151
+ `motrace-convert --pi` replays a notebook as a session of the [Pi](https://github.com/earendil-works/pi-mono) coding agent
123
152
  building it. The replay uses Pi 1.5.2's system prompt, its `read`/`bash`/`edit`/`write` tool schemas and its result
124
153
  strings. The agent explores the project, writes the first cells, then edits in each exported cell with its tests, in
125
154
  marimo dependency order. It runs `motrace-prepare` after every step and finally checks that the package imports. Every tool
@@ -98,15 +98,44 @@ tinylm-train # {'train_ppl': 11.14, 'val_ppl': 11.58} + sampled na
98
98
  marimo edit jobs/tinylm.py # keep developing in the notebook
99
99
  ```
100
100
 
101
- ## Training data: notebook → Pi rollout → Tinker (`motrace-convert`)
101
+ ## Training data: notebook ↔ agent trajectory (`motrace-convert`)
102
+
103
+ ```sh
104
+ motrace-convert # every notebook in nbs_path -> traces/<notebook>.jsonl
105
+ motrace-convert jobs/00_core.py -o all.jsonl # one notebook (or a directory) into one JSONL file
106
+ motrace-convert traces/00_core.jsonl -o nbs/ # back: trajectory -> nbs/00_core.py
107
+ motrace-convert t.json --to-notebook -o x.py # force the reverse direction for any file name
108
+ ```
109
+
110
+ `motrace-convert` turns each notebook into a trajectory of an agent writing it one cell at a time:
111
+
112
+ - a **narration cell** (a hidden cell holding only `mo.md(r"""...""")`) becomes the text of one assistant message;
113
+ - every other cell becomes a `run_cell` tool call (`code`, plus `name` for the setup cell or a reusable function, and
114
+ `hide_code`) on the message that carries the narration before it;
115
+ - the cell's output, recorded in the notebook's marimo session (`__marimo__/session/<name>.json`), becomes the tool
116
+ result. Outputs are matched by code hash, so a stale output is never attached to edited code; those cells get
117
+ `(output not recorded)`, and `metadata.outputs_recorded` counts the rest.
118
+
119
+ Each row is `{"messages", "tools", "metadata"}`: OpenAI-style chat messages and tool calls (tinker-cookbook's
120
+ `ToolCall` shape), tool specs as `{name, description, parameters}`, and metadata with the notebook path, app config
121
+ and file header (PEP 723 block, docstring). Converting a row back gives the notebook exactly as `motrace-clean` writes
122
+ it. Only `hide_code` survives as a cell option, so cells that set `disabled`, `column` etc. are rejected.
123
+ `--instruction FILE` sets the user turn (default: built from the first heading), `--session` picks another session
124
+ file, and `--max-output-chars` truncates tool results. In Python: `motrace.trajectory.to_trajectory(nb)`,
125
+ `to_notebook(row)`, and `training_messages(row, renderer)` for a tinker-cookbook renderer.
126
+
127
+ To keep trajectories next to the code, set `traces_path = "traces"` in `[tool.motrace]`: `motrace-prepare` then
128
+ converts every notebook before exporting.
129
+
130
+ ### Pi rollout → Tinker (`motrace-convert --pi`)
102
131
 
103
132
  ```sh
104
133
  pip install "mo-trace[tinker]"
105
- motrace-convert examples/tinylm/jobs/tinylm.py -o traces
134
+ motrace-convert examples/tinylm/jobs/tinylm.py --pi -o traces
106
135
  python examples/tinker_train.py traces # SFT, then on-policy distillation, on Tinker
107
136
  ```
108
137
 
109
- `motrace-convert` replays a notebook as a session of the [Pi](https://github.com/earendil-works/pi-mono) coding agent
138
+ `motrace-convert --pi` replays a notebook as a session of the [Pi](https://github.com/earendil-works/pi-mono) coding agent
110
139
  building it. The replay uses Pi 1.5.2's system prompt, its `read`/`bash`/`edit`/`write` tool schemas and its result
111
140
  strings. The agent explores the project, writes the first cells, then edits in each exported cell with its tests, in
112
141
  marimo dependency order. It runs `motrace-prepare` after every step and finally checks that the package imports. Every tool
@@ -1,3 +1,3 @@
1
1
  """nbdev-style literate programming for marimo notebooks."""
2
- __version__ = "0.1.0"
2
+ __version__ = "0.3.0"
3
3
  from .core import nb_export, nb_update, nb_test, nb_clean
@@ -1,8 +1,9 @@
1
- """Command line entry points: motrace (the guide), motrace-export, motrace-prepare, motrace-clean."""
1
+ """Command line entry points: motrace (the guide), motrace-export, motrace-prepare, motrace-clean, motrace-convert."""
2
2
 
3
3
  import argparse, sys
4
4
  from . import __version__
5
- from .core import nb_clean, nb_export, nb_test, nb_update, clean_text
5
+ from pathlib import Path
6
+ from .core import clean_text, get_config, nb_clean, nb_export, nb_test, nb_update
6
7
 
7
8
  GUIDE = '''
8
9
  motrace is nbdev for marimo notebooks: write code, docs and tests in a marimo
@@ -15,6 +16,8 @@ SETUP
15
16
  [tool.motrace]
16
17
  lib_path = "mypkg" # package to generate (default: [project].name)
17
18
  nbs_path = "jobs" # where notebooks live (default: jobs)
19
+ traces_path = "traces" # optional: motrace-prepare also writes
20
+ # notebook trajectories here, before exporting
18
21
 
19
22
  IN A MARIMO NOTEBOOK
20
23
  Directives are `#|` comments on the first lines of a cell:
@@ -56,13 +59,19 @@ IN THE CLI
56
59
  motrace-export --update edits made in mypkg/*.py -> back into notebooks
57
60
  motrace-prepare export, run all notebooks' tests in parallel
58
61
  (one process each, cwd = notebook dir), clean;
59
- exits 1 and names any failing notebook
62
+ exits 1 and names any failing notebook. With
63
+ traces_path set, converts notebooks first
60
64
  motrace-clean normalize notebooks (marimo's canonical format,
61
65
  no trailing whitespace) to keep diffs small
62
- motrace-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
+ motrace-convert [NB|DIR] notebooks -> run_cell agent trajectories (JSONL,
67
+ one row per notebook) in traces_path or traces/;
68
+ hidden `mo.md(r"""...""")` cells are the
69
+ agent's narration, other cells its tool calls,
70
+ session outputs the tool results
71
+ motrace-convert T.jsonl trajectory -> notebook (or --to-notebook)
72
+ motrace-convert NB --pi replay a notebook as a Pi coding-agent rollout
73
+ and write Tinker training data for Inkling 2
74
+ Small; needs `pip install "mo-trace[tinker]"`
66
75
  Run any command with --help for its options.
67
76
 
68
77
  Typical loop:
@@ -119,25 +128,61 @@ def clean_cli(argv=None):
119
128
  for f in nb_clean(a.fname): print(f'cleaned {f}')
120
129
 
121
130
  def convert_cli(argv=None):
122
- p = argparse.ArgumentParser('motrace-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 motrace 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')
131
+ p = argparse.ArgumentParser('motrace-convert', formatter_class=argparse.RawDescriptionHelpFormatter,
132
+ description='Convert marimo notebooks to run_cell agent trajectories (JSONL), and back.\n\n'
133
+ 'Narration cells (hidden `mo.md(r"""...""")`) become assistant text; every other cell\n'
134
+ 'becomes a run_cell tool call whose result is the output recorded in the notebook\'s\n'
135
+ 'marimo session.',
136
+ epilog='''examples:
137
+ motrace-convert all notebooks in nbs_path -> traces_path (default: traces/)
138
+ motrace-convert jobs/00_core.py -> traces/00_core.jsonl
139
+ motrace-convert jobs/ -o all.jsonl every notebook, one row each, in one file
140
+ motrace-convert traces/00_core.jsonl -o nbs/ trajectory -> nbs/00_core.py (.json/.jsonl inputs go back)
141
+ motrace-convert t.txt --to-notebook -o x.py force the reverse direction
142
+ motrace-convert jobs/00_core.py --pi -o out/ Pi coding-agent rollout + Tinker data (the 0.2 behavior)''')
143
+ p.add_argument('paths', nargs='*', help='notebooks or directories (default: nbs_path); trajectory .json/.jsonl '
144
+ 'files convert back to notebooks')
145
+ p.add_argument('-o', '--out', help='notebook -> trajectory: a directory (default: traces_path, else traces) or '
146
+ 'one .jsonl file; trajectory -> notebook: a directory (default: .) or one .py file; '
147
+ '--pi: a directory (default: traces)')
148
+ p.add_argument('--to-notebook', action='store_true', help='convert trajectories back to notebooks (implied when '
149
+ 'every input is .json/.jsonl)')
150
+ p.add_argument('--force', action='store_true', help='with --to-notebook, overwrite existing notebooks')
151
+ p.add_argument('--session', help='marimo session JSON with the recorded outputs (default: the notebook\'s '
152
+ '__marimo__/session/<name>.json); one notebook only')
153
+ p.add_argument('--instruction', help='text file with the user turn (default: built from the first heading)')
154
+ p.add_argument('--max-output-chars', type=int, default=4000, help='truncate each tool result (default: 4000)')
155
+ pi = p.add_argument_group('Pi rollout (--pi)')
156
+ pi.add_argument('--pi', action='store_true', help='replay the notebook as a Pi coding-agent rollout (real tool '
157
+ 'executions) and write pi_session.jsonl, messages.json, sft.jsonl, opd_prompts.jsonl')
158
+ pi.add_argument('--model', default='thinkingmachines/Inkling-2-Small', help='Tinker model whose renderer to use')
159
+ pi.add_argument('--effort', type=float, default=0.0, help='Inkling thinking-effort conditioning in [0, 1). '
160
+ 'Reasoning comes only from the notebook\'s markdown and is usually short, so the default is 0')
161
+ pi.add_argument('--cwd', default=None, help='working directory shown in the trace (default: /home/user/<project>)')
162
+ pi.add_argument('--no-tinker', action='store_true', help='only write the Pi session and chat messages')
132
163
  a = p.parse_args(argv)
164
+ if a.pi: return _convert_pi(p, a)
165
+ from .trajectory import nb_from_trajectories, nb_trajectories
166
+ if a.to_notebook or (a.paths and all(x.endswith(('.json', '.jsonl')) for x in a.paths)):
167
+ if not a.paths: p.error('--to-notebook needs trajectory files')
168
+ for f in nb_from_trajectories(a.paths, a.out or '.', force=a.force): print(f'wrote {f}')
169
+ return
170
+ if a.session and (len(a.paths) != 1 or Path(a.paths[0]).is_dir()): p.error('--session needs exactly one notebook')
171
+ files = nb_trajectories(a.paths, a.out, session=a.session, max_output_chars=a.max_output_chars,
172
+ instruction=Path(a.instruction).read_text() if a.instruction else None)
173
+ if not files: print('No notebooks found')
174
+ for f in files: print(f'wrote {f}')
175
+
176
+ def _convert_pi(p, a):
177
+ if len(a.paths) != 1: p.error('--pi converts exactly one notebook')
133
178
  tinker = not a.no_tinker
134
179
  if tinker:
135
180
  try: import tinker_cookbook # noqa: F401
136
181
  except ImportError: sys.exit('motrace-convert: Tinker output needs `pip install "mo-trace[tinker]"` (or pass --no-tinker)')
137
182
  from .convert import convert
138
- ro, files = convert(a.notebook, a.out, model=a.model, effort=a.effort, cwd=a.cwd, tinker=tinker)
183
+ ro, files = convert(a.paths[0], a.out or 'traces', model=a.model, effort=a.effort, cwd=a.cwd, tinker=tinker)
139
184
  n = sum(m['role'] == 'assistant' for m in ro['messages'])
140
- print(f'{a.notebook}: {n} assistant turns, {n - 1} tool calls')
185
+ print(f'{a.paths[0]}: {n} assistant turns, {n - 1} tool calls')
141
186
  for f in files: print(f'wrote {f}')
142
187
 
143
188
  def prepare_cli(argv=None):
@@ -146,6 +191,9 @@ def prepare_cli(argv=None):
146
191
  p.add_argument('--timing', action='store_true', help='print how long each notebook took')
147
192
  p.add_argument('--timeout', type=float, default=None, help='seconds before a notebook test is killed')
148
193
  a = p.parse_args(argv)
194
+ if get_config().traces_path:
195
+ from .trajectory import nb_trajectories
196
+ for f in nb_trajectories(): print(f'wrote {f}')
149
197
  nb_export()
150
198
  if not nb_test(n_workers=a.n_workers, timing=a.timing, timeout=a.timeout): sys.exit(1)
151
199
  nb_clean()
@@ -20,6 +20,7 @@ class Config:
20
20
  root: Path
21
21
  lib_path: Path
22
22
  nbs_path: Path
23
+ traces_path: Path | None = None # if set, motrace-prepare writes notebook trajectories here before exporting
23
24
  @property
24
25
  def lib_name(self): return self.lib_path.name
25
26
 
@@ -34,7 +35,7 @@ def get_config(path=None) -> Config:
34
35
  if 'motrace' not in cfg.get('tool', {}): continue
35
36
  m = cfg['tool']['motrace']
36
37
  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
+ return Config(p, p/lib, p/m.get('nbs_path', 'jobs'), p/m['traces_path'] if m.get('traces_path') else None)
38
39
  raise SystemExit('motrace: no pyproject.toml with a [tool.motrace] table found')
39
40
 
40
41
  # ---------------------------------------------------------------- notebooks
@@ -0,0 +1,318 @@
1
+ """motrace-convert: turn a marimo notebook into a multi-turn agent trajectory, and back.
2
+
3
+ Each cell becomes one step of an agent writing the notebook:
4
+
5
+ - a narration cell (hidden code holding one raw markdown literal, `mo.md(r\"\"\"...\"\"\")`) becomes the text of an
6
+ assistant message, one message per cell;
7
+ - every other cell becomes a `run_cell` tool call on the message that carries the narration before it, and the cell's
8
+ recorded output becomes the tool result.
9
+
10
+ Outputs come from the notebook's saved session (`__marimo__/session/<name>.json`), matched to cells by code hash, so an
11
+ output recorded before a cell was edited is never attached to the new code; such cells get `(output not recorded)` and
12
+ the row's metadata counts them.
13
+
14
+ A row is `{"messages", "tools", "metadata"}`: chat messages with OpenAI-style tool calls (tinker-cookbook's `ToolCall`
15
+ shape), and tool specs as `{name, description, parameters}`. `to_notebook` inverts `to_trajectory`.
16
+ `training_messages` turns a row into the message list a tinker-cookbook renderer takes.
17
+ """
18
+
19
+ import hashlib, html, json, re
20
+ from pathlib import Path
21
+ from typing import NamedTuple
22
+
23
+ from marimo._ast.app_config import _AppConfig
24
+ from marimo._ast.cell import CellConfig
25
+ from marimo._ast.codegen import generate_filecontents
26
+ from marimo._ast.parse import parse_notebook
27
+
28
+ TOOL = "run_cell"
29
+ TOOLS = [
30
+ {
31
+ "name": TOOL,
32
+ "description": "Append a cell to the notebook and run it. Returns the cell's output and anything it printed.",
33
+ "parameters": {
34
+ "type": "object",
35
+ "required": ["code"],
36
+ "properties": {
37
+ "code": {"type": "string", "description": "The cell's code."},
38
+ "name": {
39
+ "type": "string",
40
+ "description": "Optional. `setup` for the setup block that runs first; otherwise "
41
+ "the function name the cell defines, if it is reusable.",
42
+ },
43
+ "hide_code": {
44
+ "type": "boolean",
45
+ "description": "Optional. Hide the code in the editor.",
46
+ },
47
+ },
48
+ },
49
+ }
50
+ ]
51
+ SYSTEM = (
52
+ "You are a coding agent building a notebook one cell at a time. Before each step, explain what it is for; "
53
+ "then call run_cell with the cell's code. The tool runs the cell and returns its output."
54
+ )
55
+ NOT_RECORDED, NO_OUTPUT = "(output not recorded)", "(no output)"
56
+ _NARRATION = re.compile(r'mo\.md\(r"""\n(.*)\n"""\)', re.S)
57
+
58
+
59
+ class Cell(NamedTuple):
60
+ code: str
61
+ name: str
62
+ hide_code: bool
63
+
64
+
65
+ def read_cells(notebook) -> tuple[list[Cell], dict, str]:
66
+ "The notebook's cells in file order, its non-default app config, and its header (docstring, PEP 723 block)"
67
+ ir = parse_notebook(Path(notebook).read_text(), str(notebook))
68
+ if ir is None or not ir.cells:
69
+ raise ValueError(f"{notebook} has no cells")
70
+ cells = []
71
+ for c in ir.cells:
72
+ extra = set(CellConfig.from_dict(c.options).asdict_without_defaults()) - {
73
+ "hide_code"
74
+ }
75
+ if extra:
76
+ raise ValueError(
77
+ f"{notebook}: cell {c.name!r} sets {sorted(extra)}; only hide_code survives the "
78
+ "round trip"
79
+ )
80
+ cells.append(Cell(c.code, c.name, bool(c.options.get("hide_code"))))
81
+ defaults = _AppConfig().asdict()
82
+ config = {
83
+ k: v
84
+ for k, v in _AppConfig.from_untrusted_dict(ir.app.options).asdict().items()
85
+ if v != defaults[k]
86
+ }
87
+ return cells, config, ir.header.value if ir.header else ""
88
+
89
+
90
+ def narration(cell: Cell) -> str | None:
91
+ "The markdown of a narration cell, or None for a code cell"
92
+ m = _NARRATION.fullmatch(cell.code)
93
+ if not (m and cell.hide_code and cell.name == "_"):
94
+ return None
95
+ return m[1] if m[1].strip() and '"""' not in m[1] else None
96
+
97
+
98
+ def _strip_html(text):
99
+ return html.unescape(re.sub(r"<[^>]+>", "", text)).strip()
100
+
101
+
102
+ def output_text(recorded: dict, max_chars: int) -> str:
103
+ "One session cell's outputs and console as plain text"
104
+ parts = []
105
+ for o in recorded.get("outputs", []):
106
+ data = o.get("data", {})
107
+ if not isinstance(data, dict):
108
+ parts.append(str(data))
109
+ elif data.get("text/plain"):
110
+ parts.append(data["text/plain"])
111
+ elif "text/markdown" in data:
112
+ parts.append(_strip_html(data["text/markdown"]))
113
+ elif "text/html" in data:
114
+ parts.append(_strip_html(data["text/html"]) or "[widget]")
115
+ elif any(k.startswith("image/") for k in data):
116
+ parts.append("[image]")
117
+ parts += [line.get("text", "") for line in recorded.get("console", [])]
118
+ text = "\n".join(p for p in parts if p.strip()) or NO_OUTPUT
119
+ if len(text) > max_chars:
120
+ text = text[:max_chars] + f"\n[... {len(text) - max_chars} chars cut]"
121
+ return text
122
+
123
+
124
+ def default_session(notebook) -> Path:
125
+ notebook = Path(notebook)
126
+ return notebook.parent / "__marimo__" / "session" / f"{notebook.name}.json"
127
+
128
+
129
+ def recorded_outputs(session, max_chars: int) -> dict[str, str]:
130
+ "Output text by cell code hash, from a saved session (empty if none)"
131
+ if session is None or not Path(session).exists():
132
+ return {}
133
+ return {
134
+ c["code_hash"]: output_text(c, max_chars)
135
+ for c in json.loads(Path(session).read_text())["cells"]
136
+ }
137
+
138
+
139
+ def to_trajectory(
140
+ notebook, session=None, instruction=None, system=SYSTEM, max_output_chars=4000
141
+ ) -> dict:
142
+ "The trajectory row of one notebook. `session` defaults to the notebook's saved marimo session"
143
+ notebook = Path(notebook)
144
+ cells, app_config, header = read_cells(notebook)
145
+ outputs = recorded_outputs(
146
+ default_session(notebook) if session is None else session, max_output_chars
147
+ )
148
+ heading = next(
149
+ (
150
+ line.lstrip("# ")
151
+ for c in cells
152
+ if (n := narration(c))
153
+ for line in n.splitlines()
154
+ if line.strip()
155
+ ),
156
+ notebook.stem,
157
+ )
158
+ messages = [
159
+ {"role": "system", "content": system},
160
+ {
161
+ "role": "user",
162
+ "content": instruction or f"Build the notebook for: {heading}",
163
+ },
164
+ ]
165
+ pending = None # narration waiting for its tool call
166
+ code_cells = recorded = 0
167
+ for cell in cells:
168
+ if (text := narration(cell)) is not None:
169
+ if pending is not None:
170
+ messages.append({"role": "assistant", "content": pending})
171
+ pending = text
172
+ continue
173
+ code_cells += 1
174
+ call_id = f"call_{code_cells}"
175
+ args = {"code": cell.code}
176
+ if cell.name != "_":
177
+ args["name"] = cell.name
178
+ if cell.hide_code:
179
+ args["hide_code"] = True
180
+ messages.append(
181
+ {
182
+ "role": "assistant",
183
+ "content": pending or "",
184
+ "tool_calls": [
185
+ {
186
+ "type": "function",
187
+ "id": call_id,
188
+ "function": {
189
+ "name": TOOL,
190
+ "arguments": json.dumps(args, ensure_ascii=False),
191
+ },
192
+ }
193
+ ],
194
+ }
195
+ )
196
+ pending = None
197
+ digest = hashlib.md5(cell.code.encode()).hexdigest()
198
+ recorded += digest in outputs
199
+ messages.append(
200
+ {
201
+ "role": "tool",
202
+ "content": outputs.get(digest, NOT_RECORDED),
203
+ "tool_call_id": call_id,
204
+ "name": TOOL,
205
+ }
206
+ )
207
+ if pending is not None:
208
+ messages.append({"role": "assistant", "content": pending})
209
+ meta = {
210
+ "notebook": str(notebook),
211
+ "app_config": app_config,
212
+ "cells": len(cells),
213
+ "code_cells": code_cells,
214
+ "outputs_recorded": recorded,
215
+ }
216
+ if header:
217
+ meta["header"] = header
218
+ return {"messages": messages, "tools": TOOLS, "metadata": meta}
219
+
220
+
221
+ def to_notebook(row: dict) -> str:
222
+ "The notebook source a trajectory row was made from"
223
+ codes, names, configs = [], [], []
224
+ for m in row["messages"]:
225
+ if m["role"] != "assistant":
226
+ continue
227
+ if m["content"]:
228
+ codes.append(f'mo.md(r"""\n{m["content"]}\n""")')
229
+ names.append("_")
230
+ configs.append(CellConfig(hide_code=True))
231
+ for call in m.get("tool_calls", []):
232
+ args = json.loads(call["function"]["arguments"])
233
+ codes.append(args["code"])
234
+ names.append(args.get("name", "_"))
235
+ configs.append(CellConfig(hide_code=args.get("hide_code", False)))
236
+ meta = row.get("metadata", {})
237
+ config = _AppConfig.from_untrusted_dict(meta.get("app_config", {}))
238
+ return generate_filecontents(
239
+ codes, names, configs, config, header_comments=meta.get("header") or None
240
+ )
241
+
242
+
243
+ def read_rows(path) -> list[dict]:
244
+ "Trajectory rows from a `.jsonl` file (one per line) or a `.json` file (one row or a list of rows)"
245
+ text = Path(path).read_text()
246
+ if Path(path).suffix == ".jsonl":
247
+ return [json.loads(l) for l in text.splitlines() if l.strip()]
248
+ data = json.loads(text)
249
+ return data if isinstance(data, list) else [data]
250
+
251
+
252
+ def training_messages(row: dict, renderer) -> list:
253
+ """The row as renderer messages: tool declarations first, tool calls typed.
254
+
255
+ The renderers read `tool_call.function.name` as attributes, so JSON tool calls are validated into `ToolCall`s here.
256
+ Needs `pip install "mo-trace[tinker]"`."""
257
+ from tinker_cookbook.renderers import ToolCall
258
+
259
+ messages, system = list(row["messages"]), ""
260
+ if messages and messages[0]["role"] == "system":
261
+ system = messages.pop(0)["content"]
262
+ out = renderer.create_conversation_prefix_with_tools(row["tools"], system)
263
+ for m in messages:
264
+ m = dict(m)
265
+ if "tool_calls" in m:
266
+ m["tool_calls"] = [ToolCall.model_validate(c) for c in m["tool_calls"]]
267
+ out.append(m)
268
+ return out
269
+
270
+
271
+ def _config(path):
272
+ from .core import get_config
273
+ try: return get_config(path)
274
+ except SystemExit: return None # ad hoc use outside a motrace project
275
+
276
+ def nb_trajectories(paths=None, out=None, **kw) -> list[Path]:
277
+ """Convert notebooks (files or directories; default: `nbs_path`) to trajectories; return the files written.
278
+
279
+ `out` ending in `.jsonl` collects every row in that one file; otherwise it is a directory (default: `traces_path`,
280
+ else `traces`) that gets `<notebook>.jsonl` per notebook, mirroring subfolders."""
281
+ from .core import nbglob
282
+ cfg = _config(paths[0] if paths else None)
283
+ if not paths:
284
+ if cfg is None: raise SystemExit('motrace-convert: name a notebook, or run inside a motrace project')
285
+ paths = [cfg.nbs_path]
286
+ jobs = [] # (notebook, its path relative to the output directory)
287
+ for p in map(Path, paths):
288
+ jobs += [(nb, nb.relative_to(p.resolve()) if p.is_dir() else Path(nb.name)) for nb in nbglob(p, p)]
289
+ out = Path(out or (cfg and cfg.traces_path) or 'traces')
290
+ rows = [(rel, json.dumps(to_trajectory(nb, **kw), ensure_ascii=False) + '\n') for nb, rel in jobs]
291
+ if out.suffix == '.jsonl':
292
+ out.parent.mkdir(parents=True, exist_ok=True)
293
+ out.write_text(''.join(r for _, r in rows))
294
+ return [out] if rows else []
295
+ written = []
296
+ for rel, row in rows:
297
+ f = (out/rel).with_suffix('.jsonl')
298
+ f.parent.mkdir(parents=True, exist_ok=True)
299
+ f.write_text(row)
300
+ written.append(f)
301
+ return written
302
+
303
+ def nb_from_trajectories(paths, out='.', force=False) -> list[Path]:
304
+ """Rebuild notebooks from trajectory files; return the files written.
305
+
306
+ `out` ending in `.py` names the notebook (one row only); otherwise it is a directory that gets each row's original
307
+ notebook file name. Existing files with different contents are only replaced with `force`."""
308
+ rows = [r for p in paths for r in read_rows(p)]
309
+ out = Path(out)
310
+ if out.suffix == '.py' and len(rows) != 1: raise SystemExit(f'motrace-convert: {len(rows)} trajectories, one {out}')
311
+ plan = [(out if out.suffix == '.py' else out/Path(r['metadata']['notebook']).name, to_notebook(r)) for r in rows]
312
+ if not force:
313
+ clash = [str(f) for f, src in plan if f.exists() and f.read_text() != src]
314
+ if clash: raise SystemExit(f'motrace-convert: would overwrite {", ".join(clash)} (pass --force)')
315
+ for f, src in plan:
316
+ f.parent.mkdir(parents=True, exist_ok=True)
317
+ f.write_text(src)
318
+ return [f for f, _ in plan]
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "mo-trace"
7
- version = "0.2.0"
7
+ dynamic = ["version"]
8
8
  description = "nbdev-style literate programming for marimo notebooks"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -29,3 +29,6 @@ include = ["motrace", "tests", "README.md"]
29
29
 
30
30
  [tool.hatch.build.targets.wheel]
31
31
  packages = ["motrace"]
32
+
33
+ [tool.hatch.version]
34
+ path = "motrace/__init__.py"
@@ -87,7 +87,7 @@ def test_render_for_inkling(ro):
87
87
 
88
88
  def test_cli_and_loaders(tmp_path):
89
89
  pytest.importorskip('tinker_cookbook')
90
- r = run(['motrace-convert', str(TINYLM), '-o', str(tmp_path/'out')], tmp_path)
90
+ r = run(['motrace-convert', str(TINYLM), '--pi', '-o', str(tmp_path/'out')], tmp_path)
91
91
  assert '12 assistant turns' in r.stdout
92
92
  [d] = load_sft(tmp_path/'out/sft.jsonl')
93
93
  assert d.model_input.length == len(d.loss_fn_inputs['weights'].data)
@@ -0,0 +1,268 @@
1
+ """motrace-convert (default mode): notebook <-> run_cell trajectory."""
2
+
3
+ import hashlib, json, shutil
4
+ from pathlib import Path
5
+
6
+ import pytest
7
+ from marimo._ast.cell import CellConfig
8
+ from marimo._ast.codegen import generate_filecontents
9
+ from conftest import mk_marimo, run
10
+ from motrace.core import clean_text
11
+ from motrace.trajectory import (
12
+ NOT_RECORDED,
13
+ default_session,
14
+ narration,
15
+ read_cells,
16
+ to_notebook,
17
+ to_trajectory,
18
+ )
19
+
20
+ EX = Path(__file__).parent.parent / "examples"
21
+ NOTEBOOKS = [
22
+ EX / "interview/candidate/nbs/interview_1.py",
23
+ EX / "interview/reference/nbs/interview_1.py",
24
+ EX / "tinylm/jobs/tinylm.py",
25
+ ]
26
+ CANDIDATE = NOTEBOOKS[0] # the one with a recorded session
27
+
28
+
29
+ def narrated(path, header=None):
30
+ "A notebook with narration cells (hidden raw `mo.md`), a setup cell, a named cell and a hidden code cell"
31
+ codes = [
32
+ "import marimo as mo",
33
+ 'mo.md(r"""\n# Squares\n\nWe square things.\n""")',
34
+ "x = 3",
35
+ 'mo.md(r"""\nNow a reusable function.\n""")',
36
+ 'mo.md(r"""\nSecond thought.\n""")',
37
+ "def sq(v): return v * v",
38
+ "print(sq(x))",
39
+ 'mo.md(r"""\nDone.\n""")',
40
+ ]
41
+ names = ["setup", "_", "_", "_", "_", "sq", "_", "_"]
42
+ hidden = {1, 3, 4, 6, 7}
43
+ path.parent.mkdir(parents=True, exist_ok=True)
44
+ path.write_text(
45
+ generate_filecontents(
46
+ codes,
47
+ names,
48
+ [CellConfig(hide_code=i in hidden) for i in range(len(codes))],
49
+ header_comments=header,
50
+ )
51
+ )
52
+ return path
53
+
54
+
55
+ @pytest.fixture(params=NOTEBOOKS, ids=lambda p: f"{p.parent.parent.name}/{p.stem}")
56
+ def converted(request):
57
+ return request.param, to_trajectory(request.param)
58
+
59
+
60
+ def test_round_trip_gives_the_clean_notebook(converted, tmp_path):
61
+ """The regenerated notebook is exactly what motrace-clean writes, and a fixed point.
62
+
63
+ It can differ from the file on disk: marimo's serializer derives each cell's signature and promotes reusable
64
+ functions to `@app.function`, and a file saved before later edits (or by hand) may not be in that form yet."""
65
+ nb, row = converted
66
+ back = tmp_path/nb.name
67
+ back.write_text(to_notebook(row))
68
+ assert back.read_text() == clean_text(nb.read_text(), nb)
69
+ assert to_notebook(to_trajectory(back)) == back.read_text()
70
+
71
+
72
+ def test_message_structure(converted):
73
+ nb, row = converted
74
+ msgs = row["messages"]
75
+ assert [m["role"] for m in msgs[:2]] == ["system", "user"]
76
+ cells, _, _ = read_cells(nb)
77
+ calls = [
78
+ c for m in msgs if m["role"] == "assistant" for c in m.get("tool_calls", [])
79
+ ]
80
+ assert (
81
+ len(calls)
82
+ == sum(narration(c) is None for c in cells)
83
+ == row["metadata"]["code_cells"]
84
+ )
85
+ for i, m in enumerate(msgs):
86
+ for call in m.get("tool_calls", []):
87
+ assert len(m["tool_calls"]) == 1 and call["function"]["name"] == "run_cell"
88
+ assert isinstance(json.loads(call["function"]["arguments"])["code"], str) # empty cells stay
89
+ assert (
90
+ msgs[i + 1]["role"] == "tool"
91
+ and msgs[i + 1]["tool_call_id"] == call["id"]
92
+ )
93
+ if m["role"] == "tool":
94
+ assert msgs[i - 1].get("tool_calls")
95
+ assert all(isinstance(m["content"], str) for m in msgs)
96
+
97
+
98
+ def test_outputs_match_by_code_hash_only(converted):
99
+ nb, row = converted
100
+ s = default_session(nb)
101
+ hashes = (
102
+ {c["code_hash"] for c in json.loads(s.read_text())["cells"]}
103
+ if s.exists()
104
+ else set()
105
+ )
106
+ cells, _, _ = read_cells(nb)
107
+ want = sum(
108
+ hashlib.md5(c.code.encode()).hexdigest() in hashes
109
+ for c in cells
110
+ if narration(c) is None
111
+ )
112
+ recorded = [
113
+ m
114
+ for m in row["messages"]
115
+ if m["role"] == "tool" and m["content"] != NOT_RECORDED
116
+ ]
117
+ assert row["metadata"]["outputs_recorded"] == len(recorded) == want
118
+ if nb == CANDIDATE:
119
+ assert want == 3
120
+
121
+
122
+ def test_narration_and_tool_args(tmp_path):
123
+ row = to_trajectory(narrated(tmp_path / "sq.py"))
124
+ msgs = row["messages"]
125
+ assert msgs[1]["content"] == "Build the notebook for: Squares"
126
+ a = [m for m in msgs if m["role"] == "assistant"]
127
+ assert [m["content"] for m in a] == [
128
+ "",
129
+ "# Squares\n\nWe square things.",
130
+ "Now a reusable function.",
131
+ "Second thought.",
132
+ "",
133
+ "Done.",
134
+ ]
135
+ args = [
136
+ json.loads(m["tool_calls"][0]["function"]["arguments"])
137
+ for m in a
138
+ if "tool_calls" in m
139
+ ]
140
+ assert args == [
141
+ {"code": "import marimo as mo", "name": "setup"},
142
+ {"code": "x = 3"},
143
+ {"code": "def sq(v): return v * v", "name": "sq"},
144
+ {"code": "print(sq(x))", "hide_code": True},
145
+ ]
146
+ assert (
147
+ "tool_calls" not in a[2] and "tool_calls" not in a[-1]
148
+ ) # back-to-back and trailing narration
149
+ assert row["metadata"] | {"notebook": None} == {
150
+ "notebook": None,
151
+ "app_config": {},
152
+ "cells": 8,
153
+ "code_cells": 4,
154
+ "outputs_recorded": 0,
155
+ }
156
+ assert all(m["content"] == NOT_RECORDED for m in msgs if m["role"] == "tool")
157
+
158
+
159
+ def test_visible_or_named_markdown_is_code(tmp_path):
160
+ nb = mk_marimo(
161
+ tmp_path / "v.py",
162
+ ["import marimo as mo", 'mo.md(r"""\nShown, not narration.\n""")'],
163
+ )
164
+ assert to_trajectory(nb)["metadata"]["code_cells"] == 2
165
+
166
+
167
+ def test_header_and_app_config_survive(tmp_path):
168
+ hdr = '# /// script\n# dependencies = ["marimo"]\n# ///\n"""A notebook."""'
169
+ nb = narrated(tmp_path / "h.py", header=hdr)
170
+ nb.write_text(nb.read_text().replace("marimo.App()", 'marimo.App(width="medium")'))
171
+ row = to_trajectory(nb)
172
+ assert row["metadata"]["app_config"] == {"width": "medium"}
173
+ assert to_notebook(row) == nb.read_text()
174
+
175
+
176
+ def test_unsupported_cell_config_is_rejected(tmp_path):
177
+ nb = tmp_path / "d.py"
178
+ nb.write_text(generate_filecontents(["x = 1"], ["_"], [CellConfig(disabled=True)]))
179
+ with pytest.raises(ValueError, match="disabled"):
180
+ to_trajectory(nb)
181
+
182
+
183
+ def test_renders_as_supervised_data(tmp_path):
184
+ pytest.importorskip("tinker_cookbook")
185
+ from tinker_cookbook.renderers import TrainOnWhat
186
+ from motrace.convert import MODEL, _renderer
187
+ from motrace.trajectory import training_messages
188
+
189
+ renderer = _renderer(MODEL)
190
+ row = to_trajectory(CANDIDATE)
191
+ model_input, weights = renderer.build_supervised_example(
192
+ training_messages(row, renderer),
193
+ train_on_what=TrainOnWhat.ALL_ASSISTANT_MESSAGES,
194
+ )
195
+ tokens = model_input.to_ints()
196
+ assert len(tokens) == len(weights)
197
+ trained = renderer.tokenizer.decode([t for t, w in zip(tokens, weights) if w > 0])
198
+ context = renderer.tokenizer.decode([t for t, w in zip(tokens, weights) if w == 0])
199
+ assert (
200
+ "run_cell" in trained and "run_cell" in context
201
+ ) # calls are trained, and declared in the prompt
202
+ assert row["messages"][1]["content"] in context and "analyze_logs" in trained
203
+
204
+
205
+ # ------------------------------------------------------------------ CLI
206
+
207
+
208
+ def project(tmp_path, traces=None):
209
+ proj = tmp_path / "p"
210
+ (proj / "jobs").mkdir(parents=True)
211
+ extra = f'traces_path = "{traces}"\n' if traces else ""
212
+ (proj / "pyproject.toml").write_text(
213
+ f'[project]\nname = "pkg"\n\n[tool.motrace]\n{extra}'
214
+ )
215
+ narrated(proj / "jobs/00_sq.py")
216
+ narrated(proj / "jobs/sub/01_sq.py")
217
+ mk_marimo(proj / "jobs/_draft.py", ["x = 1"]) # skipped, like export
218
+ return proj
219
+
220
+
221
+ def test_cli_round_trip(tmp_path):
222
+ proj = project(tmp_path)
223
+ r = run(["motrace-convert"], proj) # default: nbs_path -> traces/
224
+ assert (
225
+ sorted(str(p.relative_to(proj)) for p in (proj / "traces").rglob("*.jsonl"))
226
+ == ["traces/00_sq.jsonl", "traces/sub/01_sq.jsonl"]
227
+ and r.stdout.count("wrote") == 2
228
+ )
229
+ run(["motrace-convert", "jobs", "-o", "all.jsonl"], proj)
230
+ assert len((proj / "all.jsonl").read_text().splitlines()) == 2
231
+ run(
232
+ ["motrace-convert", "all.jsonl", "-o", "back"], proj
233
+ ) # .jsonl input goes back to notebooks
234
+ assert (proj / "back/00_sq.py").read_text() == (proj / "jobs/00_sq.py").read_text()
235
+ assert (proj / "back/01_sq.py").read_text() == (
236
+ proj / "jobs/sub/01_sq.py"
237
+ ).read_text()
238
+ shutil.copy(proj / "traces/00_sq.jsonl", proj / "t.txt")
239
+ run(["motrace-convert", "t.txt", "--to-notebook", "-o", "one.py"], proj)
240
+ assert (proj / "one.py").read_text() == (proj / "jobs/00_sq.py").read_text()
241
+
242
+
243
+ def test_cli_refuses_to_overwrite(tmp_path):
244
+ proj = project(tmp_path)
245
+ run(["motrace-convert", "jobs/00_sq.py", "-o", "x.jsonl"], proj)
246
+ nb = proj / "jobs/00_sq.py"
247
+ nb.write_text(nb.read_text().replace("x = 3", "x = 4"))
248
+ r = run(["motrace-convert", "x.jsonl", "-o", "jobs"], proj, check=False)
249
+ assert r.returncode and "would overwrite" in r.stderr and "x = 4" in nb.read_text()
250
+ run(["motrace-convert", "x.jsonl", "-o", "jobs", "--force"], proj)
251
+ assert "x = 3" in nb.read_text()
252
+
253
+
254
+ def test_cli_outside_a_project(tmp_path):
255
+ nb = narrated(tmp_path / "sq.py")
256
+ run(["motrace-convert", str(nb)], tmp_path)
257
+ assert (tmp_path / "traces/sq.jsonl").exists()
258
+ r = run(["motrace-convert"], tmp_path, check=False)
259
+ assert r.returncode and "motrace project" in r.stderr
260
+
261
+
262
+ def test_prepare_writes_traces_when_configured(tmp_path):
263
+ proj = project(tmp_path, traces="data/traces")
264
+ r = run(["motrace-prepare"], proj)
265
+ assert "Success." in r.stdout and (proj / "data/traces/sub/01_sq.jsonl").exists()
266
+ proj2 = project(tmp_path / "q")
267
+ run(["motrace-prepare"], proj2)
268
+ assert not (proj2 / "traces").exists()
File without changes
File without changes
File without changes
File without changes