codejourney 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.
@@ -0,0 +1,297 @@
1
+ """Static source analysis for loop, condition, and warning metadata."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import builtins
7
+ from dataclasses import dataclass
8
+ from typing import Dict, Iterable, Optional, Tuple
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class LoopInfo:
13
+ loop_id: str
14
+ kind: str
15
+ line_number: int
16
+ end_line: int
17
+ body_start: int
18
+ body_end: int
19
+ header: str
20
+ total_iterations: Optional[int]
21
+
22
+ def contains(self, line_number: int) -> bool:
23
+ return self.body_start <= line_number <= self.body_end
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class ConditionInfo:
28
+ condition_id: str
29
+ kind: str
30
+ line_number: int
31
+ body_start: int
32
+ body_end: int
33
+ expression: str
34
+
35
+ def body_contains(self, line_number: int) -> bool:
36
+ return self.body_start <= line_number <= self.body_end
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class EducationalWarning:
41
+ code: str
42
+ message: str
43
+ line_number: Optional[int] = None
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class ProgramAnalysis:
48
+ loops: Tuple[LoopInfo, ...]
49
+ conditions: Tuple[ConditionInfo, ...]
50
+ warnings: Tuple[EducationalWarning, ...]
51
+
52
+ @property
53
+ def loops_by_line(self) -> Dict[int, LoopInfo]:
54
+ return {loop.line_number: loop for loop in self.loops}
55
+
56
+ @property
57
+ def conditions_by_line(self) -> Dict[int, ConditionInfo]:
58
+ return {condition.line_number: condition for condition in self.conditions}
59
+
60
+
61
+ def _block_span(statements: Iterable[ast.stmt]) -> Tuple[int, int]:
62
+ statements = tuple(statements)
63
+ if not statements:
64
+ return 0, -1
65
+ start = min(statement.lineno for statement in statements)
66
+ end = max(getattr(statement, "end_lineno", statement.lineno) for statement in statements)
67
+ return start, end
68
+
69
+
70
+ def _known_iterable_length(node: ast.AST) -> Optional[int]:
71
+ try:
72
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
73
+ if node.func.id == "range":
74
+ args = [ast.literal_eval(argument) for argument in node.args]
75
+ if all(type(argument) is int for argument in args) and 1 <= len(args) <= 3:
76
+ return len(range(*args))
77
+ value = ast.literal_eval(node)
78
+ if type(value) in (list, tuple, set, dict, str, bytes):
79
+ return len(value)
80
+ except (ValueError, TypeError, MemoryError):
81
+ return None
82
+ return None
83
+
84
+
85
+ class _Analyzer(ast.NodeVisitor):
86
+ def __init__(self) -> None:
87
+ self.loops = []
88
+ self.conditions = []
89
+ self.warnings = []
90
+ self._loop_number = 0
91
+ self._condition_number = 0
92
+ self._warning_keys = set()
93
+
94
+ def _warn(self, code: str, message: str, line_number: Optional[int]) -> None:
95
+ key = code, line_number
96
+ if key not in self._warning_keys:
97
+ self._warning_keys.add(key)
98
+ self.warnings.append(EducationalWarning(code, message, line_number))
99
+
100
+ def _add_loop(self, node: ast.AST, kind: str, header: str, total: Optional[int]) -> None:
101
+ body = getattr(node, "body", ())
102
+ body_start, body_end = _block_span(body)
103
+ line_number = node.lineno
104
+ self._loop_number += 1
105
+ loop_id = f"loop-{self._loop_number}"
106
+ loop = LoopInfo(
107
+ loop_id=loop_id,
108
+ kind=kind,
109
+ line_number=line_number,
110
+ end_line=getattr(node, "end_lineno", line_number),
111
+ body_start=body_start,
112
+ body_end=body_end,
113
+ header=header,
114
+ total_iterations=total,
115
+ )
116
+ self.loops.append(loop)
117
+ for statement in body:
118
+ self.visit(statement)
119
+
120
+ iterated_name = None
121
+ if kind == "for" and isinstance(node, ast.For):
122
+ if isinstance(node.iter, ast.Name):
123
+ iterated_name = node.iter.id
124
+ elif (
125
+ isinstance(node.iter, ast.Call)
126
+ and isinstance(node.iter.func, ast.Name)
127
+ and node.iter.func.id in {"enumerate", "iter", "reversed"}
128
+ and node.iter.args
129
+ and isinstance(node.iter.args[0], ast.Name)
130
+ ):
131
+ iterated_name = node.iter.args[0].id
132
+ if iterated_name is not None:
133
+ for statement in ast.walk(node):
134
+ if statement is node:
135
+ continue
136
+ mutation_name = None
137
+ if isinstance(statement, ast.Call) and isinstance(statement.func, ast.Attribute):
138
+ if statement.func.attr in {"append", "extend", "insert", "pop", "remove", "clear", "sort", "reverse"}:
139
+ if isinstance(statement.func.value, ast.Name):
140
+ mutation_name = statement.func.value.id
141
+ elif isinstance(statement, (ast.Assign, ast.AnnAssign, ast.AugAssign, ast.Delete)):
142
+ if isinstance(statement, (ast.Assign, ast.Delete)):
143
+ targets = statement.targets
144
+ else:
145
+ targets = [getattr(statement, "target", None)]
146
+ for target in targets:
147
+ for item in ast.walk(target) if target is not None else ():
148
+ if isinstance(item, ast.Subscript) and isinstance(item.value, ast.Name):
149
+ mutation_name = item.value.id
150
+ elif (
151
+ isinstance(statement, ast.AugAssign)
152
+ and isinstance(item, ast.Name)
153
+ and item is target
154
+ ):
155
+ mutation_name = item.id
156
+ if mutation_name == iterated_name:
157
+ self._warn(
158
+ "list-mutated-during-iteration",
159
+ f"'{iterated_name}' may be changed while it is being iterated over.",
160
+ getattr(statement, "lineno", line_number),
161
+ )
162
+
163
+ for statement in ast.walk(node):
164
+ if statement is node:
165
+ continue
166
+ if isinstance(statement, ast.Break):
167
+ self._warn(
168
+ "break-first-iteration",
169
+ "This loop can stop with `break` during its first iteration.",
170
+ statement.lineno,
171
+ )
172
+ elif isinstance(statement, ast.Return):
173
+ self._warn(
174
+ "return-first-iteration",
175
+ "This function can return during a loop's first iteration.",
176
+ statement.lineno,
177
+ )
178
+
179
+ for statement in getattr(node, "orelse", ()):
180
+ self.visit(statement)
181
+
182
+ def visit_For(self, node: ast.For) -> None:
183
+ self._add_loop(node, "for", f"for {ast.unparse(node.target)} in {ast.unparse(node.iter)}", _known_iterable_length(node.iter))
184
+
185
+ def visit_AsyncFor(self, node: ast.AsyncFor) -> None:
186
+ self._add_loop(node, "for", f"async for {ast.unparse(node.target)} in {ast.unparse(node.iter)}", None)
187
+
188
+ def visit_While(self, node: ast.While) -> None:
189
+ self._add_loop(node, "while", f"while {ast.unparse(node.test)}", None)
190
+ self._add_condition(node, "while", node.test, node.body)
191
+
192
+ def visit_If(self, node: ast.If) -> None:
193
+ self._add_condition(node, "if", node.test, node.body)
194
+ for statement in node.body:
195
+ self.visit(statement)
196
+ for statement in node.orelse:
197
+ self.visit(statement)
198
+
199
+ def _add_condition(
200
+ self,
201
+ node: ast.AST,
202
+ kind: str,
203
+ expression: ast.AST,
204
+ body: Iterable[ast.stmt],
205
+ ) -> None:
206
+ body_start, body_end = _block_span(body)
207
+ self._condition_number += 1
208
+ self.conditions.append(
209
+ ConditionInfo(
210
+ condition_id=f"condition-{self._condition_number}",
211
+ kind=kind,
212
+ line_number=node.lineno,
213
+ body_start=body_start,
214
+ body_end=body_end,
215
+ expression=ast.unparse(expression),
216
+ )
217
+ )
218
+
219
+ def visit_Name(self, node: ast.Name) -> None:
220
+ if isinstance(node.ctx, (ast.Store, ast.Param)) and node.id in vars(builtins):
221
+ self._warn(
222
+ "builtin-shadowing",
223
+ f"'{node.id}' shadows a Python built-in name.",
224
+ node.lineno,
225
+ )
226
+
227
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
228
+ if node.name in vars(builtins):
229
+ self._warn(
230
+ "builtin-shadowing",
231
+ f"'{node.name}' shadows a Python built-in name.",
232
+ node.lineno,
233
+ )
234
+ arguments = (
235
+ node.args.posonlyargs
236
+ + node.args.args
237
+ + node.args.kwonlyargs
238
+ + ([node.args.vararg] if node.args.vararg is not None else [])
239
+ + ([node.args.kwarg] if node.args.kwarg is not None else [])
240
+ )
241
+ for argument in arguments:
242
+ if argument.arg in vars(builtins):
243
+ self._warn(
244
+ "builtin-shadowing",
245
+ f"'{argument.arg}' shadows a Python built-in name.",
246
+ argument.lineno if hasattr(argument, "lineno") else node.lineno,
247
+ )
248
+ for statement in node.body:
249
+ self.visit(statement)
250
+
251
+ visit_AsyncFunctionDef = visit_FunctionDef
252
+
253
+ def visit_Import(self, node: ast.Import) -> None:
254
+ for imported in node.names:
255
+ name = imported.asname or imported.name.split(".", 1)[0]
256
+ if name in vars(builtins):
257
+ self._warn(
258
+ "builtin-shadowing",
259
+ f"'{name}' shadows a Python built-in name.",
260
+ node.lineno,
261
+ )
262
+
263
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
264
+ for imported in node.names:
265
+ name = imported.asname or imported.name
266
+ if name in vars(builtins):
267
+ self._warn(
268
+ "builtin-shadowing",
269
+ f"'{name}' shadows a Python built-in name.",
270
+ node.lineno,
271
+ )
272
+
273
+ def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None:
274
+ if node.name in vars(builtins):
275
+ self._warn(
276
+ "builtin-shadowing",
277
+ f"'{node.name}' shadows a Python built-in name.",
278
+ node.lineno,
279
+ )
280
+ self.generic_visit(node)
281
+
282
+ def visit_ClassDef(self, node: ast.ClassDef) -> None:
283
+ if node.name in vars(builtins):
284
+ self._warn("builtin-shadowing", f"'{node.name}' shadows a Python built-in name.", node.lineno)
285
+ for statement in node.body:
286
+ self.visit(statement)
287
+
288
+
289
+ def analyze_source(source: str) -> ProgramAnalysis:
290
+ tree = ast.parse(source)
291
+ analyzer = _Analyzer()
292
+ analyzer.visit(tree)
293
+ return ProgramAnalysis(
294
+ loops=tuple(analyzer.loops),
295
+ conditions=tuple(analyzer.conditions),
296
+ warnings=tuple(analyzer.warnings),
297
+ )
@@ -0,0 +1,396 @@
1
+ """Notebook-safe, CSS-only rendering for CodeJourney trace data."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ import json
7
+ import math
8
+ import uuid
9
+ from dataclasses import asdict, is_dataclass
10
+ from typing import Any
11
+
12
+ from . import CollectionSnapshot, ObjectSnapshot, TraceEvent, TraceResult
13
+
14
+
15
+ def _json_value(value: Any) -> Any:
16
+ if value is None or type(value) in (bool, int, str):
17
+ return value
18
+ if type(value) is float:
19
+ return value if math.isfinite(value) else str(value)
20
+ if type(value) is bytes:
21
+ return {"type": "bytes", "hex": value.hex()}
22
+ if type(value) in (list, tuple):
23
+ return [_json_value(item) for item in value]
24
+ if isinstance(value, ObjectSnapshot):
25
+ return {"type": value.type_name}
26
+ if isinstance(value, CollectionSnapshot):
27
+ return {"type": value.type_name, "items": _json_value(value.items)}
28
+ if is_dataclass(value):
29
+ return _json_value(asdict(value))
30
+ if type(value) is dict:
31
+ return {str(key): _json_value(item) for key, item in value.items()}
32
+ return {"type": type(value).__name__}
33
+
34
+
35
+ def _value_text(value: Any) -> str:
36
+ return json.dumps(_json_value(value), ensure_ascii=True, indent=2)
37
+
38
+
39
+ def _is_object(value: Any) -> bool:
40
+ return type(value) in (list, tuple, dict, set, frozenset) or isinstance(
41
+ value, (CollectionSnapshot, ObjectSnapshot)
42
+ )
43
+
44
+
45
+ def _variable_objects(event: TraceEvent, scope: str) -> tuple[str, str]:
46
+ aliases = {alias.name: alias.linked_to for alias in event.aliases}
47
+
48
+ def canonical_name(name: str) -> str:
49
+ seen = set()
50
+ while name in aliases and name not in seen:
51
+ seen.add(name)
52
+ name = aliases[name]
53
+ return name
54
+
55
+ object_ids = {}
56
+ object_values = {}
57
+ variable_rows = []
58
+ for name, value in event.after.items():
59
+ safe_name = html.escape(name)
60
+ if _is_object(value):
61
+ canonical = canonical_name(name)
62
+ object_id = object_ids.get(canonical)
63
+ if object_id is None:
64
+ object_id = f"{scope}-object-{len(object_ids) + 1}"
65
+ object_ids[canonical] = object_id
66
+ object_values[canonical] = value
67
+ pointer_label = object_id.rsplit("-object-", 1)[-1]
68
+ alias_label = next(
69
+ (alias.label for alias in event.aliases if alias.name == name),
70
+ None,
71
+ )
72
+ variable_rows.append(
73
+ '<div class="cj-variable">'
74
+ f'<span class="cj-variable-name">{safe_name}</span>'
75
+ f'<a class="cj-pointer" href="#{object_id}" aria-label="View object for {safe_name}">'
76
+ f'&rarr; object {pointer_label}</a>'
77
+ + (
78
+ f'<span class="cj-alias">{html.escape(alias_label)}</span>'
79
+ if alias_label is not None
80
+ else ""
81
+ )
82
+ + "</div>"
83
+ )
84
+ else:
85
+ variable_rows.append(
86
+ '<div class="cj-variable">'
87
+ f'<span class="cj-variable-name">{safe_name}</span>'
88
+ f'<code class="cj-scalar">= {html.escape(_value_text(value))}</code>'
89
+ "</div>"
90
+ )
91
+
92
+ if not variable_rows:
93
+ variables_html = '<p class="cj-empty">No variables in this state.</p>'
94
+ objects_html = '<p class="cj-empty">No objects in this state.</p>'
95
+ return variables_html, objects_html
96
+
97
+ objects_html = []
98
+ for canonical, value in object_values.items():
99
+ object_id = object_ids[canonical]
100
+ object_number = object_id.rsplit("-object-", 1)[-1]
101
+ objects_html.append(
102
+ f'<article class="cj-object" id="{object_id}">'
103
+ f'<h4>Object {object_number}</h4>'
104
+ f"<pre>{html.escape(_value_text(value))}</pre>"
105
+ "</article>"
106
+ )
107
+ if not objects_html:
108
+ objects_html.append('<p class="cj-empty">No objects in this state.</p>')
109
+ return "\n".join(variable_rows), "\n".join(objects_html)
110
+
111
+
112
+ def _diffs_html(event: TraceEvent) -> str:
113
+ if not event.variable_diffs:
114
+ return '<p class="cj-empty">No variable changes at this step.</p>'
115
+ cards = []
116
+ for diff in event.variable_diffs:
117
+ detail = (
118
+ f"Before: {_value_text(diff.before)}\n"
119
+ f"After: {_value_text(diff.after)}"
120
+ )
121
+ if diff.list_indices:
122
+ detail += "\nChanged list indices: " + ", ".join(
123
+ str(index) for index in diff.list_indices
124
+ )
125
+ if diff.dictionary_keys:
126
+ detail += "\nChanged dictionary keys: " + _value_text(
127
+ diff.dictionary_keys
128
+ )
129
+ cards.append(
130
+ '<article class="cj-diff">'
131
+ f"<strong>{html.escape(diff.name)} · {html.escape(diff.change)}</strong>"
132
+ f"<pre>{html.escape(detail)}</pre>"
133
+ "</article>"
134
+ )
135
+ return "\n".join(cards)
136
+
137
+
138
+ def _view_html(result: TraceResult, event: TraceEvent, index: int, scope: str) -> str:
139
+ source_lines = result.source.splitlines()
140
+ line_markup = "\n".join(
141
+ f'<span class="cj-source-line{" cj-current" if number == event.line_number else ""}">'
142
+ f'<span class="cj-line-number">{number:>3}</span> '
143
+ f"{html.escape(line)}</span>"
144
+ for number, line in enumerate(source_lines, start=1)
145
+ )
146
+ if not line_markup:
147
+ line_markup = '<span class="cj-empty">No source lines.</span>'
148
+
149
+ variables_html, objects_html = _variable_objects(event, f"{scope}-{index}")
150
+ iteration_text = (
151
+ event.loop_iterations[-1].label
152
+ if event.loop_iterations
153
+ else "No loop iteration selected"
154
+ )
155
+ boundary = next(
156
+ (item for item in event.loop_boundaries if item.kind == "start"),
157
+ None,
158
+ )
159
+ if boundary is not None:
160
+ total = boundary.total_iterations if boundary.total_iterations is not None else "?"
161
+ iteration_text = f"Iteration {boundary.iteration_index + 1} of {total} · iteration begins"
162
+ aliases_text = "; ".join(alias.label for alias in event.aliases)
163
+ if aliases_text:
164
+ iteration_text += " · " + aliases_text
165
+
166
+ condition_html = (
167
+ f'<p class="cj-condition">{html.escape(event.condition_preview.preview)}</p>'
168
+ if event.condition_preview is not None
169
+ else ""
170
+ )
171
+ warning_html = "".join(
172
+ f'<li class="cj-warning">{html.escape(warning.message)}'
173
+ + (
174
+ f' <span class="cj-muted">(line {warning.line_number})</span>'
175
+ if warning.line_number is not None
176
+ else ""
177
+ )
178
+ + "</li>"
179
+ for warning in result.warnings
180
+ )
181
+ error_html = ""
182
+ if result.error is not None:
183
+ error_html = (
184
+ '<li class="cj-error">'
185
+ + html.escape(result.error.type_name)
186
+ + ": "
187
+ + html.escape(result.error.message)
188
+ + "</li>"
189
+ )
190
+ if result.truncated:
191
+ warning_html += (
192
+ '<li class="cj-warning">Trace stopped after '
193
+ + str(result.max_steps)
194
+ + " steps. The displayed execution is partial.</li>"
195
+ )
196
+
197
+ return f"""<section class="cj-view" data-index="{index}">
198
+ <div class="cj-state"><span class="cj-badge">{html.escape(iteration_text)}</span>{condition_html}</div>
199
+ <div class="cj-layout">
200
+ <section class="cj-panel"><h3>Source</h3><pre class="cj-source"><code>{line_markup}</code></pre></section>
201
+ <section class="cj-panel">
202
+ <h3>Variables</h3><div class="cj-variables">{variables_html}</div>
203
+ <h3>Objects</h3><div class="cj-objects">{objects_html}</div>
204
+ <h3>What changed?</h3><div class="cj-diffs">{_diffs_html(event)}</div>
205
+ <h3>Learning notes</h3><ul>{warning_html}{error_html}</ul>
206
+ </section>
207
+ </div>
208
+ </section>"""
209
+
210
+
211
+ def render_html(result: TraceResult) -> str:
212
+ """Render a self-contained, notebook-safe interactive HTML view.
213
+
214
+ The timeline uses radio inputs and labels so it remains interactive in
215
+ notebook renderers that intentionally disable JavaScript in HTML output.
216
+ """
217
+ scope = f"cj-{uuid.uuid4().hex}"
218
+ events = tuple(
219
+ event
220
+ for event in result.events
221
+ if event.line_number is not None and event.line_number > 0
222
+ )
223
+ if events:
224
+ initial_index = next(
225
+ (
226
+ index
227
+ for index, event in enumerate(events)
228
+ if event.after or event.variable_diffs
229
+ ),
230
+ 0,
231
+ )
232
+ else:
233
+ initial_index = -1
234
+
235
+ controls = []
236
+ timeline = []
237
+ views = []
238
+ selectors = []
239
+ count = len(events)
240
+ for index, event in enumerate(events):
241
+ selector_id = f"{scope}-step-{index}"
242
+ selectors.append(
243
+ f'<input class="cj-selector" type="radio" name="{scope}-steps" '
244
+ f'id="{selector_id}"{ " checked" if index == initial_index else ""}>'
245
+ )
246
+
247
+ control_labels = []
248
+ targets = {
249
+ "prev": index - 1 if index > 0 else None,
250
+ "next": index + 1 if index + 1 < count else None,
251
+ }
252
+ next_change = next(
253
+ (
254
+ candidate
255
+ for candidate in range(index + 1, count)
256
+ if events[candidate].variable_diffs
257
+ ),
258
+ None,
259
+ )
260
+ previous_iteration = next(
261
+ (
262
+ candidate
263
+ for candidate in range(index - 1, -1, -1)
264
+ if any(
265
+ boundary.kind == "start"
266
+ for boundary in events[candidate].loop_boundaries
267
+ )
268
+ ),
269
+ None,
270
+ )
271
+ next_iteration = next(
272
+ (
273
+ candidate
274
+ for candidate in range(index + 1, count)
275
+ if any(
276
+ boundary.kind == "start"
277
+ for boundary in events[candidate].loop_boundaries
278
+ )
279
+ ),
280
+ None,
281
+ )
282
+ targets.update(
283
+ {
284
+ "change": next_change,
285
+ "prev-iteration": previous_iteration,
286
+ "next-iteration": next_iteration,
287
+ }
288
+ )
289
+ for action, label in (
290
+ ("prev", "Prev"),
291
+ ("next", "Next"),
292
+ ("prev-iteration", "Prev Iteration"),
293
+ ("next-iteration", "Next Iteration"),
294
+ ("change", "Jump to Next Change"),
295
+ ):
296
+ target = targets[action]
297
+ if target is None:
298
+ control_labels.append(
299
+ f'<span class="cj-button cj-disabled" aria-disabled="true">{label}</span>'
300
+ )
301
+ else:
302
+ control_labels.append(
303
+ f'<label class="cj-button" role="button" for="{scope}-step-{target}">'
304
+ f"{label}</label>"
305
+ )
306
+ controls.append(
307
+ f'<div class="cj-controls" data-step-controls="{index}">'
308
+ + "".join(control_labels)
309
+ + f'<span class="cj-counter">{index + 1} / {count}</span></div>'
310
+ )
311
+ timeline.append(
312
+ f'<label class="cj-tick" role="button" for="{selector_id}" '
313
+ f'aria-label="Go to step {index + 1}" title="Step {index + 1}">'
314
+ f"{index + 1}</label>"
315
+ )
316
+ views.append(_view_html(result, event, index, scope))
317
+
318
+ rules = []
319
+ for index in range(count):
320
+ selector_id = f"{scope}-step-{index}"
321
+ rules.append(
322
+ f"#{selector_id}:checked ~ .cj-controls[data-step-controls='{index}']"
323
+ "{display:flex}"
324
+ )
325
+ rules.append(
326
+ f"#{selector_id}:checked ~ .cj-views .cj-view[data-index='{index}']"
327
+ "{display:block}"
328
+ )
329
+ rules.append(
330
+ f"#{selector_id}:checked ~ .cj-timeline label[for='{selector_id}']"
331
+ "{background:#315fa8;color:#fff}"
332
+ )
333
+
334
+ if not events:
335
+ selector_html = '<p class="cj-empty">No execution steps captured.</p>'
336
+ controls_html = ""
337
+ timeline_html = ""
338
+ views_html = ""
339
+ else:
340
+ selector_html = "".join(selectors)
341
+ controls_html = "".join(controls)
342
+ timeline_html = (
343
+ '<div class="cj-timeline" role="group" aria-label="Execution timeline">'
344
+ + "".join(timeline)
345
+ + "</div>"
346
+ )
347
+ views_html = '<div class="cj-views">' + "".join(views) + "</div>"
348
+
349
+ return f"""<div class="codejourney {scope}">
350
+ <style>
351
+ .codejourney {{ font: 14px/1.45 system-ui, sans-serif; color: #172033; background: #fff; border: 1px solid #d5dbe6; border-radius: 10px; padding: 14px; }}
352
+ .codejourney * {{ box-sizing: border-box; }}
353
+ .cj-selector {{ position: absolute; width: 1px; height: 1px; opacity: 0; pointer-events: none; }}
354
+ .cj-controls {{ display: none; flex-wrap: wrap; align-items: center; gap: 8px; margin-bottom: 10px; }}
355
+ .cj-button {{ border: 1px solid #aeb8c8; background: #f7f9fc; border-radius: 6px; padding: 6px 10px; cursor: pointer; color: inherit; }}
356
+ .cj-button:hover {{ background: #e9eff8; }}
357
+ .cj-disabled {{ opacity: .5; cursor: default; }}
358
+ .cj-counter {{ margin-left: auto; color: #657187; font-size: 12px; }}
359
+ .cj-timeline {{ display: flex; gap: 4px; overflow-x: auto; padding: 5px 0 11px; }}
360
+ .cj-tick {{ flex: 0 0 auto; min-width: 24px; padding: 2px 6px; border-radius: 999px; background: #e8edf5; color: #34445c; text-align: center; cursor: pointer; font-size: 12px; }}
361
+ .cj-view {{ display: none; }}
362
+ .cj-layout {{ display: grid; grid-template-columns: minmax(0, 1fr) minmax(260px, .8fr); gap: 12px; }}
363
+ .cj-panel {{ min-width: 0; border: 1px solid #e1e5ec; border-radius: 8px; padding: 10px; }}
364
+ .cj-panel h3 {{ font-size: 14px; margin: 0 0 8px; }}
365
+ .cj-panel h3:not(:first-child) {{ margin-top: 14px; }}
366
+ .cj-source {{ overflow: auto; margin: 0; background: #f7f8fa; border-radius: 6px; padding: 8px; white-space: pre; }}
367
+ .cj-source-line {{ display: block; min-height: 1.45em; }}
368
+ .cj-source-line.cj-current {{ background: #fff0b3; outline: 1px solid #f1d46b; }}
369
+ .cj-line-number {{ user-select: none; color: #8490a2; }}
370
+ .cj-state {{ margin: 0 0 10px; }}
371
+ .cj-badge {{ display: inline-block; background: #e8efff; border-radius: 999px; padding: 3px 9px; font-size: 12px; }}
372
+ .cj-condition {{ margin: 8px 0 0; color: #385883; }}
373
+ .cj-variables {{ display: flex; flex-direction: column; gap: 7px; }}
374
+ .cj-variable {{ display: flex; align-items: center; gap: 8px; flex-wrap: wrap; padding: 7px 9px; background: #edf4ff; border: 1px solid #cfddf4; border-radius: 6px; }}
375
+ .cj-variable-name {{ font-weight: 650; }}
376
+ .cj-pointer {{ color: #315fa8; font-weight: 700; text-decoration: none; }}
377
+ .cj-pointer:hover {{ text-decoration: underline; }}
378
+ .cj-alias {{ color: #657187; font-size: 12px; }}
379
+ .cj-scalar {{ white-space: pre-wrap; overflow-wrap: anywhere; }}
380
+ .cj-object {{ border: 1px solid #bdc9da; border-radius: 7px; padding: 8px 10px; background: #fff; margin: 7px 0 0 18px; scroll-margin: 8px; }}
381
+ .cj-object h4 {{ font-size: 12px; color: #53647c; margin: 0 0 4px; }}
382
+ .cj-object pre {{ margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }}
383
+ .cj-diff {{ border-left: 3px solid #6688c7; background: #f7f9fd; padding: 7px 9px; margin: 7px 0; border-radius: 4px; overflow-wrap: anywhere; }}
384
+ .cj-diff pre {{ margin: 4px 0 0; white-space: pre-wrap; }}
385
+ .cj-warning {{ color: #684800; background: #fff6d8; border-radius: 5px; padding: 6px 8px; margin: 5px 0; }}
386
+ .cj-error {{ color: #8d2020; background: #fde8e8; border-radius: 5px; padding: 6px 8px; margin: 5px 0; }}
387
+ .cj-muted, .cj-empty {{ color: #657187; font-size: 12px; }}
388
+ @media (max-width: 700px) {{ .cj-layout {{ grid-template-columns: 1fr; }} }}
389
+ {''.join(rules)}
390
+ </style>
391
+ {selector_html}
392
+ {controls_html}
393
+ {timeline_html}
394
+ {views_html}
395
+ <p class="cj-muted">Educational trace, not a debugger. Code ran with this Python process's permissions; execution is not sandboxed.</p>
396
+ </div>"""