The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(skills): skill_view dedup compares the served content
Maciej Lisiewskieedf3944e9e8
diff --git a/tests/agent/test_proactive_prune_loop_wiring.py b/tests/agent/test_proactive_prune_loop_wiring.pyindex 767e71373e0..13a2708ddf4 100644--- a/tests/agent/test_proactive_prune_loop_wiring.py+++ b/tests/agent/test_proactive_prune_loop_wiring.py@@ -18,6 +18,8 @@ These tests drive ``run_conversation()`` through real tool iterations and pin:from __future__ import annotationsimport json+import os+import timefrom types import SimpleNamespacefrom unittest.mock import MagicMock, patch@@ -292,12 +294,12 @@ class TestCommittedPruneIsDedupBoundary:@staticmethoddef _seed_dedup(tmp_path, task_id):from tools.file_tools_read_tracking import _read_tracker, _read_tracker_lock, _task_data- from tools.skills_tool_dedup import _record_skill_view, reset_skill_view_dedup+ from tools.skills_tool_dedup import dedup_skill_view, reset_skill_view_dedupskill_md = tmp_path / "SKILL.md"skill_md.write_text("# s\n", encoding="utf-8")reset_skill_view_dedup(task_id)- _record_skill_view(task_id, "bigskill", None, {"name": "bigskill", "_source_path": str(skill_md)})+ dedup_skill_view(task_id, "bigskill", None, {"name": "bigskill"}, '{"success": true, "content": "# s"}')with _read_tracker_lock:_read_tracker.pop(task_id, None)td = _task_data(task_id)@@ -308,9 +310,9 @@ class TestCommittedPruneIsDedupBoundary:@staticmethoddef _dedup_state(task_id):from tools.file_tools_read_tracking import _read_tracker- from tools.skills_tool_dedup import _check_skill_view_dedup+ from tools.skills_tool_dedup import _skill_view_tracker- skill_stubbed = _check_skill_view_dedup(task_id, "bigskill", None) is not None+ skill_stubbed = ("bigskill", "") in _skill_view_tracker.get(task_id, {})file_in_generation = ("/x/big.txt", 1, 2000) in _read_tracker[task_id]["dedup_generation_reads"]return skill_stubbed, file_in_generationdiff --git a/tests/agent/test_read_dedup_rewrite_boundaries.py b/tests/agent/test_read_dedup_rewrite_boundaries.pyindex 7e723b6e92f..3aeda059de9 100644--- a/tests/agent/test_read_dedup_rewrite_boundaries.py+++ b/tests/agent/test_read_dedup_rewrite_boundaries.py@@ -9,6 +9,8 @@ so the next repeat must serve content again, as after compaction (#32106).from __future__ import annotationsimport json+import os+import timefrom types import SimpleNamespacefrom unittest.mock import MagicMock, patch@@ -16,7 +18,7 @@ import pytestfrom tools.file_tools_read_tracking import _read_tracker, _read_tracker_lock, _task_datafrom tools.skills_tool import _skill_view_with_bump-from tools.skills_tool_dedup import _check_skill_view_dedup, reset_skill_view_dedup+from tools.skills_tool_dedup import _skill_view_tracker, reset_skill_view_dedupTASK = "rewrite-boundary-task"FILE_KEY = ("/x/big.txt", 1, 2000)@@ -54,7 +56,7 @@ def _dedup_state():"""(a skill_view repeat would get the stub, a read_file repeat would get the stub)."""with _read_tracker_lock:file_stubbed = FILE_KEY in _read_tracker.get(TASK, {}).get("dedup_generation_reads", ())- return _check_skill_view_dedup(TASK, "demo-skill", None) is not None, file_stubbed+ return ("demo-skill", "") in _skill_view_tracker.get(TASK, {}), file_stubbeddef _run(agent, history, monkeypatch):diff --git a/tests/tools/test_skill_view_dedup.py b/tests/tools/test_skill_view_dedup.pyindex 4ca7d3f8461..9539f05a9d9 100644--- a/tests/tools/test_skill_view_dedup.py+++ b/tests/tools/test_skill_view_dedup.py@@ -1,6 +1,7 @@"""Tests for skill_view repeat-view dedup (unchanged-skill stub)."""import json+import osimport timeimport pytest@@ -10,6 +11,13 @@ from tools.skills_tool import (reset_skill_view_dedup,)+_SETTLED_NS = time.time_ns() - 3600 * 1_000_000_000+++def _pin_mtime(path, ns):+ os.utime(path, ns=(ns, ns))++@pytest.fixturedef skills_home(tmp_path, monkeypatch):home = tmp_path / ".hermes"@@ -125,3 +133,50 @@ class TestSkillViewDedup:repeat = _view("demo-dedup-skill")assert repeat.get("dedup") is Trueassert repeat.get("content_returned") is False+++class TestSkillViewDedupRaces:+ """A repeat view must never claim 'unchanged' for content the model was not served."""++ def _md(self, skills_home):+ return skills_home / "skills" / "demo-dedup-skill" / "SKILL.md"++ def test_write_while_serving_is_not_deduped(self, skills_home, monkeypatch):+ import tools.skills_tool as st++ md = self._md(skills_home)+ real = st._log_security_warnings++ def write_after_read(*args, **kwargs):+ # A background-review skill_manage patch lands after skill_view read v1.+ md.write_text(md.read_text(encoding="utf-8").replace("Step one", "Step NEW!"), encoding="utf-8")+ return real(*args, **kwargs)++ monkeypatch.setattr(st, "_log_security_warnings", write_after_read)+ first = _view("demo-dedup-skill")+ assert "Step one" in first["content"]+ monkeypatch.setattr(st, "_log_security_warnings", real)++ again = _view("demo-dedup-skill")+ assert again.get("dedup") is None+ assert "Step NEW!" in again.get("content", "")++ def test_same_size_rewrite_with_pinned_mtime_is_not_deduped(self, skills_home):+ md = self._md(skills_home)+ _view("demo-dedup-skill")+ md.write_text(md.read_text(encoding="utf-8").replace("Step one", "Step 111"), encoding="utf-8")+ _pin_mtime(md, _SETTLED_NS)++ again = _view("demo-dedup-skill")+ assert again.get("dedup") is None+ assert "Step 111" in again.get("content", "")++ def test_freshly_written_unchanged_file_is_deduped_by_content(self, skills_home):+ md = self._md(skills_home)+ # Content, not timestamps, decides: a file written this instant (any clock skew between+ # this host and the filesystem included) is still "unchanged" when its bytes are.+ md.write_text(md.read_text(encoding="utf-8"), encoding="utf-8")+ _view("demo-dedup-skill")++ again = _view("demo-dedup-skill")+ assert again.get("dedup") is Truediff --git a/tools/skills_tool.py b/tools/skills_tool.pyindex 58eda3fd6e2..e10531aa4f1 100644--- a/tools/skills_tool.py+++ b/tools/skills_tool.py@@ -25,8 +25,7 @@ from tools.skills_tool_plugin import (MAX_DESCRIPTION_LENGTH, MAX_NAME_LENGTH, _INJECTION_PATTERNS, _fail, _json,_mark_background_review_read, _preprocess_skill, _read_skill_text, _safe_frontmatter,_serve_plugin_skill, _serve_skill_file, _truncate_description)-from tools.skills_tool_dedup import (- _check_skill_view_dedup, _record_skill_view, reset_skill_view_dedup)+from tools.skills_tool_dedup import dedup_skill_view, reset_skill_view_dedupfrom tools.skill_provenance import is_background_reviewlogger = logging.getLogger(__name__)@@ -428,7 +427,7 @@ def _skill_linked_files(skill_dir: Optional[Path]) -> dict:def _skill_readiness(frontmatter: dict[str, Any], skill_name: str) -> tuple[dict, dict]:"""Resolve required env vars / credential files (prompting for secrets where the surfaceallows) and register what's available for sandboxes. Returns ``(fields, extras)``: fields go- before ``_source_path`` in the skill_view result, extras after — key order is tool output."""+ before the readiness extras in the skill_view result — key order is tool output."""required_env_vars = _get_required_environment_variables(frontmatter)from tools.terminal_scope import terminal_envbackend = str(terminal_env("TERMINAL_ENV", "local")).strip().lower() or "local"@@ -660,8 +659,6 @@ def skill_view("linked_files": linked_files if linked_files else None,"usage_hint": "To view linked files, call skill_view(name, file_path) where file_path is e.g. 'references/api.md' or 'assets/config.yaml'" if linked_files else None,**readiness,- # Internal: absolute source path for the repeat-view dedup fingerprint.- "_source_path": str(skill_md),**readiness_extras}if deps_note:result["deps_note"] = deps_note@@ -717,8 +714,8 @@ registry.register(def _skill_view_with_bump(args, **kw):"""Invoke skill_view, then bump view_count/use on success (best-effort). Repeat-view dedup- mirrors read_file's unchanged-stub: a SAME, unchanged skill file already loaded in this- session returns a short stub (cache cleared on context compression)."""+ mirrors read_file's unchanged-stub: a result byte-identical to one already served for the+ same skill file in this session returns a short stub (cache cleared on context compression)."""name = args.get("name", "")task_id = kw.get("task_id")# The background-review fork shares the parent's task_id (prefix-cache parity). A stub there@@ -726,13 +723,12 @@ def _skill_view_with_bump(args, **kw):# possibly-pruned transcript copy (#95976). No dedup in the fork; None also keeps its views# out of the parent's bucket.dedup_task_id = None if is_background_review() else task_id- if (stub := _check_skill_view_dedup(dedup_task_id, name, args.get("file_path"))) is not None:- return stubresult = skill_view(name, file_path=args.get("file_path"), task_id=task_id)with suppress(Exception):parsed = json.loads(result)if isinstance(parsed, dict) and parsed.get("success"):- _record_skill_view(dedup_task_id, name, args.get("file_path"), parsed)+ if (stub := dedup_skill_view(dedup_task_id, name, args.get("file_path"), parsed, result)) is not None:+ return stubif resolved := parsed.get("name") or name: # qualified forms return the canonical namefrom tools.skill_usage import bump_use, bump_viewbump_view(str(resolved))diff --git a/tools/skills_tool_dedup.py b/tools/skills_tool_dedup.pyindex de50354d266..ba61970bbec 100644--- a/tools/skills_tool_dedup.py+++ b/tools/skills_tool_dedup.py@@ -1,16 +1,17 @@-"""skill_view repeat-view dedup registry: per-task cache of (skill name, file_path) ->-(skill file mtime+size). A repeat view of an UNCHANGED file returns a short stub — the earlier-tool result already carries the content verbatim. Cleared via ``reset_skill_view_dedup()`` on+"""skill_view repeat-view dedup registry: per-task cache of (resolved skill name, file_path) ->+digest of the skill_view result served. A repeat view whose result is byte-identical returns a short+stub — the earlier tool result already carries the content verbatim. Content digests need no file+timestamps, so a same-size rewrite in one coarse mtime tick (or on a host whose clock disagrees with+the filesystem's) is never mistaken for "unchanged". Cleared via ``reset_skill_view_dedup()`` oncontext compression AND on a committed proactive tool-result prune, because both replace theoriginal content with a one-line marker."""+import hashlibimport json-import osimport threading-from typing import Dict-_skill_view_tracker: dict[str, dict[tuple, tuple]] = {}+_skill_view_tracker: dict[str, dict[tuple, str]] = {}_skill_view_tracker_lock = threading.Lock()_SKILL_VIEW_DEDUP_CAP = 200@@ -21,63 +22,28 @@ _SKILL_VIEW_DEDUP_MESSAGE = ("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."""- if not (src := payload.get("_source_path")):- 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."""+def dedup_skill_view(task_id, name, file_path, payload: dict, result: str) -> str | None:+ """The "unchanged" stub when this task was already served exactly ``result`` for this skill+ file; otherwise record ``result``'s digest and return None (serve the full result)."""# Never dedup setup-needed views: readiness depends on config/env state that# changes without the file changing; the model must see the refreshed status.if (not task_id or payload.get("setup_needed")or payload.get("readiness_status") == "setup_needed"):- return- if (fp := _skill_view_fingerprint(payload)) 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: # FIFO eviction- del cache[next(iter(cache))]---def _check_skill_view_dedup(task_id, name, file_path) -> str | None:- """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- n = str(name)+ resolved = str(payload.get("name") or name)+ key = (resolved, file_path or "")+ digest = hashlib.sha256(result.encode("utf-8")).hexdigest()with _skill_view_tracker_lock:- if not (cache := _skill_view_tracker.get(str(task_id))):- return None- # Record key is the RESOLVED name; match raw 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 "") or (- rec_name != n and not n.endswith("/" + rec_name)- and not rec_name.endswith("/" + n) and n.split(":")[-1] != rec_name):- continue- try:- st = os.stat(src)- changed = (st.st_mtime_ns, st.st_size) != (mtime_ns, size)- except OSError:- changed = True- if changed:- cache.pop(key, None)- return None+ cache = _skill_view_tracker.setdefault(str(task_id), {})+ if cache.get(key) == digest:return json.dumps({- "success": True, "status": "unchanged", "name": rec_name,+ "success": True, "status": "unchanged", "name": resolved,"file": file_path or "SKILL.md", "dedup": True, "content_returned": False,"message": _SKILL_VIEW_DEDUP_MESSAGE}, ensure_ascii=False)+ cache.pop(key, None) # re-insert at the end: FIFO eviction keeps the recently served+ cache[key] = digest+ while len(cache) > _SKILL_VIEW_DEDUP_CAP: # FIFO eviction+ del cache[next(iter(cache))]return Nonediff --git a/tools/skills_tool_plugin.py b/tools/skills_tool_plugin.pyindex 08fb2856772..e548614f2b9 100644--- a/tools/skills_tool_plugin.py+++ b/tools/skills_tool_plugin.py@@ -97,9 +97,9 @@ def _serve_skill_file(return _fail(f"Failed to read '{file_path}': {exc}")if mark_read:_mark_background_review_read(target)- return _json({ # _source_path: internal, feeds the repeat-view dedup fingerprint+ return _json({"success": True, "name": label, "file": file_path, "content": content,- "file_type": target.suffix, "_source_path": str(target)})+ "file_type": target.suffix})def _mark_background_review_read(path: Path) -> None:@@ -158,7 +158,7 @@ def _serve_plugin_skill("description": _truncate_description(str(parsed_frontmatter.get("description", ""))),"linked_files": _plugin_skill_linked_files(skill_md.parent),"readiness_status": SkillReadinessStatus.AVAILABLE.value,- "skill_dir": str(skill_md.parent), "_source_path": str(skill_md)})+ "skill_dir": str(skill_md.parent)})def _plugin_skill_linked_files(skill_root: Path) -> dict[str, list[str]] | None: