The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent/curator+learning): inline single-use run-dir/tool-call helpers, compact module docstrings
Teknium4f37f11b6382
diff --git a/agent/curator.py b/agent/curator.pyindex ce1b9507efa..1b5821dbeb0 100644--- a/agent/curator.py+++ b/agent/curator.py@@ -1,15 +1,10 @@"""Curator — background skill maintenance orchestrator.-Inactivity-triggered (no cron daemon): when the agent is idle and the last run-is older than ``interval_hours``, ``maybe_run_curator()`` auto-transitions-lifecycle states from activity timestamps, optionally forks an AIAgent that may-pin/archive/consolidate/patch skills via skill_manage, and persists scheduler-state in ``.curator_state``.--Invariants: only curator-managed skills are touched; never delete, only archive-(recoverable); pinned skills bypass all auto-transitions; the fork uses the-auxiliary client and never touches the main session's prompt cache.-"""+Inactivity-triggered (no cron daemon): when the agent is idle and the last run is older than ``interval_hours``,+``maybe_run_curator()`` auto-transitions lifecycle states from activity timestamps, optionally forks an AIAgent that+may pin/archive/consolidate/patch skills via skill_manage, and persists scheduler state in ``.curator_state``.+Invariants: only curator-managed skills are touched; never delete, only archive (recoverable); pinned skills bypass+all auto-transitions; the fork uses the auxiliary client and never touches the main session's prompt cache."""from __future__ import annotations@@ -30,10 +25,8 @@ from utils import atomic_json_writelogger = logging.getLogger(__name__)-DEFAULT_INTERVAL_HOURS = 24 * 7 # 7 days-DEFAULT_MIN_IDLE_HOURS = 2-DEFAULT_STALE_AFTER_DAYS = 30-DEFAULT_ARCHIVE_AFTER_DAYS = 90+DEFAULT_INTERVAL_HOURS, DEFAULT_MIN_IDLE_HOURS = 24 * 7, 2 # 7 days+DEFAULT_STALE_AFTER_DAYS, DEFAULT_ARCHIVE_AFTER_DAYS = 30, 90# The LLM consolidation fork is opt-in; the deterministic inactivity prune# (apply_automatic_transitions) always runs when the curator is enabled.DEFAULT_CONSOLIDATE = False@@ -68,7 +61,8 @@ def save_state(data: Dict[str, Any]) -> None:logger.debug("Failed to save curator state: %s", e, exc_info=True)-def set_paused(paused: bool) -> None: save_state({**load_state(), "paused": bool(paused)})+def set_paused(paused: bool) -> None:+ save_state({**load_state(), "paused": bool(paused)})def is_paused() -> bool:@@ -677,8 +671,12 @@ def _write_file(path: Path, label: str, render: Any) -> None:logger.debug("Curator %s write failed: %s", label, e)-def _new_run_dir(started_at: datetime) -> Optional[Path]:- """``logs/curator/{YYYYMMDD-HHMMSS}[-N]/`` (N disambiguates a crash-rerun in the same second); None when it can't be created."""+def _write_run_report(+ *, started_at: datetime, elapsed_seconds: float, auto_counts: Dict[str, int], auto_summary: str,+ before_report: List[Dict[str, Any]], before_names: Set[str], after_report: List[Dict[str, Any]], llm_meta: Dict[str, Any],+) -> Optional[Path]:+ """Write run.json + REPORT.md under logs/curator/{YYYYMMDD-HHMMSS}[-N]/ (N disambiguates a crash-rerun in the same+ second). Returns the report dir, or None if it couldn't be created (reporting is best-effort)."""root, stamp = _reports_root(), started_at.strftime("%Y%m%d-%H%M%S")run_dir, suffix = root / stamp, 1while run_dir.exists():@@ -686,20 +684,9 @@ def _new_run_dir(started_at: datetime) -> Optional[Path]:run_dir = root / f"{stamp}-{suffix}"try:run_dir.mkdir(parents=True, exist_ok=False)- return run_direxcept Exception as e:logger.debug("Curator run dir create failed: %s", e)return None---def _write_run_report(- *, started_at: datetime, elapsed_seconds: float, auto_counts: Dict[str, int], auto_summary: str,- before_report: List[Dict[str, Any]], before_names: Set[str], after_report: List[Dict[str, Any]], llm_meta: Dict[str, Any],-) -> Optional[Path]:- """Write run.json + REPORT.md under logs/curator/{YYYYMMDD-HHMMSS}/. Returns the report dir, or None if it couldn't be created (best-effort)."""- run_dir = _new_run_dir(started_at)- if run_dir is None:- return Nonetool_calls = llm_meta.get("tool_calls", []) or []after_by_name, before_by_name = _by_name(after_report), _by_name(before_report)diff = _diff_and_classify(before_names, set(after_by_name), tool_calls, llm_meta.get("final", "") or "")@@ -886,11 +873,10 @@ def run_curator_review() -> Dict[str, Any]:"""Execute a single curator review pass: (1) automatic state transitions (no LLM); (2) if *consolidate* and there arecandidates, fork an AIAgent on the review prompt; (3) update .curator_state; (4) call *on_summary*.- *synchronous* runs the LLM review in the calling thread (default: daemon thread).- *consolidate* ``None`` reads ``curator.consolidate`` (OFF by default); when off- only the deterministic prune runs — no fork, no aux cost. *dry_run* SKIPS the- stale/archive transitions and instructs the fork to report only; REPORT.md is still- written and recorded in ``state.last_report_path`` so users can read what WOULD have happened."""+ *synchronous* runs the LLM review in the calling thread (default: daemon thread). *consolidate* ``None`` reads+ ``curator.consolidate`` (OFF by default); when off only the deterministic prune runs — no fork, no aux cost.+ *dry_run* SKIPS the stale/archive transitions and instructs the fork to report only; REPORT.md is still written and+ recorded in ``state.last_report_path`` so users can read what WOULD have happened."""consolidate = get_consolidate() if consolidate is None else consolidatestart = datetime.now(timezone.utc)if dry_run: # count candidates without mutating state@@ -970,26 +956,25 @@ def _merge_request_overrides(runtime_overrides: Any, slot_extra_body: Any) -> Direturn merged-def _slot_binding(provider: str, model: str, slot: Dict[str, Any]) -> _ReviewRuntimeBinding:- api_key, base_url = ((str(v).strip() or None) if v is not None else None for v in (slot.get("api_key"), slot.get("base_url")))- return _ReviewRuntimeBinding(provider, model, api_key, base_url, _merge_request_overrides({}, slot.get("extra_body")))--def _resolve_review_runtime(cfg: Dict[str, Any]) -> _ReviewRuntimeBinding:"""Curator is a regular auxiliary task slot (``auxiliary.curator.*``), so it rides the canonical aux-model plumbing. Precedence:1. ``auxiliary.curator.{provider,model}`` when both are set non-auto2. Legacy ``curator.auxiliary.{provider,model}`` (deprecated) when both set3. Main ``model.{provider,default/model}`` pair ("auto" + "" = main chat model)Non-empty slot ``api_key``/``base_url`` are returned as explicit overrides so ``resolve_runtime_provider`` doesn't reuse the main chat credential chain."""+ def _slot(provider: str, model: str, slot: Dict[str, Any]) -> _ReviewRuntimeBinding:+ api_key, base_url = ((str(v).strip() or None) if v is not None else None for v in (slot.get("api_key"), slot.get("base_url")))+ return _ReviewRuntimeBinding(provider, model, api_key, base_url, _merge_request_overrides({}, slot.get("extra_body")))+task = _subdict(cfg, "auxiliary", "curator")task_provider = (task.get("provider") or "").strip() or Nonetask_model = (task.get("model") or "").strip() or Noneif task_provider and task_provider != "auto" and task_model:- return _slot_binding(task_provider, task_model, task)+ return _slot(task_provider, task_model, task)legacy = _subdict(cfg, "curator", "auxiliary")if legacy.get("provider") and legacy.get("model"):logger.info("curator: using deprecated curator.auxiliary.{provider,model} config — please migrate to auxiliary.curator.{provider,model}")- return _slot_binding(str(legacy["provider"]), str(legacy["model"]), legacy)+ return _slot(str(legacy["provider"]), str(legacy["model"]), legacy)main = _subdict(cfg, "model")return _ReviewRuntimeBinding(main.get("provider") or "auto", main.get("default") or main.get("model") or "", None, None, {})@@ -1018,16 +1003,6 @@ def _resolve_review_provider() -> tuple:return rp, model_name, provider, overrides-def _collect_tool_calls(review_agent: Any) -> List[Dict[str, Any]]:- """[{name, arguments}] from the fork's session; arguments truncated to 400 chars so a giant skill_manage create doesn't blow up the report."""- calls: List[Dict[str, Any]] = []- for msg in getattr(review_agent, "_session_messages", []) or []:- for fn in ((tc.get("function") or {}) for tc in (msg.get("tool_calls") or []) if isinstance(tc, dict)) if isinstance(msg, dict) else []:- args_raw = fn.get("arguments") or ""- calls.append({"name": fn.get("name") or "", "arguments": args_raw[:400] + "…" if isinstance(args_raw, str) and len(args_raw) > 400 else args_raw})- return calls--def _run_llm_review(prompt: str) -> Dict[str, Any]:"""Spawn an AIAgent fork on the review prompt. Returns ``final`` (untruncated response), ``summary`` (240-char cap),``model``/``provider`` (what ran), ``tool_calls`` ([{name, arguments}], truncated) and ``error``. Never raises."""@@ -1072,7 +1047,13 @@ def _run_llm_review(prompt: str) -> Dict[str, Any]:final = str(conv_result.get("final_response") or "").strip() if isinstance(conv_result, dict) else ""result_meta["final"] = finalresult_meta["summary"] = (final[:240] + "…") if len(final) > 240 else (final or "no change")- result_meta["tool_calls"] = _collect_tool_calls(review_agent)+ # Tool calls for the report; arguments truncated to 400 chars so a giant skill_manage create doesn't blow it up.+ fns = (tc.get("function") or {} for msg in getattr(review_agent, "_session_messages", []) or [] if isinstance(msg, dict)+ for tc in (msg.get("tool_calls") or []) if isinstance(tc, dict))+ result_meta["tool_calls"] = [+ {"name": fn.get("name") or "", "arguments": a[:400] + "…" if isinstance(a, str) and len(a) > 400 else a}+ for fn in fns for a in (fn.get("arguments") or "",)+ ]except Exception as e:result_meta["error"] = result_meta["summary"] = f"error: {e}"finally:diff --git a/agent/insights.py b/agent/insights.pyindex 0880ae9de65..5a77136ace0 100644--- a/agent/insights.py+++ b/agent/insights.py@@ -1,9 +1,5 @@-"""Session Insights Engine: aggregates the SQLite state DB into usage insights-(tokens, cost estimates, tool/skill usage, activity, model/platform breakdowns).-- engine = InsightsEngine(db); report = engine.generate(days=30)- print(engine.format_terminal(report))-"""+"""Session Insights Engine: aggregates the SQLite state DB into usage insights (tokens, cost estimates, tool/skill+usage, activity, model/platform breakdowns). ``InsightsEngine(db).generate(days=30)`` → ``format_terminal(report)``."""import jsonimport sqlite3diff --git a/agent/learn_prompt.py b/agent/learn_prompt.pyindex 2a879a66436..db50f95aa31 100644--- a/agent/learn_prompt.py+++ b/agent/learn_prompt.py@@ -1,13 +1,9 @@-"""``/learn`` — build the ONE prompt that turns whatever the user described-(code dir, doc URL, "what we just did", pasted notes) into a reusable skill.--The live agent gathers sources with its existing tools and authors the skill via-``skill_manage`` per the Hermes authoring standards; large prose sources get the-knowledge-base layout (lean SKILL.md index + per-chapter ``references/``, after-virgiliojr94/book-to-skill). No distillation engine, no model-tool footprint, so-it works identically on local, Docker, and remote backends; every surface-(CLI/gateway ``/learn``, dashboard) calls :func:`build_learn_prompt` as a normal turn.-"""+"""``/learn`` — build the ONE prompt that turns whatever the user described (code dir, doc URL, "what we just did",+pasted notes) into a reusable skill. The live agent gathers sources with its existing tools and authors the skill via+``skill_manage`` per the Hermes authoring standards; large prose sources get the knowledge-base layout (lean SKILL.md+index + per-chapter ``references/``, after virgiliojr94/book-to-skill). No distillation engine, no model-tool footprint,+so it works identically on local, Docker, and remote backends; every surface (CLI/gateway ``/learn``, dashboard) calls+:func:`build_learn_prompt` as a normal turn."""from __future__ import annotationsdiff --git a/agent/learning_graph_render.py b/agent/learning_graph_render.pyindex 53838a48530..dd3fe3eabac 100644--- a/agent/learning_graph_render.py+++ b/agent/learning_graph_render.py@@ -1,12 +1,8 @@-"""Terminal renderer for the learning timeline (learned skills + memories).--Same data as the desktop starmap (``apps/desktop/src/app/starmap``), drawn as a-timeline bar chart (date rows, skill/memory bars colored by dominant category,-cumulative trajectory sparkline) plus per-slice bucket metadata the TUI walks as-a tree. Age gradient and memory ink are ported from the desktop source. Grids-are style runs ``[text, style, alpha, hex?]``: consumers map style + brightness-onto their palette; hex overrides the base color (category heatmap). Pure, stdlib-only.-"""+"""Terminal renderer for the learning timeline (learned skills + memories): the desktop starmap's data+(``apps/desktop/src/app/starmap``) drawn as a timeline bar chart (date rows, skill/memory bars colored by dominant+category, cumulative trajectory sparkline) plus per-slice bucket metadata the TUI walks as a tree. Age gradient and+memory ink are ported from the desktop source. Grids are style runs ``[text, style, alpha, hex?]``: consumers map+style + brightness onto their palette; hex overrides the base color (category heatmap). Pure, stdlib-only."""from __future__ import annotations@@ -24,28 +20,42 @@ STYLE_BG, STYLE_SKILL, STYLE_MEMORY, STYLE_LABEL, STYLE_DIM = "bg", "skill", "meSKILL_GLYPH, MEMORY_GLYPH = "●", "◆"_LABEL_KEYS = tuple("123456789abc")-Run = list # [text, style, alpha, hex?]-Row = list # list[Run]-Grid = list # list[Row]+Row = list # of runs ``[text, style, alpha, hex?]``; a grid is a list of rowsdef _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()@@ -328,7 +338,7 @@ def render_graph(payload: dict[str, Any], *, cols: int = 80, rows: int = 16, revlabel_w = min(9, max(len(b.label) for b in buckets))bar_w = max(14, cols - label_w - 16)- grid: Grid = []+ grid: list[Row] = []labels: list[dict[str, Any]] = []visible = 0for i, bucket in enumerate(buckets[:visible_bucket_count]):diff --git a/agent/learning_mutations.py b/agent/learning_mutations.pyindex 3bc9a75221c..a64f73fde06 100644--- a/agent/learning_mutations.py+++ b/agent/learning_mutations.py@@ -60,7 +60,6 @@ def _write_memory(path: Path, chunks: list[str]) -> None:"""Atomic temp-file + rename via the memory tool, so a concurrent readernever sees a half-written file (and the §-join stays single-sourced)."""from tools.memory_tool import MemoryStore-MemoryStore._write_file(path, [c.strip() for c in chunks if c.strip()])@@ -95,7 +94,6 @@ def _memory_detail(node_id: str) -> dict[str, Any]:def _skill_detail(node_id: str) -> dict[str, Any]:from tools.skill_manager_tool import _find_skill-found = _find_skill(node_id)if not found:return {"ok": False, "message": f"skill '{node_id}' not found"}@@ -113,7 +111,6 @@ def delete_node(node_id: str) -> dict[str, Any]:def _delete_skill(name: str) -> dict[str, Any]:from tools import skill_usage-if skill_usage.get_record(name).get("pinned"):return {"ok": False, "message": f"'{name}' is pinned — unpin it first (hermes curator unpin {name})"}ok, message = skill_usage.archive_skill(name)@@ -137,7 +134,6 @@ def edit_node(node_id: str, content: str) -> dict[str, Any]:def _edit_skill(name: str, content: str) -> dict[str, Any]:from tools.skill_manager_tool import _edit_skill as _do_edit-result = _do_edit(name, content)if result.get("success"):_clear_skill_cache()