diff --git a/agent/review_engine.py b/agent/review_engine.py index aceaf0b5ed..6d5e8cd62d 100644 --- a/agent/review_engine.py +++ b/agent/review_engine.py @@ -25,6 +25,7 @@ from __future__ import annotations import json import logging +import re from typing import Any, Dict, List, Optional logger = logging.getLogger(__name__) @@ -89,9 +90,64 @@ def snapshot_recent_messages( return out +def collect_parent_loaded_skills( + parent_agent, + messages: List[Dict[str, Any]], + limit: int = 8, +) -> List[str]: + """Names of skills the parent agent was operating under. + + Two sources, both surface-independent: + + * Launch-preloaded skills (``hermes -s``, kanban lanes, TUI skills env): + their activation notes are embedded in the parent's + ``ephemeral_system_prompt`` with a stable marker + (see ``agent.skill_commands.build_preloaded_skills_prompt``). + * Mid-session loads: ``skill_view`` tool calls in the parent's + conversation history (assistant ``tool_calls`` entries). + + Order: preloaded first, then history loads, deduped, capped at ``limit`` + (a reviewer told to load 30 skills would burn its budget before working). + """ + names: List[str] = [] + seen: set = set() + + def _add(name: str) -> None: + cleaned = (name or "").strip() + if cleaned and cleaned not in seen: + seen.add(cleaned) + names.append(cleaned) + + prompt = str(getattr(parent_agent, "ephemeral_system_prompt", "") or "") + for match in re.finditer(r'with the "([^"]+)" skill\s+preloaded', prompt): + _add(match.group(1)) + + for message in messages or []: + if not isinstance(message, dict) or message.get("role") != "assistant": + continue + for tool_call in message.get("tool_calls") or []: + if not isinstance(tool_call, dict): + continue + fn = tool_call.get("function") or {} + if fn.get("name") != "skill_view": + continue + try: + args = json.loads(fn.get("arguments") or "{}") + except Exception: + continue + # Only whole-skill loads seed the reviewer; a reference-file read + # (file_path=...) is a detail of the parent's task, and the + # reviewer loading the main SKILL.md covers it. + if isinstance(args, dict) and not args.get("file_path"): + _add(str(args.get("name") or "")) + + return names[:limit] + + def build_review_task( snapshot: List[Dict[str, str]], user_prompt: str = "", + loaded_skills: Optional[List[str]] = None, ) -> tuple: """Compose the reviewer subagent's (goal, context) pair.""" goal = ( @@ -121,6 +177,16 @@ def build_review_task( lines.append(message["text"]) lines.append("") lines.append("--- End of conversation excerpt ---") + if loaded_skills: + skill_list = ", ".join(loaded_skills) + lines.append("") + lines.append( + "The primary agent was operating under these loaded skills: " + f"{skill_list}. Before reviewing, load each with " + "skill_view(name=...) and treat their conventions, invariants, " + "and review standards as binding for your assessment — the work " + "was produced under them and must be judged against them." + ) if user_prompt.strip(): lines.append("") lines.append("Additional review instructions from the user:") @@ -189,7 +255,8 @@ def start_review( if not snapshot: raise ValueError("Nothing to review yet — the conversation is empty.") - goal, context = build_review_task(snapshot, user_prompt) + loaded_skills = collect_parent_loaded_skills(parent_agent, messages) + goal, context = build_review_task(snapshot, user_prompt, loaded_skills) credentials_cfg = _load_review_credentials_cfg() from tools.delegate_tool import delegate_task diff --git a/tests/agent/test_review_engine.py b/tests/agent/test_review_engine.py index 98c5c2510e..cfe873072d 100644 --- a/tests/agent/test_review_engine.py +++ b/tests/agent/test_review_engine.py @@ -268,6 +268,120 @@ def test_start_review_requires_agent(): start_review(None, [{"role": "user", "content": "x"}], "") +# --------------------------------------------------------------------------- +# collect_parent_loaded_skills — reviewer inherits the parent's working skills +# --------------------------------------------------------------------------- + +def test_collect_skills_from_preloaded_prompt_and_history(): + from agent.review_engine import collect_parent_loaded_skills + + parent = MagicMock() + parent.ephemeral_system_prompt = ( + '[IMPORTANT: The user launched this CLI session with the ' + '"hermes-agent-dev" skill preloaded. Treat its instructions as ' + 'active guidance for the duration of this session unless the user ' + 'overrides them.]' + ) + msgs = [ + {"role": "assistant", "content": "", "tool_calls": [ + {"function": {"name": "skill_view", + "arguments": '{"name": "github-pr-workflow"}'}}, + # reference-file read of an already-counted skill: skipped + {"function": {"name": "skill_view", + "arguments": '{"name": "hermes-agent-dev", ' + '"file_path": "references/x.md"}'}}, + {"function": {"name": "read_file", + "arguments": '{"path": "/tmp/x"}'}}, + ]}, + # duplicate load coalesces + {"role": "assistant", "content": "", "tool_calls": [ + {"function": {"name": "skill_view", + "arguments": '{"name": "github-pr-workflow"}'}}, + ]}, + ] + names = collect_parent_loaded_skills(parent, msgs) + assert names == ["hermes-agent-dev", "github-pr-workflow"] + + +def test_collect_skills_empty_when_none_loaded(): + from agent.review_engine import collect_parent_loaded_skills + + parent = MagicMock() + parent.ephemeral_system_prompt = None + assert collect_parent_loaded_skills(parent, [ + {"role": "user", "content": "hi"}, + ]) == [] + + +def test_collect_skills_caps_at_limit(): + from agent.review_engine import collect_parent_loaded_skills + + parent = MagicMock() + parent.ephemeral_system_prompt = "" + msgs = [ + {"role": "assistant", "content": "", "tool_calls": [ + {"function": {"name": "skill_view", + "arguments": json.dumps({"name": f"skill-{i}"})}} + ]} + for i in range(15) + ] + assert len(collect_parent_loaded_skills(parent, msgs)) == 8 + + +def test_briefing_includes_loaded_skills_instruction(): + snap = [{"role": "user", "text": "review my PR"}] + _, context = build_review_task(snap, "", ["hermes-agent-dev", "xitter"]) + assert "hermes-agent-dev, xitter" in context + assert "skill_view" in context + assert "binding" in context + + +def test_briefing_omits_skills_block_when_none(): + _, context = build_review_task([{"role": "user", "text": "hi"}], "") + assert "operating under these loaded skills" not in context + + +def test_start_review_threads_loaded_skills_into_context(monkeypatch): + import tools.delegate_tool as dt + + fake_child = MagicMock() + fake_child._delegate_role = "leaf" + creds = { + "model": "m", "provider": None, "base_url": None, "api_key": None, + "api_mode": None, "command": None, "args": None, + } + built = {} + + def fake_build(**kw): + built.update(kw) + return fake_child + + monkeypatch.setattr(dt, "_build_child_agent", fake_build) + monkeypatch.setattr(dt, "_resolve_delegation_credentials", lambda *a, **k: creds) + monkeypatch.setattr( + dt, "_run_single_child", + lambda *a, **k: { + "task_index": 0, "status": "completed", "summary": "ok", + "api_calls": 1, "duration_seconds": 0.1, "model": "m", + "exit_reason": "completed", + }, + ) + monkeypatch.setattr(re_mod, "_load_review_credentials_cfg", lambda: None) + + parent = _fake_parent() + parent.ephemeral_system_prompt = ( + 'session with the "hermes-agent-dev" skill preloaded.' + ) + msgs = [ + {"role": "user", "content": "open a PR"}, + {"role": "assistant", "content": "PR #9 opened"}, + ] + result = start_review(parent, msgs, "") + assert result["status"] == "dispatched" + assert "hermes-agent-dev" in built["context"] + assert "skill_view" in built["context"] + + # --------------------------------------------------------------------------- # Registry sync: `review` must be a first-class slot in every aux-task surface # --------------------------------------------------------------------------- diff --git a/website/docs/user-guide/features/delegation.md b/website/docs/user-guide/features/delegation.md index c4d548683b..ed32b0719b 100644 --- a/website/docs/user-guide/features/delegation.md +++ b/website/docs/user-guide/features/delegation.md @@ -183,7 +183,8 @@ What happens: 1. The last 10 user/assistant messages are snapshotted as the reviewer's starting evidence (tool output and system messages are excluded). 2. A reviewer subagent is dispatched on the same background delegation rail as `delegate_task` — it gets the full normal subagent toolset (terminal, web, files, browser...), so it actually opens the PR, reads the diff, and runs code rather than judging from the excerpt. -3. When it finishes, its full review re-enters the same session as a normal background-subagent completion — your primary agent sees it and can act on it (fix the findings, push follow-ups, reply to you). +3. The reviewer inherits the primary agent's working context: any skills the primary agent had loaded (launch-preloaded or via `skill_view` during the session) are named in its briefing with an instruction to load them and judge the work against their conventions. +4. When it finishes, its full review re-enters the same session as a normal background-subagent completion — your primary agent sees it and can act on it (fix the findings, push follow-ups, reply to you). The canonical flow: your main agent opens a PR, you type `/review`, and a second pair of eyes investigates it while you keep working; the review lands back in the chat addressed to the agent that created the PR. diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/delegation.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/delegation.md index 835d7d2cfb..4ca96ec30c 100644 --- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/delegation.md +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/delegation.md @@ -174,7 +174,8 @@ delegation: 1. 最近 10 条用户/助手消息被快照为评审者的起始证据(工具输出和系统消息被排除)。 2. 评审子智能体在与 `delegate_task` 相同的后台委派通道上派发——它拥有完整的常规子智能体工具集(终端、网络、文件、浏览器等),因此会实际打开 PR、阅读 diff、运行代码,而不是仅凭摘录下判断。 -3. 完成后,完整评审作为常规后台子智能体完成事件重新进入同一会话——你的主智能体可以看到并据此行动(修复问题、推送后续提交、回复你)。 +3. 评审者继承主智能体的工作上下文:主智能体已加载的技能(启动预加载或会话中通过 `skill_view` 加载)会列在其简报中,并指示其加载这些技能、以其约定为标准评判工作。 +4. 完成后,完整评审作为常规后台子智能体完成事件重新进入同一会话——你的主智能体可以看到并据此行动(修复问题、推送后续提交、回复你)。 典型流程:主智能体开了一个 PR,你输入 `/review`,第二双眼睛在你继续工作的同时对其进行调查;评审结果回到聊天中,交给创建该 PR 的智能体。