JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat(tui): add /simplify command for code review and cleanup
ldstyle8291a83631b49
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/help.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/help.tsindex 3ca61748bb..d9fb83a7a9 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/help.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/help.ts@@ -4,7 +4,7 @@ import { makeItem } from "../helpers.js";const COMMAND_GROUPS: Record<string, { name: string; commands: string[] }> = {core: {name: "Core",- commands: ["help", "clear", "exit", "init", "copy", "export"],+ commands: ["help", "clear", "exit", "init", "simplify", "copy", "export"],},session: {name: "Session",diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/simplify.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/simplify.tsnew file mode 100644index 0000000000..40f8919f89--- /dev/null+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/simplify.ts@@ -0,0 +1,94 @@+import { addError, addInfo } from "../helpers.js";+import { CommandKind, type SlashCommand } from "../types.js";++interface SimplifyResponse {+ prompt?: string;+ error?: string;+}++/**+ * Returns a review prompt from the server and forwards it to the agent.+ * Requires code mode (git diff + file editing capability).+ */+export function createSimplifyCommand(): SlashCommand {+ return {+ name: "simplify",+ description:+ "Review changed code for reuse, quality, and efficiency, then fix issues found",+ usage: "/simplify [target]",+ example: "/simplify",+ argGuide: "[optional: file path, module or focus dimension]",+ kind: CommandKind.BUILT_IN,+ takesArgs: true,+ action: async (ctx, args) => {+ if (!ctx.mode.startsWith("code.")) {+ ctx.addItem(+ addError(+ ctx.sessionId,+ ctx.preferredLanguage === "zh"+ ? "/simplify 需要在 code 模式下运行。请先执行 /mode code 切到 code 模式再重试。"+ : "/simplify requires code mode. Run /mode code first, then try again.",+ ),+ );+ return;+ }++ const target = args.trim();++ ctx.setRunningCommand?.("simplify");+ try {+ const payload = await ctx.request<SimplifyResponse>(+ "command.simplify",+ { target },+ 30000,+ );++ if (payload?.error) {+ ctx.addItem(addError(ctx.sessionId, `simplify failed: ${payload.error}`));+ return;+ }++ const prompt = payload?.prompt;+ if (!prompt || !prompt.trim()) {+ ctx.addItem(addError(ctx.sessionId, "simplify failed: empty prompt from server"));+ return;+ }++ const requestId = ctx.sendMessage(prompt, undefined, ctx.mode, {+ logAsUser: false,+ });+ if (!requestId) {+ ctx.addItem(+ addInfo(+ ctx.sessionId,+ ctx.preferredLanguage === "zh"+ ? "当前离线,/simplify 请求未发送;网络恢复后请重试。"+ : "Offline; /simplify request not sent. Please retry after reconnecting.",+ "p",+ ),+ );+ return;+ }++ ctx.addItem(+ addInfo(+ ctx.sessionId,+ ctx.preferredLanguage === "zh"+ ? target+ ? `正在启动代码精简审查(关注:${target})…`+ : "正在启动代码精简审查…"+ : target+ ? `Starting code simplify review (focus: ${target})…`+ : "Starting code simplify review…",+ "i",+ ),+ );+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ ctx.addItem(addError(ctx.sessionId, `simplify failed: ${message}`));+ } finally {+ ctx.setRunningCommand?.(null);+ }+ },+ };+}diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.tsindex 124c0616ab..0cf6c984c3 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts@@ -35,6 +35,7 @@ import { createRenameCommand } from "./builtins/rename.js";import { createRewindCommand } from "./builtins/rewind.js";import { createSandboxCommand } from "./builtins/sandbox.js";import { createSessionCommand } from "./builtins/session.js";+import { createSimplifyCommand } from "./builtins/simplify.js";import { createStatusCommand } from "./builtins/status.js";import { createStatusLineCommand } from "./builtins/statusline.js";import { createSkillsCommand } from "./builtins/skills.js";@@ -79,6 +80,7 @@ export function createBuiltinCommands(): SlashCommand[] {createRewindCommand(),createSandboxCommand(),createSessionCommand(),+ createSimplifyCommand(),createSkillsCommand(),createStatusCommand(),createStatusLineCommand(),diff --git a/jiuwenswarm/common/schema/message.py b/jiuwenswarm/common/schema/message.pyindex 0c284fb6fc..03233a42e9 100644--- a/jiuwenswarm/common/schema/message.py+++ b/jiuwenswarm/common/schema/message.py@@ -23,6 +23,7 @@ class ReqMethod(Enum):COMMAND_CONTEXT = "command.context"COMMAND_RECAP = "command.recap"COMMAND_DIFF = "command.diff"+ COMMAND_SIMPLIFY = "command.simplify"COMMAND_MCP = "command.mcp"COMMAND_MODEL = "command.model"COMMAND_RESUME = "command.resume"diff --git a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.pyindex a420902b2f..28930dc22f 100644--- a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py+++ b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py@@ -172,6 +172,7 @@ CLI_FORWARD_REQ_METHODS = frozenset("command.context","command.recap","command.diff",+ "command.simplify","command.mcp","command.resume","command.sandbox",@@ -272,6 +273,7 @@ CLI_FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset("command.context","command.recap","command.diff",+ "command.simplify","command.mcp","command.resume","command.sandbox",diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex 94f8c9164c..20db7aca79 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -130,6 +130,80 @@ def _request_query_text(request: AgentRequest) -> str:return ""return query.strip()++# /simplify prompt template — adapted /simplify skill for jiuwenswarm.+# Guides the agent through three phases: identify changes → three-dimension review+# (reuse/quality/efficiency) → aggregate and fix.+# Note: jiuwenswarm's sub-agents (task_tool / Agent tool) can only be dispatched to registered+# types (explore/plan/code, etc.) and cannot create custom reviewer roles on the fly. The prompt+# therefore presents parallel sub-agent review as an optional optimization — the agent may also+# perform all three reviews itself directly.+_SIMPLIFY_PROMPT_TEMPLATE = """\+# Simplify: Code Review and Cleanup++Review all changed files for reuse, quality, and efficiency. Fix any issues found.++## Phase 1: Identify Changes++Run `git diff` (or `git diff HEAD` if there are staged changes) to see what changed. If there are no git changes, review the most recently modified files that the user mentioned or that you edited earlier in this conversation.++## Phase 2: Launch Three Review Agents in Parallel++If sub-agent tools are available (e.g. task_tool / Agent tool), launch all three agents concurrently in a single message. Pass each agent the full diff so it has the complete context. Otherwise, perform all three reviews yourself directly.++### Agent 1: Code Reuse Review++For each change:++1. **Search for existing utilities and helpers** that could replace newly written code. Look for similar patterns elsewhere in the codebase — common locations are utility directories, shared modules, and files adjacent to the changed ones.+2. **Flag any new function that duplicates existing functionality.** Suggest the existing function to use instead.+3. **Flag any inline logic that could use an existing utility** — hand-rolled string manipulation, manual path handling, custom environment checks, ad-hoc type guards, and similar patterns are common candidates.++### Agent 2: Code Quality Review++Review the same changes for hacky patterns:++1. **Redundant state**: state that duplicates existing state, cached values that could be derived, observers/effects that could be direct calls+2. **Parameter sprawl**: adding new parameters to a function instead of generalizing or restructuring existing ones+3. **Copy-paste with slight variation**: near-duplicate code blocks that should be unified with a shared abstraction+4. **Leaky abstractions**: exposing internal details that should be encapsulated, or breaking existing abstraction boundaries+5. **Stringly-typed code**: using raw strings where constants, enums (string unions), or branded types already exist in the codebase+6. **Unnecessary JSX nesting**: wrapper Boxes/elements that add no layout value — check if inner component props (flexShrink, alignItems, etc.) already provide the needed behavior+7. **Unnecessary comments**: comments explaining WHAT the code does (well-named identifiers already do that), narrating the change, or referencing the task/caller — delete; keep only non-obvious WHY (hidden constraints, subtle invariants, workarounds)++### Agent 3: Efficiency Review++Review the same changes for efficiency:++1. **Unnecessary work**: redundant computations, repeated file reads, duplicate network/API calls, N+1 patterns+2. **Missed concurrency**: independent operations run sequentially when they could run in parallel+3. **Hot-path bloat**: new blocking work added to startup or per-request/per-render hot paths+4. **Recurring no-op updates**: state/store updates inside polling loops, intervals, or event handlers that fire unconditionally — add a change-detection guard so downstream consumers aren't notified when nothing changed. Also: if a wrapper function takes an updater/reducer callback, verify it honors same-reference returns (or whatever the "no change" signal is) — otherwise callers' early-return no-ops are silently defeated+5. **Unnecessary existence checks**: pre-checking file/resource existence before operating (TOCTOU anti-pattern) — operate directly and handle the error+6. **Memory**: unbounded data structures, missing cleanup, event listener leaks+7. **Overly broad operations**: reading entire files when only a portion is needed, loading all items when filtering for one++## Phase 3: Fix Issues++Wait for all reviewers to complete. Aggregate their findings and fix each issue directly. If a finding is a false positive or not worth addressing, note it and move on — do not argue with the finding, just skip it.++When done, briefly summarize what was fixed (or confirm the code was already clean).+"""+++def _build_simplify_prompt(target: str = "") -> str:+ """Build the prompt for the /simplify command.++ Args:+ target: Optional additional focus (e.g. file path, module name, specific dimension+ to emphasize), appended to the end of the prompt.+ """+ prompt = _SIMPLIFY_PROMPT_TEMPLATE+ if target:+ prompt += f"\n\n## Additional Focus\n\n{target}"+ return prompt++# System prompt for LLM-based agent generation_AGENT_CREATION_SYSTEM_PROMPT = """\You are an elite AI agent architect. When given an agent name and description, your job is to design a high-performance agent that EXECUTES tasks to completion — not just analyzes and reports.@@ -982,6 +1056,9 @@ class AgentWebSocketServer:if request.req_method == ReqMethod.COMMAND_DIFF:await self._handle_command_diff(ws, request, send_lock)return+ if request.req_method == ReqMethod.COMMAND_SIMPLIFY:+ await self._handle_command_simplify(ws, request, send_lock)+ returnif request.req_method == ReqMethod.COMMAND_MODEL:await self._handle_command_model(ws, request, send_lock)return@@ -2864,6 +2941,38 @@ class AgentWebSocketServer:async with send_lock:await ws.send(json.dumps(wire, ensure_ascii=False))+ async def _handle_command_simplify(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:+ """处理 /simplify 命令:组装代码精简审查 prompt 并返回(由前端作为消息发送给 Agent)。++ prompt 指导 Agent 分三阶段完成+ 1) 识别改动(git diff)+ 2) 三维度审查(复用 / 质量 / 效率)—— 子 Agent 并行审查为可选优化手段+ 3) 聚合发现并直接修复+ """+ try:+ params = request.params or {}+ target = str(params.get("target", "")).strip()++ prompt = _build_simplify_prompt(target)++ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload={"prompt": prompt},+ )+ except Exception as e: # noqa: BLE001+ logger.exception("[AgentWebSocketServer] command.simplify failed: %s", e)+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=False,+ payload={"error": str(e)},+ )+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)+ async with send_lock:+ await ws.send(json.dumps(wire, ensure_ascii=False))+async def _handle_command_model(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:try:params = request.params or {}diff --git a/tests/unit_tests/agentserver/test_agentserver_cli_commands.py b/tests/unit_tests/agentserver/test_agentserver_cli_commands.pyindex e501ac06ec..1924d4e2e9 100644--- a/tests/unit_tests/agentserver/test_agentserver_cli_commands.py+++ b/tests/unit_tests/agentserver/test_agentserver_cli_commands.py@@ -26,6 +26,9 @@ class AgentWebSocketServerHarness(agent_ws_server_module.AgentWebSocketServer):async def handle_command_diff_for_test(self, ws, request, send_lock):await self._handle_command_diff(ws, request, send_lock)+ async def handle_command_simplify_for_test(self, ws, request, send_lock):+ await self._handle_command_simplify(ws, request, send_lock)+async def handle_command_model_for_test(self, ws, request, send_lock):await self._handle_command_model(ws, request, send_lock)@@ -237,6 +240,57 @@ async def test_handle_command_diff_returns_summary_payload(server, fake_ws):]+async def test_handle_command_simplify_returns_prompt(server, fake_ws):+ """ /simplify 无 target 时返回包含三阶段审查结构的 prompt。"""+ request = AgentRequest(+ request_id="req-simplify",+ channel_id="tui",+ req_method=ReqMethod.COMMAND_SIMPLIFY,+ params={},+ )++ await server.handle_command_simplify_for_test(fake_ws, request, asyncio.Lock())++ assert len(fake_ws.sent) == 1+ msg = fake_ws.sent[0]+ assert msg["response_id"] == "req-simplify"+ assert msg["ok"] is True+ prompt = msg["payload"]["prompt"]+ # prompt should contain three-phase structure keywords (English)+ assert "Phase 1" in prompt+ assert "Phase 2" in prompt+ assert "Phase 3" in prompt+ # All three review dimensions should be present+ assert "Code Reuse Review" in prompt+ assert "Code Quality Review" in prompt+ assert "Efficiency Review" in prompt+ # Parallel sub-agent review should be optional, not mandatory+ assert "task_tool" in prompt or "Agent tool" in prompt+ assert "perform all three reviews yourself directly" in prompt+ # No Additional Focus section when no target is given+ assert "Additional Focus" not in prompt+++async def test_handle_command_simplify_with_target_appends_focus(server, fake_ws):+ """/simplify 带 target 时将关注点追加到 prompt 末尾。"""+ request = AgentRequest(+ request_id="req-simplify-target",+ channel_id="tui",+ req_method=ReqMethod.COMMAND_SIMPLIFY,+ params={"target": "src/auth/ 模块的错误处理"},+ )++ await server.handle_command_simplify_for_test(fake_ws, request, asyncio.Lock())++ msg = fake_ws.sent[0]+ assert msg["ok"] is True+ prompt = msg["payload"]["prompt"]+ assert "Additional Focus" in prompt+ assert "src/auth/ 模块的错误处理" in prompt++@pytest.mark.asyncioasync def test_handle_command_model_no_action_shows_current(server, fake_ws, monkeypatch