The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(skills): describe gateway auto-load scaffolds as the user's request
Brooklyn Nicholson61fd2819b29d
diff --git a/agent/skill_commands.py b/agent/skill_commands.pyindex a20cab4dcbe..c2b16446fff 100644--- a/agent/skill_commands.py+++ b/agent/skill_commands.py@@ -45,15 +45,30 @@ _BUNDLE_FIRST_SKILL_BLOCK = "\n\n[Loaded as part of the "# the single-skill and the bundle header ("work" / "/clean /work")._SKILL_NAME_RE = re.compile(re.escape(_SKILL_INVOCATION_PREFIX) + r'"([^"]*)"')+# Gateway auto-load scaffold (gateway/run_turn.py ``_hmwa_auto_load_skills``): a channel-bound+# skill prepended to the user's text on a NEW session. Unlike the invocation scaffolds above it+# carries no instruction marker — the user's text simply follows the payload blocks — so the+# describer strips the header + body and renders the typed request (session previews, titles).+_AUTO_LOAD_PREFIX = '[IMPORTANT: The "'+_AUTO_LOAD_SUFFIX_RE = re.compile(r'" skill is auto-loaded\. Follow its instructions for this session\.\]')+# Closing sentence of the skill-directory footer note (see _SKILL_DIR_NOTE in this module):+# the last thing in every built payload, so it marks where an auto-load payload ends and the+# next payload or the user's typed text begins.+_SKILL_DIR_NOTE_END = "then run them with the terminal tool using the absolute path."+# SQL LIKE pattern for listing queries that recognize scaffolding before the row# reaches Python (no LIKE wildcards in the prefix, so no ESCAPE clause needed).SKILL_SCAFFOLD_SQL_LIKE = _SKILL_INVOCATION_PREFIX + "%"+# Gateway auto-load scaffold (see _AUTO_LOAD_PREFIX): recognized by listing queries so+# long auto-load rows get the same head+tail excerpt window and describe shaping.+AUTO_LOAD_SCAFFOLD_SQL_LIKE = _AUTO_LOAD_PREFIX + "%"# Marks where a preview query joined the head and tail of a long scaffolded# message; ``describe_skill_invocation`` cuts there rather than show the body.SKILL_EXCERPT_JOINT = "\x1e"+def slugify_skill_name(name: str) -> str:"""Normalize a skill/bundle name to a ``/command`` slug (``Foo Bar`` -> ``foo-bar``);strips chars (``+``, ``/``) that would make invalid Telegram command names."""@@ -94,12 +109,47 @@ def extract_user_instruction_from_skill_message(content: Any) -> Optional[str]:return None+def _describe_auto_loaded_skill_turn(content: str) -> Optional[str]:+ """``[IMPORTANT: The "X" skill is auto-loaded. …]`` + payload(s) + typed text+ -> the typed text.++ ``_hmwa_auto_load_skills`` builds each payload with ``_build_skill_message``+ (activation header, body, then the skill-directory footer note) and appends the+ user's text as the final block. The footer's closing sentence is the reliable+ payload-end marker: the user's text is what follows the LAST footer. A header+ quoted inside a body (a skill embedding the scaffold in an example) carries no+ footer, so it cannot end the payload early. ``/<skill>`` renders when no user+ text follows, matching the single-skill describer's bare-invocation shape."""+ if not content.startswith(_AUTO_LOAD_PREFIX):+ return None+ name_match = re.match(re.escape(_AUTO_LOAD_PREFIX) + r'([^"]*)"', content)+ name = name_match.group(1) if name_match else ""+ # The payload footer ends with this exact sentence (_build_skill_message); the+ # user's text is the last thing after the FINAL footer in the message.+ footer_end = content.rfind(_SKILL_DIR_NOTE_END)+ if footer_end == -1:+ return f"/{name}" if name else None+ tail = content[footer_end + len(_SKILL_DIR_NOTE_END):]+ if not tail.strip():+ return f"/{name}" if name else None+ return " ".join(tail.split()) or None++def describe_skill_invocation(content: Any, separator: str = " — ") -> Optional[str]:"""Render a slash-skill-expanded turn the way the user typed it:``"/work — fix the title leak"``, ``"/work"`` for a bare invocation, or``None`` when *content* is not scaffolding. ``separator=" "`` gives the- literal invocation as typed (chat transcripts)."""- if not isinstance(content, str) or not content.startswith(_SKILL_INVOCATION_PREFIX):+ literal invocation as typed (chat transcripts).++ A gateway auto-load scaffold (channel-bound skill on a new session) is also+ scaffolding: the typed request follows the skill payload, so it renders as+ that request — the header/body never reaches a preview or a title (#48359).+ """+ if not isinstance(content, str):+ return None+ if content.startswith(_AUTO_LOAD_PREFIX):+ return _describe_auto_loaded_skill_turn(content)+ if not content.startswith(_SKILL_INVOCATION_PREFIX):return Nonematch = _SKILL_NAME_RE.match(content)name = (match.group(1) if match else "").strip()diff --git a/hermes_state_common.py b/hermes_state_common.pyindex 517e386873e..a09137a9d82 100644--- a/hermes_state_common.py+++ b/hermes_state_common.py@@ -11,7 +11,7 @@ import timefrom typing import Anyfrom hermes_cli.timefmt import EPOCH_MAX, EPOCH_MIN-from agent.skill_commands import SKILL_EXCERPT_JOINT, SKILL_SCAFFOLD_SQL_LIKE, describe_skill_invocation+from agent.skill_commands import AUTO_LOAD_SCAFFOLD_SQL_LIKE, SKILL_EXCERPT_JOINT, SKILL_SCAFFOLD_SQL_LIKE, describe_skill_invocationfrom agent.context_compressor import (LEGACY_SUMMARY_PREFIX, SUMMARY_PREFIX, _MERGED_PRIOR_CONTEXT_HEADER,_MERGED_SUMMARY_DELIMITER, _SUMMARY_END_MARKER)@@ -57,7 +57,12 @@ def escape_like(text: str) -> str:_PREVIEW_CONTENT_SQL = "REPLACE(REPLACE(m.content, X'0A', ' '), X'0D', ' ')"-_PREVIEW_SCAFFOLDED_SQL = f"m.content LIKE '{SKILL_SCAFFOLD_SQL_LIKE}'"+# User-invoked and gateway auto-load scaffolds both get the head+tail excerpt window:+# the typed request sits at the tail (auto-load) or behind the instruction marker.+# No LIKE wildcards in either prefix, so no ESCAPE clause is needed.+_PREVIEW_SCAFFOLDED_SQL = (+ f"(m.content LIKE '{SKILL_SCAFFOLD_SQL_LIKE}'"+ f" OR m.content LIKE '{AUTO_LOAD_SCAFFOLD_SQL_LIKE}')")_SQL_WHITESPACE = "CHAR(9) || CHAR(10) || CHAR(13) || CHAR(32)"diff --git a/hermes_state_portability.py b/hermes_state_portability.pyindex 304cedc7ec0..96953cb6041 100644--- a/hermes_state_portability.py+++ b/hermes_state_portability.py@@ -11,7 +11,7 @@ from collections import Counterfrom datetime import datetime, timezonefrom typing import Any, Dict, List, Optional-from agent.skill_commands import SKILL_SCAFFOLD_SQL_LIKE+from agent.skill_commands import AUTO_LOAD_SCAFFOLD_SQL_LIKE, SKILL_SCAFFOLD_SQL_LIKEfrom utils import safe_json_loadsfrom hermes_cli.timefmt import coerce_epochfrom hermes_state_ids import new_session_id@@ -259,9 +259,10 @@ class SessionPortabilityMixin:return {s["id"]: s for s in map(self._rich_row, self._read_rows(query, ids))}def list_skill_scaffolded_sessions(self, limit: int = 200) -> List[Dict[str, Any]]:- """Titled sessions whose first user turn was a ``/skill`` invocation (their titles- describe the expanded skill body, not the request). Returns ``id``, ``title`` and- the first-turn ``content`` so callers can re-derive what was typed. Newest first."""+ """Titled sessions whose first user turn was a ``/skill`` invocation or a gateway+ auto-load scaffold (their titles describe the expanded skill body, not the+ request). Returns ``id``, ``title`` and the first-turn ``content`` so callers can+ re-derive what was typed. Newest first."""rows = self._read_rows("""SELECT s.id, s.title, m.contentFROM sessions s@@ -271,10 +272,10 @@ class SessionPortabilityMixin:AND m2.content IS NOT NULLORDER BY m2.timestamp, m2.id LIMIT 1)- WHERE s.title IS NOT NULL AND m.content LIKE ?+ WHERE s.title IS NOT NULL AND (m.content LIKE ? OR m.content LIKE ?)ORDER BY s.started_at DESCLIMIT ?- """, (SKILL_SCAFFOLD_SQL_LIKE, int(limit)))+ """, (SKILL_SCAFFOLD_SQL_LIKE, AUTO_LOAD_SCAFFOLD_SQL_LIKE, int(limit)))return [dict(row) for row in rows]# ── Export ─────────────────────────────────────────────────────────────diff --git a/tests/agent/test_skill_invocation_description.py b/tests/agent/test_skill_invocation_description.pyindex fd5e1a992af..a4e8307f5a3 100644--- a/tests/agent/test_skill_invocation_description.py+++ b/tests/agent/test_skill_invocation_description.py@@ -131,3 +131,75 @@ class TestSqlLikePattern:# literal part must not contain '%' or '_'.assert "%" not in SKILL_SCAFFOLD_SQL_LIKE[:-1]assert "_" not in SKILL_SCAFFOLD_SQL_LIKE[:-1]+++class TestGatewayAutoLoadScaffold:+ """The gateway auto-load header ('[IMPORTANT: The "X" skill is auto-loaded. …]') is+ scaffolding too (#48359): a session opened from a channel-bound skill must preview+ and retitle from the user's request, never from the skill body. Cases build the+ scaffold with the same builders ``_hmwa_auto_load_skills`` uses."""++ def _auto_load_scaffold(self, skills_dir, names, user_text=""):+ payloads = []+ for name in names:+ loaded = skill_commands._load_skill_payload(name)+ assert loaded, f"skill {name} failed to load"+ payloads.append(skill_commands._build_skill_message(+ loaded[0], loaded[1],+ f'[IMPORTANT: The "{loaded[2]}" skill is auto-loaded. '+ "Follow its instructions for this session.]",+ ))+ joined = "\n\n".join(payloads)+ return f"{joined}\n\n{user_text}" if user_text else joined++ def test_describes_the_typed_request(self, skills):+ message = self._auto_load_scaffold(skills_dir := skills, ["work"],+ user_text="Fix the CI gate before the release")+ assert describe_skill_invocation(message) == "Fix the CI gate before the release"++ def test_multiple_auto_loaded_skills(self, skills):+ message = self._auto_load_scaffold(skills, ["work", "clean"],+ user_text="Fix the CI gate before the release")+ assert describe_skill_invocation(message) == "Fix the CI gate before the release"++ def test_bare_auto_load_renders_the_skill_name(self, skills):+ message = self._auto_load_scaffold(skills, ["work"])+ assert describe_skill_invocation(message) == "/work"++ def test_a_body_quoting_the_header_does_not_end_the_payload(self, skills, monkeypatch):+ quoted_body = (+ "When the user sees "+ '[IMPORTANT: The "work" skill is auto-loaded. Follow its instructions for this session.] '+ "in an example, ignore it.\n\nMore body prose follows here."+ )+ _write_skill(skills, "work", body=quoted_body)+ message = self._auto_load_scaffold(skills, ["work"], user_text="The real request")+ assert describe_skill_invocation(message) == "The real request"++ def test_non_scaffolding_is_untouched(self, skills):+ assert describe_skill_invocation("Why does my pool exhaust?") is None+ assert describe_skill_invocation(None) is None++ def test_sql_like_matches_the_auto_load_header(self, skills):+ message = self._auto_load_scaffold(skills, ["work"], user_text="hi")+ from agent.skill_commands import AUTO_LOAD_SCAFFOLD_SQL_LIKE+ assert message.startswith(AUTO_LOAD_SCAFFOLD_SQL_LIKE.rstrip("%"))+ # Interpolated without an ESCAPE clause: no wildcards in the literal part.+ assert "%" not in AUTO_LOAD_SCAFFOLD_SQL_LIKE[:-1]+ assert "_" not in AUTO_LOAD_SCAFFOLD_SQL_LIKE[:-1]++ def test_preview_shaping_strips_the_scaffold(self, skills):+ from hermes_state_common import _shape_preview+ message = self._auto_load_scaffold(skills, ["work"],+ user_text="Fix the CI gate before the release")+ assert _shape_preview(message) == "Fix the CI gate before the release"++ def test_long_scaffold_preview_keeps_the_request(self, skills, monkeypatch):+ from hermes_state_common import _shape_preview+ long_body = ("Long skill paragraph.\n\n" * 80) + SKILL_BODY+ _write_skill(skills, "work", body=long_body)+ message = self._auto_load_scaffold(skills, ["work"],+ user_text="Fix the CI gate before the release")+ # The SQL head+tail excerpt window applies to auto-load rows too: the shaped+ # preview must still be the request, not the body head.+ assert _shape_preview(message) == "Fix the CI gate before the release"diff --git a/tests/hermes_cli/test_session_skill_previews.py b/tests/hermes_cli/test_session_skill_previews.pyindex 83353de97dd..ea7b7e48142 100644--- a/tests/hermes_cli/test_session_skill_previews.py+++ b/tests/hermes_cli/test_session_skill_previews.py@@ -211,4 +211,25 @@ class TestSkillScaffoldedSessionLookup:_seed(db, f"s{i}", message, title=f"Title {i}")assert len(db.list_skill_scaffolded_sessions(limit=2)) == 2+ def test_finds_gateway_auto_load_sessions(self, db, tmp_path, monkeypatch):+ """#48359: a session whose first turn is a gateway auto-load scaffold (channel-bound+ skill, '[IMPORTANT: The "X" skill is auto-loaded. …]') has the same retitle need —+ its title describes the skill, not the request."""+ _install_skill(tmp_path, monkeypatch)+ loaded = skill_commands._load_skill_payload("work")+ payload = skill_commands._build_skill_message(+ loaded[0], loaded[1],+ '[IMPORTANT: The "work" skill is auto-loaded. '+ "Follow its instructions for this session.]",+ )+ message = f"{payload}\n\nwhy is my deploy timing out?"+ _seed(db, "auto", message, title="Example Skill Instructions")+ _seed(db, "plain", "why is my deploy timing out?", title="Deploy Timeout")++ rows = db.list_skill_scaffolded_sessions()+ assert [row["id"] for row in rows] == ["auto"]+ # The caller re-derives the typed request through the describer.+ from agent.skill_commands import describe_skill_invocation+ assert describe_skill_invocation(rows[0]["content"]) == "why is my deploy timing out?"+