journey.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. """``hermes journey`` — what Hermes has learned, on a timeline."""
  2. from __future__ import annotations
  3. import argparse
  4. import shutil
  5. import sys
  6. import time
  7. from functools import lru_cache
  8. from typing import Any, Optional
  9. _TITLE_COLOR = "#E8C463"
  10. _CHARTED_SIGNAL_MIN_CONTRAST = 4.5
  11. def _build_payload() -> dict[str, Any]:
  12. from agent.learning_graph import build_learning_graph
  13. return build_learning_graph()
  14. @lru_cache(maxsize=1)
  15. def _primary_hex() -> str:
  16. """The active skin's primary color (mirrors the TUI theme primary)."""
  17. try:
  18. from hermes_cli.skin_engine import get_active_skin
  19. skin = get_active_skin()
  20. return skin.get_color("ui_primary", "") or skin.get_color("banner_title", "#FFD700")
  21. except Exception:
  22. return "#FFD700"
  23. @lru_cache(maxsize=1)
  24. def _palette() -> dict[str, str]:
  25. from agent.learning_graph_render import derive_palette
  26. return derive_palette(_primary_hex(), dark=True)
  27. def _fade(base: Optional[str], alpha: float) -> Optional[str]:
  28. from agent.learning_graph_render import hex_to_rgb, mix_rgb, rgb_to_hex
  29. if not base:
  30. return None
  31. if alpha >= 0.999:
  32. return base
  33. return rgb_to_hex(mix_rgb(hex_to_rgb(_palette()["bg"]), hex_to_rgb(base), alpha))
  34. def _resolve(style: str, alpha: float) -> Optional[str]:
  35. """Fade the style's base ink toward the background by ``alpha`` (rgba-over-bg)."""
  36. return _fade(_palette().get(style), alpha)
  37. def _relative_luminance(rgb: tuple[int, int, int]) -> float:
  38. def channel(value: int) -> float:
  39. n = value / 255
  40. return n / 12.92 if n <= 0.03928 else ((n + 0.055) / 1.055) ** 2.4
  41. red, green, blue = (channel(value) for value in rgb)
  42. return 0.2126 * red + 0.7152 * green + 0.0722 * blue
  43. def _contrast_ratio(foreground: tuple[int, int, int], background: tuple[int, int, int]) -> float:
  44. high, low = sorted((_relative_luminance(foreground), _relative_luminance(background)), reverse=True)
  45. return (high + 0.05) / (low + 0.05)
  46. def _ensure_contrast(color: Optional[str], background: str, minimum: float) -> Optional[str]:
  47. """Lift a foreground toward the readable pole until it clears ``minimum``."""
  48. if not color:
  49. return None
  50. from agent.learning_graph_render import hex_to_rgb, mix_rgb, rgb_to_hex
  51. foreground_rgb = hex_to_rgb(color)
  52. background_rgb = hex_to_rgb(background)
  53. if _contrast_ratio(foreground_rgb, background_rgb) >= minimum:
  54. return color
  55. pole = (0, 0, 0) if _relative_luminance(background_rgb) > 0.5 else (255, 255, 255)
  56. for step in range(1, 21):
  57. candidate = mix_rgb(foreground_rgb, pole, step * 0.05)
  58. if _contrast_ratio(candidate, background_rgb) >= minimum:
  59. return rgb_to_hex(candidate)
  60. return rgb_to_hex(pole)
  61. def _resolve_charted_signal(style: str, alpha: float) -> Optional[str]:
  62. """Keep age tinting without allowing explanatory labels to disappear."""
  63. return _ensure_contrast(_resolve(style, alpha), _palette()["bg"], _CHARTED_SIGNAL_MIN_CONTRAST)
  64. def _row_to_text(row: list, color: bool):
  65. from rich.text import Text
  66. text = Text()
  67. for run in row:
  68. chunk, style = run[0], run[1]
  69. alpha = run[2] if len(run) > 2 else 1.0
  70. override = run[3] if len(run) > 3 else None
  71. if not color:
  72. text.append(chunk)
  73. elif override:
  74. text.append(chunk, style=_fade(override, alpha))
  75. else:
  76. text.append(chunk, style=_resolve(style, alpha))
  77. return text
  78. def _term_size(width: Optional[int], height: Optional[int]) -> tuple[int, int]:
  79. size = shutil.get_terminal_size((90, 30))
  80. return max(40, width or size.columns), max(10, height or size.lines)
  81. def _frame_renderable(payload, *, cols, rows, reveal, color):
  82. from rich.console import Group
  83. from rich.text import Text
  84. from agent import learning_graph_render as render
  85. legend = render.build_legend(payload)
  86. categories = render.category_legend(payload)
  87. summary = render.build_summary(payload)
  88. axis = render.axis_labels(payload)
  89. # Lines are pad_left(2), so content must fit in cols-2.
  90. inner = max(24, cols - 2)
  91. # Reserve rows for title/legend/blank/axis/footer/labels + summary; field gets rest.
  92. field_rows = max(6, rows - 10 - len(summary))
  93. frame = render.render_graph(payload, cols=inner, rows=field_rows, reveal=reveal)
  94. count = len(payload.get("nodes", []))
  95. def st(style: Optional[str]) -> Optional[str]:
  96. return style if color else None
  97. title = Text()
  98. title.append("✦ Journey ", style=st(f"bold {_TITLE_COLOR}"))
  99. title.append("· learned skills & memories over time", style=st("grey62"))
  100. parts: list[Any] = [title]
  101. legend_line = Text(" ")
  102. for i, item in enumerate(legend):
  103. if i:
  104. legend_line.append(" ")
  105. legend_line.append(item["glyph"] + " ", style=_resolve(item["style"], 1.0) if color else None)
  106. legend_line.append(item["label"], style=st("grey62"))
  107. parts.append(legend_line)
  108. if categories:
  109. cat_line = Text(" ")
  110. for i, item in enumerate(categories):
  111. if i:
  112. cat_line.append(" ")
  113. cat_line.append(item["glyph"] + " ", style=_fade(item.get("color"), 1.0) if color else None)
  114. cat_line.append(item["label"], style=st("grey54"))
  115. parts.append(cat_line)
  116. parts.append(Text(""))
  117. for grow in frame["grid"]:
  118. line = _row_to_text(grow, color)
  119. line.pad_left(2)
  120. parts.append(line)
  121. # Date axis under the field (oldest → now), with the playhead date centered.
  122. axis_line = Text(" ")
  123. axis_line.append(axis["start"], style=st("grey54"))
  124. axis_line.append(" " * max(1, inner - len(axis["start"]) - len(axis["end"])))
  125. axis_line.append(axis["end"], style=st("grey54"))
  126. parts.append(axis_line)
  127. pct = round(reveal * 100)
  128. foot = Text(" ")
  129. foot.append("◷ ", style=st("grey54"))
  130. foot.append(frame["date"] or "—", style=st(_TITLE_COLOR))
  131. foot.append(f" {frame['visible']}/{count} revealed · {pct}%", style=st("grey54"))
  132. parts.append(foot)
  133. labels = frame.get("labels", [])
  134. if labels:
  135. parts.append(Text(""))
  136. parts.append(Text(" charted signals", style=st("grey62")))
  137. for item in labels[:6]:
  138. row = Text(" ")
  139. row.append(f"{item['key']} ", style=st("grey70"))
  140. signal_style = (
  141. _resolve_charted_signal(item["style"], float(item.get("alpha", 1.0))) if color else None
  142. )
  143. row.append(f"{item['glyph']} ", style=signal_style)
  144. row.append(str(item["label"]), style=signal_style)
  145. meta = str(item["meta"])
  146. row.append(f" {meta if len(meta) <= 32 else meta[:29] + '…'}", style=st("grey54"))
  147. parts.append(row)
  148. for line_text in summary:
  149. parts.append(Text(" " + line_text, style=st("grey62")))
  150. return Group(*parts)
  151. def _console(*, color: bool, width: Optional[int] = None, force: bool = False):
  152. """A Rich console. ``force`` emits truecolor ANSI even into a captured stream — the interactive CLI
  153. grabs that output and re-renders it through prompt_toolkit (raw escapes to a real terminal would
  154. otherwise be swallowed). Mirrors the ``ChatConsole`` idiom in ``cli.py``.
  155. """
  156. from rich.console import Console
  157. extra = {"force_terminal": True, "color_system": "truecolor"} if force else {}
  158. return Console(no_color=not color, width=width, **extra)
  159. def _cmd_show(args: argparse.Namespace) -> int:
  160. from rich.console import Console
  161. if getattr(args, "json", False):
  162. import json
  163. Console(no_color=bool(getattr(args, "no_color", False))).print_json(json.dumps(_build_payload()))
  164. return 0
  165. payload = _build_payload()
  166. color = not bool(getattr(args, "no_color", False))
  167. cols, rows = _term_size(getattr(args, "width", None), getattr(args, "height", None))
  168. console = _console(color=color, width=cols, force=bool(getattr(args, "force_color", False)))
  169. if not payload.get("nodes"):
  170. console.print(
  171. "[grey62]No learning yet — use Hermes a while and your learned skills and "
  172. "memories will start mapping out here.[/grey62]"
  173. )
  174. return 0
  175. if getattr(args, "play", False):
  176. return _play(console, payload, cols=cols, rows=rows, color=color, fps=getattr(args, "fps", 12))
  177. reveal = _clamp(float(getattr(args, "reveal", 1.0) or 1.0), 0.0, 1.0)
  178. console.print(_frame_renderable(payload, cols=cols, rows=rows, reveal=reveal, color=color))
  179. return 0
  180. def _play(console, payload, *, cols, rows, color, fps: int) -> int:
  181. from rich.live import Live
  182. frames = 42
  183. delay = 1.0 / max(1, min(60, fps))
  184. try:
  185. with Live(console=console, refresh_per_second=max(1, fps), screen=False) as live:
  186. for i in range(frames):
  187. reveal = i / (frames - 1)
  188. live.update(_frame_renderable(payload, cols=cols, rows=rows, reveal=reveal, color=color))
  189. time.sleep(delay)
  190. live.update(_frame_renderable(payload, cols=cols, rows=rows, reveal=1.0, color=color))
  191. except KeyboardInterrupt:
  192. console.print("[grey54]interrupted[/grey54]")
  193. return 130
  194. return 0
  195. def _clamp(v: float, lo: float, hi: float) -> float:
  196. return lo if v < lo else min(v, hi)
  197. # ── list / delete / edit ─────────────────────────────────────────────────────
  198. def _cmd_list(args: argparse.Namespace) -> int:
  199. from agent.learning_graph_render import format_date
  200. console = _console(color=not bool(getattr(args, "no_color", False)), force=bool(getattr(args, "force_color", False)))
  201. nodes = sorted(_build_payload().get("nodes", []), key=lambda n: n.get("timestamp") or 0)
  202. if not nodes:
  203. console.print("[grey62]No learning yet.[/grey62]")
  204. return 0
  205. for node in nodes:
  206. glyph = "◆" if node.get("kind") == "memory" else "●"
  207. date = format_date(node.get("timestamp"))
  208. console.print(f"[grey54]{node['id']}[/grey54] {glyph} {node.get('label', '')} [grey54]{date}[/grey54]")
  209. return 0
  210. def _lookup_node(node_id: str) -> Optional[dict]:
  211. """Resolve a node id via ``node_detail``; print the failure and return None when missing."""
  212. from agent.learning_mutations import node_detail
  213. detail = node_detail(node_id)
  214. if not detail.get("ok"):
  215. print(f" {detail.get('message', 'not found')}")
  216. return None
  217. return detail
  218. def _cmd_delete(args: argparse.Namespace) -> int:
  219. from agent.learning_mutations import delete_node
  220. detail = _lookup_node(args.node)
  221. if detail is None:
  222. return 1
  223. if not getattr(args, "yes", False):
  224. try:
  225. if input(f" Delete {detail['label']!r}? [y/N] ").strip().lower() not in ("y", "yes"):
  226. print(" aborted")
  227. return 1
  228. except (EOFError, KeyboardInterrupt):
  229. print("\n aborted")
  230. return 1
  231. res = delete_node(args.node)
  232. print(f" {res['message']}")
  233. return 0 if res.get("ok") else 1
  234. def _cmd_edit(args: argparse.Namespace) -> int:
  235. from agent.learning_mutations import edit_node
  236. detail = _lookup_node(args.node)
  237. if detail is None:
  238. return 1
  239. edited = _open_in_editor(detail["content"], suffix=".md" if detail["kind"] == "skill" else ".txt")
  240. if edited is None or edited.strip() == detail["content"].strip():
  241. print(" no changes")
  242. return 0
  243. res = edit_node(args.node, edited)
  244. print(f" {res['message']}")
  245. return 0 if res.get("ok") else 1
  246. def _open_in_editor(initial: str, *, suffix: str) -> Optional[str]:
  247. import os
  248. import subprocess
  249. import tempfile
  250. editor = os.environ.get("EDITOR") or os.environ.get("VISUAL") or "vi"
  251. with tempfile.NamedTemporaryFile("w", suffix=suffix, delete=False, encoding="utf-8") as fh:
  252. fh.write(initial)
  253. path = fh.name
  254. try:
  255. subprocess.call([*editor.split(), path])
  256. with open(path, encoding="utf-8-sig") as fh:
  257. return fh.read()
  258. except OSError as exc:
  259. print(f" editor failed: {exc}")
  260. return None
  261. finally:
  262. try:
  263. os.unlink(path)
  264. except OSError:
  265. pass
  266. def register_cli(parent: argparse.ArgumentParser) -> None:
  267. parent.add_argument(
  268. "--reveal", type=float, default=1.0, metavar="0..1",
  269. help="Render the timeline built up to this point (0=oldest, 1=now).",
  270. )
  271. parent.add_argument("--play", action="store_true", help="Animate the build-up over time (Ctrl-C to stop).")
  272. parent.add_argument("--fps", type=int, default=12, help="Animation frames per second for --play (default 12).")
  273. parent.add_argument("--width", type=int, default=None, help="Override render width in columns.")
  274. parent.add_argument("--height", type=int, default=None, help="Override render height in rows.")
  275. parent.add_argument("--no-color", action="store_true", help="Disable color output.")
  276. # Force ANSI even when stdout is captured — the interactive CLI re-renders it.
  277. parent.add_argument("--force-color", action="store_true", help=argparse.SUPPRESS)
  278. parent.add_argument("--json", action="store_true", help="Print the raw graph payload as JSON and exit.")
  279. parent.set_defaults(func=_cmd_show)
  280. sub = parent.add_subparsers(dest="journey_action")
  281. p_list = sub.add_parser("list", help="List node ids (for delete/edit).")
  282. p_list.add_argument("--no-color", action="store_true")
  283. p_list.add_argument("--force-color", action="store_true", help=argparse.SUPPRESS)
  284. p_list.set_defaults(func=_cmd_list)
  285. p_del = sub.add_parser("delete", help="Delete a learned skill (archived) or memory by node id.")
  286. p_del.add_argument("node", help="Node id (skill name, or a memory id exactly as `journey list` prints it).")
  287. p_del.add_argument("-y", "--yes", action="store_true", help="Skip the confirmation prompt.")
  288. p_del.set_defaults(func=_cmd_delete)
  289. p_edit = sub.add_parser("edit", help="Edit a learned skill or memory by node id in $EDITOR.")
  290. p_edit.add_argument("node", help="Node id (skill name, or a memory id exactly as `journey list` prints it).")
  291. p_edit.set_defaults(func=_cmd_edit)
  292. if __name__ == "__main__":
  293. _p = argparse.ArgumentParser(prog="hermes journey")
  294. register_cli(_p)
  295. _a = _p.parse_args()
  296. sys.exit(_a.func(_a))