Skip to content

The agent that grows with you

refactor(agent/learning_graph): fold row/frame assembly into comprehensions, merge single-use color/period helpers

Tekniume6d320928728
diff --git a/agent/learning_graph.py b/agent/learning_graph.py
index 4915100c579..e708165e279 100644
--- a/agent/learning_graph.py
+++ b/agent/learning_graph.py
@@ -35,14 +35,6 @@ class SkillNode:
related: list[str] = field(default_factory=list)
-def _frontmatter(text: str) -> dict[str, Any]:
- try:
- from agent.skill_utils import parse_frontmatter
- return parse_frontmatter(text)[0] or {}
- except Exception:
- return {}
-
-
def _fm_field(fm: dict[str, Any], key: str) -> Any:
"""Top-level ``key`` or ``metadata.hermes.<key>``; tolerant of the string-valued
frontmatter that ``parse_frontmatter``'s malformed-YAML fallback produces."""
@@ -55,19 +47,10 @@ def _fm_field(fm: dict[str, Any], key: str) -> Any:
def _related(fm: dict[str, Any]) -> list[str]:
raw = _fm_field(fm, "related_skills")
- if isinstance(raw, str):
- raw = raw.strip("[]").split(",")
+ raw = raw.strip("[]").split(",") if isinstance(raw, str) else raw
return [str(r).strip() for r in raw if str(r).strip()] if isinstance(raw, list) else []
-def _category(fm: dict[str, Any], skill_md: Path) -> str:
- cat = _fm_field(fm, "category")
- if cat:
- return str(cat)
- parts = skill_md.parts # …/skills/<category>/<skill>/SKILL.md
- return parts[-3] if len(parts) >= 3 else "general"
-
-
def _load_usage() -> dict[str, dict[str, Any]]:
try:
from tools.skill_usage import load_usage
@@ -82,28 +65,19 @@ def _load_usage() -> dict[str, dict[str, Any]]:
def _to_int_ts(value: Any) -> Optional[int]:
"""Epoch seconds from a number, numeric string, or ISO timestamp; None otherwise."""
try:
- if value is None:
+ if value is None or not (s := str(value).strip()):
return None
if isinstance(value, (int, float)):
return int(value)
- s = str(value).strip()
- if not s:
- return None
try:
return int(float(s))
except ValueError:
parsed = datetime.fromisoformat(s.replace("Z", "+00:00"))
- if parsed.tzinfo is None:
- parsed = parsed.replace(tzinfo=timezone.utc)
- return int(parsed.timestamp())
+ return int((parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=timezone.utc)).timestamp())
except Exception:
return None
-def _usage_timestamp(rec: dict[str, Any]) -> Optional[int]:
- return next((ts for ts in (_to_int_ts(rec.get(k)) for k in _USAGE_TS_KEYS) if ts is not None), None)
-
-
def build_skill_nodes(skill_roots: list[tuple[str, Path]]) -> dict[str, SkillNode]:
usage = _load_usage()
nodes: dict[str, SkillNode] = {}
@@ -112,16 +86,22 @@ def build_skill_nodes(skill_roots: list[tuple[str, Path]]) -> dict[str, SkillNod
if _SKIP_PARTS.intersection(skill_md.parts):
continue
try:
- fm = _frontmatter(skill_md.read_text(encoding="utf-8")[:4000])
+ text = skill_md.read_text(encoding="utf-8")[:4000]
except OSError:
continue
+ try:
+ from agent.skill_utils import parse_frontmatter
+ fm = parse_frontmatter(text)[0] or {}
+ except Exception:
+ fm = {}
name = str(fm.get("name") or skill_md.parent.name).strip()
if not name or name in nodes:
continue
- rec = usage.get(name, {})
+ rec, cat, parts = usage.get(name, {}), _fm_field(fm, "category"), skill_md.parts # …/skills/<category>/<skill>/SKILL.md
+ usage_ts = next((ts for ts in (_to_int_ts(rec.get(k)) for k in _USAGE_TS_KEYS) if ts is not None), None)
nodes[name] = SkillNode(
- name=name, category=_category(fm, skill_md), source=source,
- timestamp=_usage_timestamp(rec) or _to_int_ts(skill_md.stat().st_mtime),
+ name=name, category=str(cat) if cat else parts[-3] if len(parts) >= 3 else "general", source=source,
+ timestamp=usage_ts or _to_int_ts(skill_md.stat().st_mtime),
use_count=int(rec.get("use_count", 0) or 0), state=str(rec.get("state", "active") or "active"),
created_by=rec.get("created_by"), pinned=bool(rec.get("pinned", False)), related=_related(fm),
)
@@ -131,24 +111,15 @@ def build_skill_nodes(skill_roots: list[tuple[str, Path]]) -> dict[str, SkillNod
def build_edges(nodes: dict[str, SkillNode]) -> list[tuple[str, str]]:
"""Undirected related_skills edges where BOTH endpoints exist (deduped, first-seen order)."""
return list(dict.fromkeys(
- (min(node.name, target), max(node.name, target))
- for node in nodes.values()
- for target in node.related
- if target in nodes and target != node.name
+ (min(node.name, target), max(node.name, target)) for node in nodes.values() for target in node.related if target in nodes and target != node.name
))
def density_stats(nodes: dict[str, SkillNode], edges: list[tuple[str, str]]) -> dict[str, Any]:
- linked = {x for edge in edges for x in edge}
- cats = Counter(n.category for n in nodes.values())
- n = len(nodes) or 1
+ linked, cats, n = {x for edge in edges for x in edge}, Counter(x.category for x in nodes.values()), len(nodes) or 1
return {
- "nodes": len(nodes),
- "related_edges": len(edges),
- "edges_per_node": round(len(edges) / n, 3),
- "linked_nodes": len(linked),
- "isolated_pct": round(100 * (n - len(linked)) / n, 1),
- "categories": len(cats),
+ "nodes": len(nodes), "related_edges": len(edges), "edges_per_node": round(len(edges) / n, 3),
+ "linked_nodes": len(linked), "isolated_pct": round(100 * (n - len(linked)) / n, 1), "categories": len(cats),
"agent_created": sum(1 for x in nodes.values() if x.created_by == "agent"),
"used": sum(1 for x in nodes.values() if x.use_count > 0),
"top_categories": sorted(cats.items(), key=lambda kv: -kv[1])[:8],
@@ -163,23 +134,20 @@ def _memory_cards() -> list[dict[str, Any]]:
for fname, source in (("MEMORY.md", "memory"), ("USER.md", "profile")):
path = base / fname
try:
- text = path.read_text(encoding="utf-8").strip()
- file_ts = _to_int_ts(path.stat().st_mtime)
+ text, file_ts = path.read_text(encoding="utf-8").strip(), _to_int_ts(path.stat().st_mtime)
except OSError:
continue
for chunk_idx, chunk in enumerate(c.strip() for c in text.split("\n§\n")):
- if not chunk:
- continue
- first = chunk.splitlines()[0].strip().lstrip("# ").strip()
- cards.append({
- "source": source, "timestamp": file_ts + chunk_idx if file_ts is not None else None,
- "title": (first[:80] + "…") if len(first) > 80 else first, "body": chunk[:1200],
- })
+ if chunk:
+ first = chunk.splitlines()[0].strip().lstrip("# ").strip()
+ cards.append({
+ "source": source, "timestamp": file_ts + chunk_idx if file_ts is not None else None,
+ "title": (first[:80] + "…") if len(first) > 80 else first, "body": chunk[:1200],
+ })
return cards
-def _tokenize(text: str) -> set[str]:
- return {t for t in re.split(r"[^a-z0-9]+", text.lower()) if len(t) >= 3}
+def _tokenize(text: str) -> set[str]: return {t for t in re.split(r"[^a-z0-9]+", text.lower()) if len(t) >= 3} # noqa: E704
def _memory_skill_edges(memory_cards: list[dict[str, Any]], skills: list[SkillNode]) -> list[tuple[str, str]]:
@@ -189,32 +157,24 @@ def _memory_skill_edges(memory_cards: list[dict[str, Any]], skills: list[SkillNo
for idx, card in enumerate(memory_cards):
text = f"{card.get('title', '')}\n{card.get('body', '')}".lower()
text_tokens = _tokenize(text)
- scored = [
- (score, name) for name, tokens, name_lower in skill_meta
- if (score := (6 if name_lower in text else 0) + len(tokens & text_tokens)) > 0
- ]
- scored.sort(key=lambda x: (-x[0], x[1]))
+ scored = sorted(
+ ((score, name) for name, tokens, name_lower in skill_meta if (score := (6 if name_lower in text else 0) + len(tokens & text_tokens)) > 0),
+ key=lambda x: (-x[0], x[1]),
+ )
edges.extend((f"memory:{card['source']}:{idx}", name) for _, name in scored[:4])
return edges
-def _skill_roots() -> list[tuple[str, Path]]:
- repo = Path(__file__).resolve().parent.parent
- return [("base", repo / "skills"), ("profile", get_hermes_home() / "skills")]
-
-
def build_learning_graph() -> dict[str, Any]:
"""Full payload for the desktop learning panel: non-base skills with real
learning signal (agent-created or used) plus memory chunks as graph nodes."""
+ roots = [("base", Path(__file__).resolve().parent.parent / "skills"), ("profile", get_hermes_home() / "skills")]
learned_skills = {
- name: node
- for name, node in build_skill_nodes(_skill_roots()).items()
+ name: node for name, node in build_skill_nodes(roots).items()
if node.source != "base" and (node.created_by == "agent" or node.use_count > 0)
}
- skill_edges = build_edges(learned_skills)
- memory_cards = _memory_cards()
+ skill_edges, memory_cards = build_edges(learned_skills), _memory_cards()
memory_edges = _memory_skill_edges(memory_cards, list(learned_skills.values()))
-
clusters = Counter(node.category for node in learned_skills.values())
if memory_cards:
clusters["memory"] = len(memory_cards)
@@ -233,7 +193,6 @@ def build_learning_graph() -> dict[str, Any]:
}
for i, card in enumerate(memory_cards)
]
-
return {
"nodes": graph_nodes,
"edges": [{"source": a, "target": b} for a, b in skill_edges + memory_edges],
@@ -241,8 +200,6 @@ def build_learning_graph() -> dict[str, Any]:
"memory": memory_cards,
"stats": {
**density_stats(learned_skills, skill_edges),
- "memory_nodes": len(memory_cards),
- "memory_skill_edges": len(memory_edges),
- "learned_skills": len(learned_skills),
+ "memory_nodes": len(memory_cards), "memory_skill_edges": len(memory_edges), "learned_skills": len(learned_skills),
},
}
diff --git a/agent/learning_graph_render.py b/agent/learning_graph_render.py
index 2815c3d15df..53838a48530 100644
--- a/agent/learning_graph_render.py
+++ b/agent/learning_graph_render.py
@@ -31,23 +31,23 @@ Grid = list # list[Row]
def _clamp(v: float, lo: float, hi: float) -> float:
return lo if v < lo else hi if v > hi else v
-
-
def _lerp(a: float, b: float, t: float) -> float:
return a + (b - a) * t
-
-
def _smoothstep(p: float) -> float:
p = _clamp(p, 0.0, 1.0)
return p * p * (3 - 2 * p)
-
-
def _is_memory(node: dict[str, Any]) -> bool:
return node.get("kind") == "memory"
-
-
def _node_id(node: dict[str, Any]) -> str:
return str(node.get("id", ""))
+def _utc(ts: float) -> datetime:
+ return datetime.fromtimestamp(ts, tz=timezone.utc)
+def _lead_in(ratio: float) -> float:
+ return LEAD_IN + (1 - LEAD_IN) * ratio
+def _visible_count(reveal: float, n: int) -> int:
+ return int(_clamp(math.ceil(reveal * n), 0, n))
+def _node_raw_label(node: dict[str, Any]) -> str:
+ return str(node.get("label") or node.get("id") or "unknown").strip()
def _node_ts(node: dict[str, Any]) -> Optional[float]:
@@ -57,16 +57,10 @@ def _node_ts(node: dict[str, Any]) -> Optional[float]:
return None
-def _utc(ts: float) -> datetime:
- return datetime.fromtimestamp(ts, tz=timezone.utc)
-
-
def recency_ink(rec: float) -> float:
"""Port of geometry.ts ``recencyInk`` — smoothstep age → ink alpha."""
t = _clamp(rec, 0.0, 1.0)
- if t <= AGE_MID:
- return _lerp(AGE_OLD_INK, AGE_MID_INK, _smoothstep(t / AGE_MID))
- return _lerp(AGE_MID_INK, AGE_NEW_INK, _smoothstep((t - AGE_MID) / (1 - AGE_MID)))
+ 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)))
def format_date(ts: Optional[float]) -> str:
@@ -77,10 +71,6 @@ def format_date(ts: Optional[float]) -> str:
return f"{dt.day} {dt.strftime('%b %Y')}" if dt else "unknown"
-def _lead_in(ratio: float) -> float:
- return LEAD_IN + (1 - LEAD_IN) * ratio
-
-
def compute_recency(nodes: list[dict[str, Any]]) -> dict[str, Any]:
"""Port of time-axis.ts ``computeRecency`` (id → recency ratio, timed flag).
Untimed graphs (no spread of timestamps) fall back to ordinal position so
@@ -88,23 +78,19 @@ def compute_recency(nodes: list[dict[str, Any]]) -> dict[str, Any]:
known = [t for t in (_node_ts(n) for n in nodes) if t is not None]
min_ts, max_ts = (min(known), max(known)) if known else (None, None)
timed = bool(known) and max_ts > min_ts
-
ordered = sorted(nodes, key=lambda n: (_node_ts(n) if _node_ts(n) is not None else math.inf, _node_id(n)))
last = max(len(ordered) - 1, 1)
ord_ratio = {_node_id(n): (i / last if len(ordered) > 1 else 0.0) for i, n in enumerate(ordered)}
- rec: dict[str, float] = {}
- for n in nodes:
- nid, ts = _node_id(n), _node_ts(n)
- ratio = (ts - min_ts) / (max_ts - min_ts) if timed and ts is not None else ord_ratio.get(nid, 0.0)
- rec[nid] = _lead_in(_clamp(ratio, 0.0, 1.0))
+ rec = {
+ 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))
+ for nid, ts in ((_node_id(n), _node_ts(n)) for n in nodes)
+ }
return {"rec": rec, "timed": timed, "minTs": min_ts, "maxTs": max_ts}
def _date_at(rec: dict[str, Any], reveal: float) -> Optional[float]:
lo, hi = rec.get("minTs"), rec.get("maxTs")
- if not rec.get("timed") or lo is None or hi is None:
- return None
- return round(lo + _clamp(reveal, 0, 1) * (hi - lo))
+ return None if not rec.get("timed") or lo is None or hi is None else round(lo + _clamp(reveal, 0, 1) * (hi - lo))
# ── Color: ported from color.ts so memory ink + age fade match the desktop ──
@@ -124,15 +110,13 @@ def rgb_to_hex(c: tuple) -> str:
def mix_rgb(a: tuple, b: tuple, t: float) -> tuple[int, int, int]:
- p = _clamp(t, 0.0, 1.0)
- return tuple(round(_lerp(a[i], b[i], p)) for i in range(3)) # type: ignore[return-value]
+ return tuple(round(_lerp(a[i], b[i], _clamp(t, 0.0, 1.0))) for i in range(3)) # type: ignore[return-value]
def _rgb_to_hsl(c: tuple) -> tuple[float, float, float]:
r, g, b = (x / 255 for x in c)
mx, mn = max(r, g, b), min(r, g, b)
- light = (mx + mn) / 2
- d = mx - mn
+ light, d = (mx + mn) / 2, mx - mn
if not d:
return 0.0, 0.0, light
s = d / (2 - mx - mn) if light > 0.5 else d / (mx + mn)
@@ -142,75 +126,53 @@ def _rgb_to_hsl(c: tuple) -> tuple[float, float, float]:
# Hue sextant → (r, g, b) as a permutation of (c, x, 0).
_HUE_SEXTANTS = (
- lambda c, x: (c, x, 0.0),
- lambda c, x: (x, c, 0.0),
- lambda c, x: (0.0, c, x),
- lambda c, x: (0.0, x, c),
- lambda c, x: (x, 0.0, c),
- lambda c, x: (c, 0.0, x),
+ lambda c, x: (c, x, 0.0), lambda c, x: (x, c, 0.0), lambda c, x: (0.0, c, x),
+ lambda c, x: (0.0, x, c), lambda c, x: (x, 0.0, c), lambda c, x: (c, 0.0, x),
)
def _hsl_to_rgb(h: float, s: float, light: float) -> tuple[int, int, int]:
hue = ((h % 360) + 360) % 360
c = (1 - abs(2 * light - 1)) * s
- x = c * (1 - abs(((hue / 60) % 2) - 1))
- m = light - c / 2
+ x, m = c * (1 - abs(((hue / 60) % 2) - 1)), light - c / 2
return tuple(round((v + m) * 255) for v in _HUE_SEXTANTS[min(int(hue // 60), 5)](c, x)) # type: ignore[return-value]
-def _complementary_ink(c: tuple) -> tuple[int, int, int]:
- h, s, light = _rgb_to_hsl(c)
- return _hsl_to_rgb(h + 165, max(s, 0.5), _clamp(light, 0.5, 0.7))
-
-
def derive_palette(primary_hex: str, *, dark: bool = True) -> dict[str, str]:
"""Port of color.ts ``computePalette`` (the bits a terminal needs)."""
primary = hex_to_rgb(primary_hex)
- base = (255, 255, 255) if dark else (0, 0, 0)
- bg = (8, 8, 12) if dark else (250, 250, 250)
+ base, bg = ((255, 255, 255), (8, 8, 12)) if dark else ((0, 0, 0), (250, 250, 250))
+ h, s, light = _rgb_to_hsl(primary)
return {
"primary": primary_hex,
# Memories are drillable → primary "clickable" ink; skills are dead-ends → muted complement.
"memory": rgb_to_hex(mix_rgb(primary, base, 0.12 if dark else 0.18)),
- "skill": rgb_to_hex(mix_rgb(_complementary_ink(primary), bg, 0.45)),
- "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),
+ "skill": rgb_to_hex(mix_rgb(_hsl_to_rgb(h + 165, max(s, 0.5), _clamp(light, 0.5, 0.7)), bg, 0.45)),
+ "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),
}
def _node_score(node: dict[str, Any], rec: float) -> float:
"""Pick which visible objects deserve map markers + label rows."""
- if _is_memory(node):
- return 3.5 + rec
- return rec * 2 + math.sqrt(max(0.0, float(node.get("useCount", 0) or 0))) + (2.0 if node.get("pinned") else 0.0)
-
-
-def _node_raw_label(node: dict[str, Any]) -> str:
- return str(node.get("label") or node.get("id") or "unknown").strip()
+ 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)
def _node_card(node: dict[str, Any]) -> dict[str, Any]:
"""Shared glyph/label/meta/style fields for label rows and bucket trees."""
- mem = _is_memory(node)
- text = _node_raw_label(node)
- date = format_date(_node_ts(node))
+ mem, text, date = _is_memory(node), _node_raw_label(node), format_date(_node_ts(node))
if mem:
meta = f"{'profile memory' if node.get('memorySource') == 'profile' else 'memory'} · {date}"
else:
count = int(node.get("useCount", 0) or 0)
meta = " · ".join([str(node.get("category") or "skill"), date] + ([f"x{count}"] if count else []) + (["pinned"] if node.get("pinned") else []))
return {
- "glyph": MEMORY_GLYPH if mem else SKILL_GLYPH,
- "label": text if len(text) <= 26 else text[:23].rstrip() + "…",
- "meta": meta,
- "style": STYLE_MEMORY if mem else STYLE_SKILL,
+ "glyph": MEMORY_GLYPH if mem else SKILL_GLYPH, "label": text if len(text) <= 26 else text[:23].rstrip() + "…",
+ "meta": meta, "style": STYLE_MEMORY if mem else STYLE_SKILL,
}
def _skill_category_counts(nodes: Iterable[dict[str, Any]]) -> Counter:
- return Counter(str(node.get("category") or "skill") for node in nodes if not _is_memory(node))
+ return Counter(str(n.get("category") or "skill") for n in nodes if not _is_memory(n))
# ── Timeline chart frame ─────────────────────────────────────────────────────
@@ -222,21 +184,12 @@ class _ChartBucket:
self.label, self.ts, self.rec = label, ts, 1.0
self.nodes: list[dict[str, Any]] = []
- @property
- def memories(self) -> int:
- return sum(1 for n in self.nodes if _is_memory(n))
-
- @property
- def skills(self) -> int:
- return len(self.nodes) - self.memories
-
- @property
- def total(self) -> int:
- return len(self.nodes)
+ memories = property(lambda self: sum(1 for n in self.nodes if _is_memory(n)))
+ skills = property(lambda self: len(self.nodes) - self.memories)
+ total = property(lambda self: len(self.nodes))
def category(self) -> Optional[str]:
- counts = _skill_category_counts(self.nodes)
- return max(counts, key=lambda k: counts[k]) if counts else None
+ return max(counts, key=lambda k: counts[k]) if (counts := _skill_category_counts(self.nodes)) else None
# granularity → (period key, row label) from a UTC datetime.
@@ -248,16 +201,13 @@ _PERIODS: dict[str, tuple] = {
def _period(ts: float, granularity: str) -> tuple[tuple[int, ...], str]:
- key_fn, label_fn = _PERIODS.get(granularity, _PERIODS["year"])
- return key_fn(_utc(ts)), label_fn(_utc(ts))
+ return tuple(fn(_utc(ts)) for fn in _PERIODS.get(granularity, _PERIODS["year"])) # type: ignore[return-value]
def _fill_even_bins(buckets: list[_ChartBucket], nodes: Iterable[dict[str, Any]], rec: dict[str, Any]) -> None:
"""Drop each node into the bin its recency ratio maps to (order preserved)."""
- n_bins = len(buckets)
for node in nodes:
- r = rec["rec"].get(_node_id(node), 0.0)
- buckets[int(_clamp(math.floor(r * n_bins), 0, n_bins - 1))].nodes.append(node)
+ buckets[int(_clamp(math.floor(rec["rec"].get(_node_id(node), 0.0) * len(buckets)), 0, len(buckets) - 1))].nodes.append(node)
def _build_chart_buckets(nodes: list[dict[str, Any]], rec: dict[str, Any], max_rows: int) -> list[_ChartBucket]:
@@ -265,9 +215,8 @@ def _build_chart_buckets(nodes: list[dict[str, Any]], rec: dict[str, Any], max_r
if not nodes:
return []
if not rec["timed"]:
- ordered = sorted(nodes, key=lambda n: rec["rec"].get(_node_id(n), 0.0))
- buckets = [_ChartBucket(f"#{i + 1}", float(i)) for i in range(min(max_rows, len(ordered)))]
- _fill_even_bins(buckets, ordered, rec)
+ buckets = [_ChartBucket(f"#{i + 1}", float(i)) for i in range(min(max_rows, len(nodes)))]
+ _fill_even_bins(buckets, sorted(nodes, key=lambda n: rec["rec"].get(_node_id(n), 0.0)), rec)
return buckets
chosen: Optional[list[_ChartBucket]] = None
@@ -299,37 +248,30 @@ def _build_chart_buckets(nodes: list[dict[str, Any]], rec: dict[str, Any], max_r
def _bucket_rows(buckets: list[_ChartBucket], payload: dict[str, Any]) -> list[dict[str, Any]]:
cmap = category_color_map(payload)
- memory_lookup = {
- f"memory:{card.get('source')}:{idx}": card
- for idx, card in enumerate(payload.get("memory", []) or [])
- if isinstance(card, dict)
- }
- rows: list[dict[str, Any]] = []
- for idx, bucket in enumerate(buckets):
+ memory_lookup = {f"memory:{card.get('source')}:{idx}": card for idx, card in enumerate(payload.get("memory", []) or []) if isinstance(card, dict)}
+
+ def node_row(node: dict[str, Any]) -> dict[str, Any]:
+ card, memory = _node_card(node), memory_lookup.get(_node_id(node))
+ return {
+ "id": _node_id(node), "glyph": card["glyph"], "label": card["label"], "fullLabel": _node_raw_label(node),
+ "meta": card["meta"], "body": str(memory.get("body", "")) if memory else "", "style": card["style"],
+ }
+
+ def bucket_row(idx: int, bucket: _ChartBucket) -> dict[str, Any]:
cat = bucket.category()
- nodes = []
- # Chronological within the slice so the TUI tree reads oldest → newest.
- for node in sorted(bucket.nodes, key=lambda n: _node_ts(n) or bucket.ts):
- card, memory = _node_card(node), memory_lookup.get(_node_id(node))
- nodes.append({
- "id": _node_id(node), "glyph": card["glyph"], "label": card["label"], "fullLabel": _node_raw_label(node),
- "meta": card["meta"], "body": str(memory.get("body", "")) if memory else "", "style": card["style"],
- })
- rows.append({
+ return {
"index": idx, "label": bucket.label, "date": format_date(bucket.ts),
"skills": bucket.skills, "memories": bucket.memories, "total": bucket.total,
"category": cat, "color": cmap.get(cat) if cat else None,
- "nodes": nodes,
- })
- return rows
+ # Chronological within the slice so the TUI tree reads oldest → newest.
+ "nodes": [node_row(n) for n in sorted(bucket.nodes, key=lambda n: _node_ts(n) or bucket.ts)],
+ }
+
+ return [bucket_row(idx, bucket) for idx, bucket in enumerate(buckets)]
def _category_counts(payload: dict[str, Any]) -> list[tuple[str, int]]:
- 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"
- ]
+ 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"]
return clusters or sorted(_skill_category_counts(payload.get("nodes", [])).items(), key=lambda kv: (-kv[1], kv[0]))
@@ -342,22 +284,14 @@ def category_color_map(payload: dict[str, Any]) -> dict[str, str]:
def category_legend(payload: dict[str, Any], limit: int = 4) -> list[dict[str, Any]]:
cmap, cats = category_color_map(payload), _category_counts(payload)
out = [{"glyph": "●", "color": cmap.get(cat, ""), "label": f"{cat} ({count})"} for cat, count in cats[:limit]]
- if len(cats) > limit:
- out.append({"glyph": "·", "color": "", "label": f"+{len(cats) - limit}"})
- return out
-
-
-def _visible_count(reveal: float, n: int) -> int:
- return int(_clamp(math.ceil(reveal * n), 0, n))
+ return out + ([{"glyph": "·", "color": "", "label": f"+{len(cats) - limit}"}] if len(cats) > limit else [])
def _trajectory_row(buckets: list[_ChartBucket], width: int, reveal: float) -> Row:
"""Cumulative learning curve as a compact star-path sparkline."""
if not buckets:
return []
- total = sum(b.total for b in buckets) or 1
- cells = [" "] * width
- acc = last = 0
+ total, cells, acc, last = sum(b.total for b in buckets) or 1, [" "] * width, 0, 0
for b in buckets[:_visible_count(reveal, len(buckets))]:
acc += b.total
p = round((acc / total) * (width - 1))
@@ -373,9 +307,7 @@ def _trajectory_row(buckets: list[_ChartBucket], width: int, reveal: float) -> R
def _bar_lengths(bucket: _ChartBucket, max_total: int, bar_w: int) -> tuple[int, int, int]:
"""(bar, skill, memory) cell counts; a present kind never rounds to zero."""
bar_len = max(1, round((bucket.total / max_total) * bar_w)) if bucket.total else 0
- skill_len = round((bucket.skills / bucket.total) * bar_len) if bucket.total else 0
- if bucket.skills and skill_len == 0:
- skill_len = 1
+ skill_len = max(1, round((bucket.skills / bucket.total) * bar_len)) if bucket.skills else 0
if bucket.memories and skill_len == bar_len > 1:
skill_len = bar_len - 1
return bar_len, skill_len, bar_len - skill_len
@@ -388,53 +320,42 @@ def render_graph(payload: dict[str, Any], *, cols: int = 80, rows: int = 16, rev
reveal, cols, rows = _clamp(reveal, 0.0, 1.0), max(44, cols), max(14, rows)
nodes = list(payload.get("nodes", []))
if not nodes:
- placeholder = [["no learning yet — keep using Hermes and it maps out here", STYLE_DIM, 0.7]]
- return {"grid": [placeholder], "date": "", "reveal": reveal, "visible": 0}
+ return {"grid": [[["no learning yet — keep using Hermes and it maps out here", STYLE_DIM, 0.7]]], "date": "", "reveal": reveal, "visible": 0}
- rec = compute_recency(nodes)
- cmap = category_color_map(payload)
+ rec, cmap = compute_recency(nodes), category_color_map(payload)
buckets = _build_chart_buckets(nodes, rec, max_rows=max(4, rows - 3))
- visible_bucket_count = _visible_count(reveal, len(buckets))
- max_total = max((b.total for b in buckets), default=1) or 1
+ visible_bucket_count, max_total = _visible_count(reveal, len(buckets)), max((b.total for b in buckets), default=1) or 1
label_w = min(9, max(len(b.label) for b in buckets))
bar_w = max(14, cols - label_w - 16)
grid: Grid = []
labels: list[dict[str, Any]] = []
visible = 0
- for i, bucket in enumerate(buckets):
- if i >= visible_bucket_count:
- grid.append([])
- continue
+ for i, bucket in enumerate(buckets[:visible_bucket_count]):
visible += bucket.total
- ink = recency_ink(bucket.rec)
+ ink, cat = recency_ink(bucket.rec), bucket.category()
bar_len, skill_len, memory_len = _bar_lengths(bucket, max_total, bar_w)
- cat = bucket.category()
cat_hex = cmap.get(cat) if cat else None
-
row: Row = [[f"{bucket.label:>{label_w}} ", STYLE_LABEL, ink], ["│ ", STYLE_DIM, 0.55]]
if bucket.nodes and len(labels) < 6:
- node = max(bucket.nodes, key=lambda n: _node_score(n, _node_ts(n) or bucket.ts))
- marker = _LABEL_KEYS[len(labels)]
+ node, marker = max(bucket.nodes, key=lambda n: _node_score(n, _node_ts(n) or bucket.ts)), _LABEL_KEYS[len(labels)]
labels.append({"key": marker, **_node_card(node), "alpha": round(ink, 3)})
row.append([marker, STYLE_LABEL, 0.95])
elif bucket.total:
row.append(["✦" if bucket.skills else "◆", STYLE_SKILL if bucket.skills else STYLE_MEMORY, ink, cat_hex if bucket.skills else None])
- if skill_len: # bar colored by the day's dominant category — a learning heatmap
- row.append(["━" * skill_len, STYLE_SKILL, ink, cat_hex])
- if memory_len:
- row.append(["◆" if memory_len == 1 else "◆" + ("━" * (memory_len - 2)) + "◆", STYLE_MEMORY, max(0.65, ink)])
- if bar_len < bar_w: # empty space keeps counts aligned; starmap texture lives in the trajectory row
- row.append([" " * (bar_w - bar_len), STYLE_BG, 1.0])
- row += [[" ", STYLE_BG, 1.0], [str(bucket.skills), STYLE_SKILL, max(0.72, ink)]]
- if bucket.memories:
- row += [["+", STYLE_DIM, 0.6], [str(bucket.memories), STYLE_MEMORY, max(0.72, ink)]]
+ # Skill bar colored by the day's dominant category (a learning heatmap); trailing empty space keeps
+ # counts aligned — starmap texture lives in the trajectory row.
+ row += ([["━" * skill_len, STYLE_SKILL, ink, cat_hex]] if skill_len else [])
+ row += ([["◆" if memory_len == 1 else "◆" + ("━" * (memory_len - 2)) + "◆", STYLE_MEMORY, max(0.65, ink)]] if memory_len else [])
+ 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)]]
+ row += ([["+", STYLE_DIM, 0.6], [str(bucket.memories), STYLE_MEMORY, max(0.72, ink)]] if bucket.memories else [])
if i == visible_bucket_count - 1:
row.append([" ◀ now", STYLE_LABEL, 0.9])
elif bucket.total == max_total and max_total > 1:
row.append([" ☄ peak", STYLE_LABEL, 0.75])
grid.append(row)
+ grid += [[] for _ in buckets[visible_bucket_count:]] # not-yet-revealed rows stay blank
grid.append([[(" " * (label_w + 2)), STYLE_BG, 1.0], *_trajectory_row(buckets, max(12, cols - label_w - 13), reveal)])
return {"grid": grid, "date": format_date(_date_at(rec, reveal)), "reveal": reveal, "visible": visible, "labels": labels}
@@ -456,12 +377,8 @@ def axis_labels(payload: dict[str, Any]) -> dict[str, str]:
def _peak_day(payload: dict[str, Any]) -> Optional[str]:
- counts: Counter = Counter()
- labels: dict[tuple[int, ...], str] = {}
- for ts in (_node_ts(n) for n in payload.get("nodes", [])):
- if ts is not None:
- key, labels[key] = _period(ts, "day")
- counts[key] += 1
+ periods = [_period(ts, "day") for ts in (_node_ts(n) for n in payload.get("nodes", [])) if ts is not None]
+ counts, labels = Counter(key for key, _label in periods), dict(periods)
if not counts:
return None
best = max(counts, key=lambda k: counts[k])
@@ -472,29 +389,21 @@ def build_summary(payload: dict[str, Any]) -> list[str]:
stats = payload.get("stats", {}) or {}
learned = stats.get("learned_skills", stats.get("nodes", 0))
lines = [f"{learned} learned skills · {stats.get('memory_nodes', 0)} memories · {stats.get('related_edges', 0)} skill links"]
- extra = [f"{stats['memory_skill_edges']} memory↔skill links"] if stats.get("memory_skill_edges") else []
- extra += filter(None, [_peak_day(payload)])
+ extra = ([f"{stats['memory_skill_edges']} memory↔skill links"] if stats.get("memory_skill_edges") else []) + list(filter(None, [_peak_day(payload)]))
return lines + ([" · ".join(extra)] if extra else [])
def render_frames(payload: dict[str, Any], *, cols: int = 80, rows: int = 16, frames: int = 48) -> dict[str, Any]:
"""Pre-render a full play-through (reveal 0→1) plus static legend/summary."""
- frames = max(2, min(frames, 240))
- nodes = list(payload.get("nodes", []))
+ frames, nodes = max(2, min(frames, 240)), list(payload.get("nodes", []))
# Mirror render_graph's bucketing so the interactive row list lines up with what the user sees.
buckets = _build_chart_buckets(nodes, compute_recency(nodes), max_rows=max(4, rows - 3)) if nodes else []
- out_frames = []
- for i in range(frames):
- frame = render_graph(payload, cols=cols, rows=rows, reveal=i / (frames - 1))
- out_frames.append({k: frame[k] for k in ("reveal", "date", "visible", "grid")} | {"labels": frame.get("labels", [])})
+ out_frames = [
+ {k: frame[k] for k in ("reveal", "date", "visible", "grid")} | {"labels": frame.get("labels", [])}
+ for frame in (render_graph(payload, cols=cols, rows=rows, reveal=i / (frames - 1)) for i in range(frames))
+ ]
return {
- "frames": out_frames,
- "legend": build_legend(payload),
- "categories": category_legend(payload),
- "buckets": _bucket_rows(buckets, payload),
- "summary": build_summary(payload),
- "axis": axis_labels(payload),
- "count": len(payload.get("nodes", [])),
- "cols": cols,
- "rows": rows,
+ "frames": out_frames, "legend": build_legend(payload), "categories": category_legend(payload),
+ "buckets": _bucket_rows(buckets, payload), "summary": build_summary(payload), "axis": axis_labels(payload),
+ "count": len(payload.get("nodes", [])), "cols": cols, "rows": rows,
}