Skip to content

The agent that grows with you

feat(skills): dedup repeat skill_view calls with an unchanged-content stub

Teknium2a3a7e6f53b8
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index 93a295e27cd..3f1cd3912e9 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -2682,6 +2682,13 @@ def compress_context(
reset_file_dedup(task_id)
except Exception:
pass
+ # Same for the skill_view repeat-view dedup: a post-compression
+ # re-view must return the full skill content again.
+ try:
+ from tools.skills_tool import reset_skill_view_dedup
+ reset_skill_view_dedup(task_id)
+ except Exception:
+ pass
logger.info(
"context compression done: session=%s messages=%d->%d rough_tokens=~%s awaiting_real_usage=true",
diff --git a/tests/tools/test_skill_view_dedup.py b/tests/tools/test_skill_view_dedup.py
new file mode 100644
index 00000000000..8234f6a39cf
--- /dev/null
+++ b/tests/tools/test_skill_view_dedup.py
@@ -0,0 +1,94 @@
+"""Tests for skill_view repeat-view dedup (unchanged-skill stub)."""
+
+import json
+import os
+import time
+from pathlib import Path
+
+import pytest
+
+from tools.skills_tool import (
+ _skill_view_with_bump,
+ reset_skill_view_dedup,
+)
+
+
+def skills_home(tmp_path, monkeypatch):
+ home = tmp_path / ".hermes"
+ skills = home / "skills"
+ d = skills / "demo-dedup-skill"
+ d.mkdir(parents=True)
+ (d / "SKILL.md").write_text(
+ "---\nname: demo-dedup-skill\ndescription: Demo skill for dedup tests.\n---\n"
+ "# Demo\n\nStep one: run the demo procedure fully.\n"
+ )
+ refs = d / "references"
+ refs.mkdir()
+ (refs / "guide.md").write_text("# Guide\n\nDetailed reference content here.\n")
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ reset_skill_view_dedup()
+ return home
+
+
+def _view(name, file_path=None, task="t-svd"):
+ args = {"name": name}
+ if file_path:
+ args["file_path"] = file_path
+ return json.loads(_skill_view_with_bump(args, task_id=task))
+
+
+class TestSkillViewDedup:
+ def test_first_view_returns_full_content(self, skills_home):
+ r = _view("demo-dedup-skill")
+ assert r["success"] is True
+ assert "Step one" in r.get("content", "")
+
+ def test_repeat_view_returns_stub(self, skills_home):
+ _view("demo-dedup-skill")
+ r2 = _view("demo-dedup-skill")
+ assert r2["success"] is True
+ assert r2.get("dedup") is True
+ assert r2.get("content_returned") is False
+ assert "unchanged" in r2["message"]
+ assert "content" not in r2
+
+ def test_modified_skill_returns_full_content(self, skills_home):
+ _view("demo-dedup-skill")
+ md = skills_home / "skills" / "demo-dedup-skill" / "SKILL.md"
+ time.sleep(0.01)
+ md.write_text(md.read_text() + "\nStep two: new instruction.\n")
+ r2 = _view("demo-dedup-skill")
+ assert "Step two" in r2.get("content", "")
+ assert r2.get("dedup") is None
+
+ def test_linked_file_dedup_is_independent(self, skills_home):
+ _view("demo-dedup-skill")
+ # First view of a DIFFERENT file within the skill: full content.
+ r = _view("demo-dedup-skill", file_path="references/guide.md")
+ assert "Detailed reference" in r.get("content", "")
+ # Repeat of that file: stub.
+ r2 = _view("demo-dedup-skill", file_path="references/guide.md")
+ assert r2.get("dedup") is True
+
+ def test_different_tasks_do_not_share_cache(self, skills_home):
+ _view("demo-dedup-skill", task="task-A")
+ r = _view("demo-dedup-skill", task="task-B")
+ assert "Step one" in r.get("content", "")
+
+ def test_reset_returns_full_content(self, skills_home):
+ _view("demo-dedup-skill")
+ reset_skill_view_dedup("t-svd")
+ r2 = _view("demo-dedup-skill")
+ assert "Step one" in r2.get("content", "")
+
+ def test_no_task_id_never_dedups(self, skills_home):
+ args = {"name": "demo-dedup-skill"}
+ r1 = json.loads(_skill_view_with_bump(args, task_id=None))
+ r2 = json.loads(_skill_view_with_bump(args, task_id=None))
+ assert "Step one" in r2.get("content", "")
+
+ def test_compression_hook_importable(self):
+ # conversation_compression imports this lazily; keep the seam stable.
+ from tools.skills_tool import reset_skill_view_dedup as f
+ f(None)
diff --git a/tools/skills_tool.py b/tools/skills_tool.py
index 9566b3a3b7f..e38e3324690 100644
--- a/tools/skills_tool.py
+++ b/tools/skills_tool.py
@@ -69,6 +69,7 @@ Usage:
import json
import logging
import time
+import threading
from hermes_constants import get_hermes_home, display_hermes_home
import os
@@ -1397,6 +1398,9 @@ def skill_view(
"file": file_path,
"content": content,
"file_type": target_file.suffix,
+ # Internal: absolute source path for the repeat-view dedup
+ # fingerprint (mtime+size change detection).
+ "_source_path": str(target_file),
},
ensure_ascii=False,
)
@@ -1652,6 +1656,9 @@ def skill_view(
"readiness_status": SkillReadinessStatus.SETUP_NEEDED.value
if setup_needed
else SkillReadinessStatus.AVAILABLE.value,
+ # Internal: absolute source path for the repeat-view dedup
+ # fingerprint (mtime+size change detection).
+ "_source_path": str(skill_md),
}
setup_help = next((e["help"] for e in required_env_vars if e.get("help")), None)
@@ -1793,16 +1800,140 @@ registry.register(
check_fn=check_skills_requirements,
emoji="πŸ“š",
)
+# ── skill_view repeat-view dedup ────────────────────────────────────────
+# Per-task cache of (skill name, file_path) -> (skill file mtime+size).
+# On a repeat view of an UNCHANGED skill file, return a short stub instead
+# of re-sending the full content β€” the earlier tool result in this
+# conversation already carries it verbatim. Cleared on context compression
+# via reset_skill_view_dedup() (wired next to read_file's reset_file_dedup)
+# because after compression the original content is summarized away.
+_skill_view_tracker: Dict[str, Dict[tuple, tuple]] = {}
+_skill_view_tracker_lock = threading.Lock()
+_SKILL_VIEW_DEDUP_CAP = 200
+
+_SKILL_VIEW_DEDUP_MESSAGE = (
+ "Skill content unchanged since it was loaded earlier in this "
+ "conversation β€” refer to the earlier skill_view result; it is still "
+ "current and complete. (Re-issued after context compression, this "
+ "returns the full content again.)"
+)
+
+
+def _skill_view_fingerprint(payload: dict) -> tuple | None:
+ """Stat the skill file a successful skill_view served, for change detection."""
+ src = payload.get("_source_path")
+ if not src:
+ return None
+ try:
+ st = os.stat(src)
+ return (src, st.st_mtime_ns, st.st_size)
+ except OSError:
+ return None
+
+
+def _record_skill_view(task_id, name, file_path, payload: dict) -> None:
+ """Record a served skill_view so an identical repeat can be deduped."""
+ if not task_id:
+ return
+ # Never dedup setup-needed views: readiness depends on config/env state
+ # that can change without the skill file changing, and the model must
+ # see the refreshed setup status on a re-view.
+ if payload.get("setup_needed") or payload.get("readiness_status") == "setup_needed":
+ return
+ fp = _skill_view_fingerprint(payload)
+ if fp is None:
+ return
+ key = (str(payload.get("name") or name), file_path or "")
+ with _skill_view_tracker_lock:
+ cache = _skill_view_tracker.setdefault(str(task_id), {})
+ cache[key] = fp
+ while len(cache) > _SKILL_VIEW_DEDUP_CAP:
+ try:
+ cache.pop(next(iter(cache)))
+ except (StopIteration, KeyError):
+ break
+
+
+def _check_skill_view_dedup(task_id, name, file_path) -> str | None:
+ """Return a dedup stub when this exact skill file was already served
+ to this task and is unchanged on disk; None otherwise."""
+ if not task_id:
+ return None
+ with _skill_view_tracker_lock:
+ cache = _skill_view_tracker.get(str(task_id))
+ if not cache:
+ return None
+ # The record key uses the RESOLVED name; check both the raw arg and
+ # resolved forms so 'category/skill' and bare-name views coalesce.
+ for key, (src, mtime_ns, size) in list(cache.items()):
+ rec_name, rec_fp = key
+ if rec_fp != (file_path or ""):
+ continue
+ if rec_name != str(name) and not str(name).endswith("/" + rec_name) \
+ and not rec_name.endswith("/" + str(name)) \
+ and str(name).split(":")[-1] != rec_name:
+ continue
+ try:
+ st = os.stat(src)
+ if (st.st_mtime_ns, st.st_size) != (mtime_ns, size):
+ cache.pop(key, None)
+ return None
+ except OSError:
+ cache.pop(key, None)
+ return None
+ return json.dumps(
+ {
+ "success": True,
+ "status": "unchanged",
+ "name": rec_name,
+ "file": file_path or "SKILL.md",
+ "dedup": True,
+ "content_returned": False,
+ "message": _SKILL_VIEW_DEDUP_MESSAGE,
+ },
+ ensure_ascii=False,
+ )
+ return None
+
+
+def reset_skill_view_dedup(task_id: str | None = None) -> None:
+ """Clear the skill_view dedup cache (all tasks when task_id is None).
+
+ Called on context compression: the original skill content is
+ summarized away, so a re-view must return full content again.
+ """
+ with _skill_view_tracker_lock:
+ if task_id is None:
+ _skill_view_tracker.clear()
+ else:
+ _skill_view_tracker.pop(str(task_id), None)
+
+
def _skill_view_with_bump(args, **kw):
"""Invoke skill_view, then bump view_count on success. Best-effort: a
telemetry failure never breaks the tool call."""
name = args.get("name", "")
+ task_id = kw.get("task_id")
+ # ── Repeat-view dedup ────────────────────────────────────────────
+ # Mirrors read_file's unchanged-stub: when this session already
+ # loaded the SAME skill file and it hasn't changed on disk, return a
+ # short stub instead of re-sending the full content (production
+ # mining: ~286k tokens of verbatim repeat skill_view content in one
+ # 400k-message window). The stub only ever replaces content that is
+ # already fully present earlier in this conversation, so the
+ # "skills must be loaded fully" rule is preserved β€” and the cache is
+ # cleared on context compression (same hook as read_file's dedup)
+ # so a post-compression re-view returns full content again.
+ stub = _check_skill_view_dedup(task_id, name, args.get("file_path"))
+ if stub is not None:
+ return stub
result = skill_view(
- name, file_path=args.get("file_path"), task_id=kw.get("task_id")
+ name, file_path=args.get("file_path"), task_id=task_id
)
try:
parsed = json.loads(result)
if isinstance(parsed, dict) and parsed.get("success"):
+ _record_skill_view(task_id, name, args.get("file_path"), parsed)
# Use the resolved skill name from the payload when present β€”
# qualified forms ("plugin:skill") return with the canonical name.
resolved = parsed.get("name") or name