learning_graph_render.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. """Terminal renderer for the learning timeline (learned skills + memories): the desktop starmap's data
  2. (``apps/desktop/src/app/starmap``) drawn as a timeline bar chart (date rows, skill/memory bars colored by dominant
  3. category, cumulative trajectory sparkline) plus per-slice bucket metadata the TUI walks as a tree. Age gradient and
  4. memory ink are ported from the desktop source. Grids are style runs ``[text, style, alpha, hex?]``: consumers map
  5. style + brightness onto their palette; hex overrides the base color (category heatmap). Pure, stdlib-only."""
  6. from __future__ import annotations
  7. import math
  8. from collections import Counter
  9. from datetime import datetime, timezone, UTC
  10. from typing import Any, Iterable, Optional
  11. from agent.learning_graph import memory_node_id
  12. from hermes_time import safe_strftime
  13. LEAD_IN = 0.06 # time-axis.ts LEAD_IN: the oldest node sits just off recency 0.
  14. # constants.ts AGE_GRADIENT — old quiet, recent bright.
  15. AGE_OLD_INK, AGE_MID_INK, AGE_NEW_INK, AGE_MID = 0.42, 0.74, 0.95, 0.52
  16. # Style keys consumers map to base colors (brightness = the run alpha).
  17. STYLE_BG, STYLE_SKILL, STYLE_MEMORY, STYLE_LABEL, STYLE_DIM = "bg", "skill", "memory", "label", "dim"
  18. # Legend glyphs mirror NODE_SHAPE (skill = circle, memory = diamond).
  19. SKILL_GLYPH, MEMORY_GLYPH = "●", "◆"
  20. _LABEL_KEYS = tuple("123456789abc")
  21. Row = list # of runs ``[text, style, alpha, hex?]``; a grid is a list of rows
  22. def _clamp(v: float, lo: float, hi: float) -> float:
  23. return lo if v < lo else min(v, hi)
  24. def _lerp(a: float, b: float, t: float) -> float:
  25. return a + (b - a) * t
  26. def _smoothstep(p: float) -> float:
  27. p = _clamp(p, 0.0, 1.0)
  28. return p * p * (3 - 2 * p)
  29. def _is_memory(node: dict[str, Any]) -> bool:
  30. return node.get("kind") == "memory"
  31. def _node_id(node: dict[str, Any]) -> str:
  32. return str(node.get("id", ""))
  33. def _utc(ts: float) -> datetime:
  34. return datetime.fromtimestamp(ts, tz=UTC)
  35. def _lead_in(ratio: float) -> float:
  36. return LEAD_IN + (1 - LEAD_IN) * ratio
  37. def _visible_count(reveal: float, n: int) -> int:
  38. return int(_clamp(math.ceil(reveal * n), 0, n))
  39. def _node_raw_label(node: dict[str, Any]) -> str:
  40. return str(node.get("label") or node.get("id") or "unknown").strip()
  41. def _node_ts(node: dict[str, Any]) -> Optional[float]:
  42. try:
  43. return None if node.get("timestamp") is None else float(node["timestamp"])
  44. except (TypeError, ValueError):
  45. return None
  46. def recency_ink(rec: float) -> float:
  47. """Port of geometry.ts ``recencyInk`` — smoothstep age → ink alpha."""
  48. t = _clamp(rec, 0.0, 1.0)
  49. return _lerp(AGE_OLD_INK, AGE_MID_INK, _smoothstep(t / AGE_MID)) if t <= AGE_MID else _lerp(AGE_MID_INK, AGE_NEW_INK, _smoothstep((t - AGE_MID) / (1 - AGE_MID)))
  50. def format_date(ts: Optional[float]) -> str:
  51. try:
  52. dt = _utc(float(ts)) if ts else None
  53. except (ValueError, OSError, OverflowError):
  54. dt = None
  55. return f"{dt.day} {safe_strftime(dt, '%b %Y')}" if dt else "unknown"
  56. def compute_recency(nodes: list[dict[str, Any]]) -> dict[str, Any]:
  57. """Port of time-axis.ts ``computeRecency`` (id → recency ratio, timed flag).
  58. Untimed graphs (no spread of timestamps) fall back to ordinal position so
  59. every node still gets a distinct recency."""
  60. known = [t for t in (_node_ts(n) for n in nodes) if t is not None]
  61. min_ts, max_ts = (min(known), max(known)) if known else (None, None)
  62. timed = bool(known) and max_ts > min_ts
  63. ordered = sorted(nodes, key=lambda n: (_node_ts(n) if _node_ts(n) is not None else math.inf, _node_id(n)))
  64. last = max(len(ordered) - 1, 1)
  65. ord_ratio = {_node_id(n): (i / last if len(ordered) > 1 else 0.0) for i, n in enumerate(ordered)}
  66. rec = {
  67. nid: _lead_in(_clamp((ts - min_ts) / (max_ts - min_ts) if timed and ts is not None else ord_ratio.get(nid, 0.0), 0.0, 1.0))
  68. for nid, ts in ((_node_id(n), _node_ts(n)) for n in nodes)
  69. }
  70. return {"rec": rec, "timed": timed, "minTs": min_ts, "maxTs": max_ts}
  71. def _date_at(rec: dict[str, Any], reveal: float) -> Optional[float]:
  72. lo, hi = rec.get("minTs"), rec.get("maxTs")
  73. return None if not rec.get("timed") or lo is None or hi is None else round(lo + _clamp(reveal, 0, 1) * (hi - lo))
  74. # ── Color: ported from color.ts so memory ink + age fade match the desktop ──
  75. def hex_to_rgb(s: str) -> tuple[int, int, int]:
  76. s = s.strip().lstrip("#")
  77. if len(s) == 3:
  78. s = "".join(c * 2 for c in s)
  79. try:
  80. return int(s[0:2], 16), int(s[2:4], 16), int(s[4:6], 16)
  81. except (ValueError, IndexError):
  82. return 255, 215, 0
  83. def rgb_to_hex(c: tuple) -> str:
  84. return "#{:02X}{:02X}{:02X}".format(*(int(_clamp(v, 0, 255)) for v in c))
  85. def mix_rgb(a: tuple, b: tuple, t: float) -> tuple[int, int, int]:
  86. return tuple(round(_lerp(a[i], b[i], _clamp(t, 0.0, 1.0))) for i in range(3)) # type: ignore[return-value]
  87. def _rgb_to_hsl(c: tuple) -> tuple[float, float, float]:
  88. r, g, b = (x / 255 for x in c)
  89. mx, mn = max(r, g, b), min(r, g, b)
  90. light, d = (mx + mn) / 2, mx - mn
  91. if not d:
  92. return 0.0, 0.0, light
  93. s = d / (2 - mx - mn) if light > 0.5 else d / (mx + mn)
  94. h = (g - b) / d + (6 if g < b else 0) if mx == r else (b - r) / d + 2 if mx == g else (r - g) / d + 4
  95. return h * 60, s, light
  96. # Hue sextant → (r, g, b) as a permutation of (c, x, 0).
  97. _HUE_SEXTANTS = (
  98. lambda c, x: (c, x, 0.0), lambda c, x: (x, c, 0.0), lambda c, x: (0.0, c, x),
  99. lambda c, x: (0.0, x, c), lambda c, x: (x, 0.0, c), lambda c, x: (c, 0.0, x),
  100. )
  101. def _hsl_to_rgb(h: float, s: float, light: float) -> tuple[int, int, int]:
  102. hue = ((h % 360) + 360) % 360
  103. c = (1 - abs(2 * light - 1)) * s
  104. x, m = c * (1 - abs(((hue / 60) % 2) - 1)), light - c / 2
  105. return tuple(round((v + m) * 255) for v in _HUE_SEXTANTS[min(int(hue // 60), 5)](c, x)) # type: ignore[return-value]
  106. def derive_palette(primary_hex: str, *, dark: bool = True) -> dict[str, str]:
  107. """Port of color.ts ``computePalette`` (the bits a terminal needs)."""
  108. primary = hex_to_rgb(primary_hex)
  109. base, bg = ((255, 255, 255), (8, 8, 12)) if dark else ((0, 0, 0), (250, 250, 250))
  110. h, s, light = _rgb_to_hsl(primary)
  111. return {
  112. "primary": primary_hex,
  113. # Memories are drillable → primary "clickable" ink; skills are dead-ends → muted complement.
  114. "memory": rgb_to_hex(mix_rgb(primary, base, 0.12 if dark else 0.18)),
  115. "skill": rgb_to_hex(mix_rgb(_hsl_to_rgb(h + 165, max(s, 0.5), _clamp(light, 0.5, 0.7)), bg, 0.45)),
  116. "label": rgb_to_hex(mix_rgb(base, bg, 0.35)), "dim": rgb_to_hex(mix_rgb(base, bg, 0.7)), "bg": rgb_to_hex(bg),
  117. }
  118. def _node_score(node: dict[str, Any], rec: float) -> float:
  119. """Pick which visible objects deserve map markers + label rows."""
  120. return 3.5 + rec if _is_memory(node) else rec * 2 + math.sqrt(max(0.0, float(node.get("useCount", 0) or 0))) + (2.0 if node.get("pinned") else 0.0)
  121. def _node_card(node: dict[str, Any]) -> dict[str, Any]:
  122. """Shared glyph/label/meta/style fields for label rows and bucket trees."""
  123. mem, text, date = _is_memory(node), _node_raw_label(node), format_date(_node_ts(node))
  124. if mem:
  125. meta = f"{'profile memory' if node.get('memorySource') == 'profile' else 'memory'} · {date}"
  126. else:
  127. count = int(node.get("useCount", 0) or 0)
  128. meta = " · ".join([str(node.get("category") or "skill"), date] + ([f"x{count}"] if count else []) + (["pinned"] if node.get("pinned") else []))
  129. return {
  130. "glyph": MEMORY_GLYPH if mem else SKILL_GLYPH, "label": text if len(text) <= 26 else text[:23].rstrip() + "…",
  131. "meta": meta, "style": STYLE_MEMORY if mem else STYLE_SKILL,
  132. }
  133. def _skill_category_counts(nodes: Iterable[dict[str, Any]]) -> Counter:
  134. return Counter(str(n.get("category") or "skill") for n in nodes if not _is_memory(n))
  135. # ── Timeline chart frame ─────────────────────────────────────────────────────
  136. class _ChartBucket:
  137. __slots__ = ("label", "nodes", "rec", "ts")
  138. def __init__(self, label: str, ts: float):
  139. self.label, self.ts, self.rec = label, ts, 1.0
  140. self.nodes: list[dict[str, Any]] = []
  141. memories = property(lambda self: sum(1 for n in self.nodes if _is_memory(n)))
  142. skills = property(lambda self: len(self.nodes) - self.memories)
  143. total = property(lambda self: len(self.nodes))
  144. def category(self) -> Optional[str]:
  145. return max(counts, key=lambda k: counts[k]) if (counts := _skill_category_counts(self.nodes)) else None
  146. # granularity → (period key, row label) from a UTC datetime.
  147. _PERIODS: dict[str, tuple] = {
  148. "day": (lambda dt: (dt.year, dt.month, dt.day), lambda dt: f"{dt.day} {safe_strftime(dt, '%b')}"),
  149. "month": (lambda dt: (dt.year, dt.month), lambda dt: safe_strftime(dt, "%b %Y")),
  150. "year": (lambda dt: (dt.year,), lambda dt: dt.strftime("%Y")),
  151. }
  152. def _period(ts: float, granularity: str) -> tuple[tuple[int, ...], str]:
  153. return tuple(fn(_utc(ts)) for fn in _PERIODS.get(granularity, _PERIODS["year"])) # type: ignore[return-value]
  154. def _fill_even_bins(buckets: list[_ChartBucket], nodes: Iterable[dict[str, Any]], rec: dict[str, Any]) -> None:
  155. """Drop each node into the bin its recency ratio maps to (order preserved)."""
  156. for node in nodes:
  157. buckets[int(_clamp(math.floor(rec["rec"].get(_node_id(node), 0.0) * len(buckets)), 0, len(buckets) - 1))].nodes.append(node)
  158. def _build_chart_buckets(nodes: list[dict[str, Any]], rec: dict[str, Any], max_rows: int) -> list[_ChartBucket]:
  159. """Timeline rows: finest date granularity that fits, oldest → newest."""
  160. if not nodes:
  161. return []
  162. if not rec["timed"]:
  163. buckets = [_ChartBucket(f"#{i + 1}", float(i)) for i in range(min(max_rows, len(nodes)))]
  164. _fill_even_bins(buckets, sorted(nodes, key=lambda n: rec["rec"].get(_node_id(n), 0.0)), rec)
  165. return buckets
  166. chosen: Optional[list[_ChartBucket]] = None
  167. for granularity in ("day", "month", "year"):
  168. groups: dict[tuple[int, ...], _ChartBucket] = {}
  169. for node in nodes:
  170. ts = _node_ts(node)
  171. if ts is not None:
  172. key, label = _period(ts, granularity)
  173. groups.setdefault(key, _ChartBucket(label, ts)).nodes.append(node)
  174. # For short spans, keep the useful day-by-day graph even when the caller
  175. # asked for fewer rows; scrollback beats collapsing a month into one bar.
  176. if len(groups) <= max_rows or (granularity == "day" and len(groups) <= 32):
  177. chosen = [groups[key] for key in sorted(groups)]
  178. break
  179. min_ts, max_ts = rec.get("minTs"), rec.get("maxTs")
  180. if chosen is None: # even yearly buckets overflow → fall back to even time bins
  181. n_bins = max(1, max_rows)
  182. stops = (min_ts + (i / max(1, n_bins - 1)) * (max_ts - min_ts) if min_ts and max_ts else float(i) for i in range(n_bins))
  183. chosen = [_ChartBucket(format_date(ts), ts) for ts in stops]
  184. _fill_even_bins(chosen, nodes, rec)
  185. span = (max_ts - min_ts) if min_ts is not None and max_ts is not None and max_ts > min_ts else 0
  186. for bucket in chosen:
  187. bucket.rec = _lead_in((bucket.ts - min_ts) / span) if span else 1.0
  188. return chosen
  189. def _bucket_rows(buckets: list[_ChartBucket], payload: dict[str, Any]) -> list[dict[str, Any]]:
  190. cmap = category_color_map(payload)
  191. memory_lookup = {memory_node_id(card, idx): card
  192. for idx, card in enumerate(payload.get("memory", []) or []) if isinstance(card, dict)}
  193. def node_row(node: dict[str, Any]) -> dict[str, Any]:
  194. card, memory = _node_card(node), memory_lookup.get(_node_id(node))
  195. return {
  196. "id": _node_id(node), "glyph": card["glyph"], "label": card["label"], "fullLabel": _node_raw_label(node),
  197. "meta": card["meta"], "body": str(memory.get("body", "")) if memory else "", "style": card["style"],
  198. }
  199. def bucket_row(idx: int, bucket: _ChartBucket) -> dict[str, Any]:
  200. cat = bucket.category()
  201. return {
  202. "index": idx, "label": bucket.label, "date": format_date(bucket.ts),
  203. "skills": bucket.skills, "memories": bucket.memories, "total": bucket.total,
  204. "category": cat, "color": cmap.get(cat) if cat else None,
  205. # Chronological within the slice so the TUI tree reads oldest → newest.
  206. "nodes": [node_row(n) for n in sorted(bucket.nodes, key=lambda n: _node_ts(n) or bucket.ts)],
  207. }
  208. return [bucket_row(idx, bucket) for idx, bucket in enumerate(buckets)]
  209. def _category_counts(payload: dict[str, Any]) -> list[tuple[str, int]]:
  210. clusters = [(str(c.get("category")), int(c.get("count", 0))) for c in payload.get("clusters", []) or [] if c.get("category") and c.get("category") != "memory"]
  211. return clusters or sorted(_skill_category_counts(payload.get("nodes", [])).items(), key=lambda kv: (-kv[1], kv[0]))
  212. def category_color_map(payload: dict[str, Any]) -> dict[str, str]:
  213. """Deterministic, evenly-spread hue per skill category (theme-independent).
  214. Golden-angle spacing so adjacent categories never collide in color."""
  215. return {cat: rgb_to_hex(_hsl_to_rgb((i * 137.508) % 360, 0.55, 0.62)) for i, (cat, _c) in enumerate(_category_counts(payload))}
  216. def category_legend(payload: dict[str, Any], limit: int = 4) -> list[dict[str, Any]]:
  217. cmap, cats = category_color_map(payload), _category_counts(payload)
  218. out = [{"glyph": "●", "color": cmap.get(cat, ""), "label": f"{cat} ({count})"} for cat, count in cats[:limit]]
  219. return out + ([{"glyph": "·", "color": "", "label": f"+{len(cats) - limit}"}] if len(cats) > limit else [])
  220. def _trajectory_row(buckets: list[_ChartBucket], width: int, reveal: float) -> Row:
  221. """Cumulative learning curve as a compact star-path sparkline."""
  222. if not buckets:
  223. return []
  224. total, cells, acc, last = sum(b.total for b in buckets) or 1, [" "] * width, 0, 0
  225. for b in buckets[:_visible_count(reveal, len(buckets))]:
  226. acc += b.total
  227. p = round((acc / total) * (width - 1))
  228. for x in range(min(last, p), max(last, p) + 1):
  229. if 0 <= x < width and cells[x] == " ":
  230. cells[x] = "·"
  231. if 0 <= p < width:
  232. cells[p] = "✦"
  233. last = p
  234. return [["trajectory ", STYLE_LABEL, 0.55], ["".join(cells), STYLE_SKILL, 0.48]]
  235. def _bar_lengths(bucket: _ChartBucket, max_total: int, bar_w: int) -> tuple[int, int, int]:
  236. """(bar, skill, memory) cell counts; a present kind never rounds to zero."""
  237. bar_len = max(1, round((bucket.total / max_total) * bar_w)) if bucket.total else 0
  238. skill_len = max(1, round((bucket.skills / bucket.total) * bar_len)) if bucket.skills else 0
  239. if bucket.memories and skill_len == bar_len > 1:
  240. skill_len = bar_len - 1
  241. return bar_len, skill_len, bar_len - skill_len
  242. def render_graph(payload: dict[str, Any], *, cols: int = 80, rows: int = 16, reveal: float = 1.0) -> dict[str, Any]:
  243. """Render one timeline frame at ``reveal`` (0→1): date rows with proportional
  244. skill/memory bars colored by dominant category, numbered markers tied to
  245. label rows, and a cumulative trajectory sparkline underneath."""
  246. reveal, cols, rows = _clamp(reveal, 0.0, 1.0), max(44, cols), max(14, rows)
  247. nodes = list(payload.get("nodes", []))
  248. if not nodes:
  249. return {"grid": [[["no learning yet — keep using Hermes and it maps out here", STYLE_DIM, 0.7]]], "date": "", "reveal": reveal, "visible": 0}
  250. rec, cmap = compute_recency(nodes), category_color_map(payload)
  251. buckets = _build_chart_buckets(nodes, rec, max_rows=max(4, rows - 3))
  252. visible_bucket_count, max_total = _visible_count(reveal, len(buckets)), max((b.total for b in buckets), default=1) or 1
  253. label_w = min(9, max(len(b.label) for b in buckets))
  254. bar_w = max(14, cols - label_w - 16)
  255. grid: list[Row] = []
  256. labels: list[dict[str, Any]] = []
  257. visible = 0
  258. for i, bucket in enumerate(buckets[:visible_bucket_count]):
  259. visible += bucket.total
  260. ink, cat = recency_ink(bucket.rec), bucket.category()
  261. bar_len, skill_len, memory_len = _bar_lengths(bucket, max_total, bar_w)
  262. cat_hex = cmap.get(cat) if cat else None
  263. row: Row = [[f"{bucket.label:>{label_w}} ", STYLE_LABEL, ink], ["│ ", STYLE_DIM, 0.55]]
  264. if bucket.nodes and len(labels) < 6:
  265. node, marker = max(bucket.nodes, key=lambda n: _node_score(n, _node_ts(n) or bucket.ts)), _LABEL_KEYS[len(labels)]
  266. labels.append({"key": marker, **_node_card(node), "alpha": round(ink, 3)})
  267. row.append([marker, STYLE_LABEL, 0.95])
  268. elif bucket.total:
  269. row.append(["✦" if bucket.skills else "◆", STYLE_SKILL if bucket.skills else STYLE_MEMORY, ink, cat_hex if bucket.skills else None])
  270. # Skill bar colored by the day's dominant category (a learning heatmap); trailing empty space keeps
  271. # counts aligned — starmap texture lives in the trajectory row.
  272. row += ([["━" * skill_len, STYLE_SKILL, ink, cat_hex]] if skill_len else [])
  273. row += ([["◆" if memory_len == 1 else "◆" + ("━" * (memory_len - 2)) + "◆", STYLE_MEMORY, max(0.65, ink)]] if memory_len else [])
  274. row += ([[" " * (bar_w - bar_len), STYLE_BG, 1.0]] if bar_len < bar_w else []) + [[" ", STYLE_BG, 1.0], [str(bucket.skills), STYLE_SKILL, max(0.72, ink)]]
  275. row += ([["+", STYLE_DIM, 0.6], [str(bucket.memories), STYLE_MEMORY, max(0.72, ink)]] if bucket.memories else [])
  276. if i == visible_bucket_count - 1:
  277. row.append([" ◀ now", STYLE_LABEL, 0.9])
  278. elif bucket.total == max_total and max_total > 1:
  279. row.append([" ☄ peak", STYLE_LABEL, 0.75])
  280. grid.append(row)
  281. grid += [[] for _ in buckets[visible_bucket_count:]] # not-yet-revealed rows stay blank
  282. grid.append([[(" " * (label_w + 2)), STYLE_BG, 1.0], *_trajectory_row(buckets, max(12, cols - label_w - 13), reveal)])
  283. return {"grid": grid, "date": format_date(_date_at(rec, reveal)), "reveal": reveal, "visible": visible, "labels": labels}
  284. # ── Trimmings ──────────────────────────────────────────────────────────────
  285. def build_legend(payload: dict[str, Any]) -> list[dict[str, Any]]:
  286. nodes = payload.get("nodes", [])
  287. memories = sum(1 for n in nodes if _is_memory(n))
  288. return [
  289. {"glyph": SKILL_GLYPH, "style": STYLE_SKILL, "label": f"skills ({len(nodes) - memories})"},
  290. {"glyph": MEMORY_GLYPH, "style": STYLE_MEMORY, "label": f"memories ({memories})"},
  291. ]
  292. def axis_labels(payload: dict[str, Any]) -> dict[str, str]:
  293. rec = compute_recency(list(payload.get("nodes", [])))
  294. return {"start": format_date(rec["minTs"]), "end": format_date(rec["maxTs"])} if rec["timed"] else {"start": "oldest", "end": "now"}
  295. def _peak_day(payload: dict[str, Any]) -> Optional[str]:
  296. periods = [_period(ts, "day") for ts in (_node_ts(n) for n in payload.get("nodes", [])) if ts is not None]
  297. counts, labels = Counter(key for key, _label in periods), dict(periods)
  298. if not counts:
  299. return None
  300. best = max(counts, key=lambda k: counts[k])
  301. return f"busiest day {labels[best]} · {counts[best]} learned"
  302. def build_summary(payload: dict[str, Any]) -> list[str]:
  303. stats = payload.get("stats", {}) or {}
  304. learned = stats.get("learned_skills", stats.get("nodes", 0))
  305. lines = [f"{learned} learned skills · {stats.get('memory_nodes', 0)} memories · {stats.get('related_edges', 0)} skill links"]
  306. extra = ([f"{stats['memory_skill_edges']} memory↔skill links"] if stats.get("memory_skill_edges") else []) + list(filter(None, [_peak_day(payload)]))
  307. return lines + ([" · ".join(extra)] if extra else [])
  308. def render_frames(payload: dict[str, Any], *, cols: int = 80, rows: int = 16, frames: int = 48) -> dict[str, Any]:
  309. """Pre-render a full play-through (reveal 0→1) plus static legend/summary."""
  310. frames, nodes = max(2, min(frames, 240)), list(payload.get("nodes", []))
  311. # Mirror render_graph's bucketing so the interactive row list lines up with what the user sees.
  312. buckets = _build_chart_buckets(nodes, compute_recency(nodes), max_rows=max(4, rows - 3)) if nodes else []
  313. out_frames = [
  314. {k: frame[k] for k in ("reveal", "date", "visible", "grid")} | {"labels": frame.get("labels", [])}
  315. for frame in (render_graph(payload, cols=cols, rows=rows, reveal=i / (frames - 1)) for i in range(frames))
  316. ]
  317. return {
  318. "frames": out_frames, "legend": build_legend(payload), "categories": category_legend(payload),
  319. "buckets": _bucket_rows(buckets, payload), "summary": build_summary(payload), "axis": axis_labels(payload),
  320. "count": len(payload.get("nodes", [])), "cols": cols, "rows": rows,
  321. }