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(evolution): show evolution state in chat input and add teamskill-creator to builtin skills
z2tng8260b157cabd
diff --git a/jiuwenclaw/agentserver/deep_agent/interface_deep.py b/jiuwenclaw/agentserver/deep_agent/interface_deep.pyindex 94bd4affb2..17c7e5ef4a 100644--- a/jiuwenclaw/agentserver/deep_agent/interface_deep.py+++ b/jiuwenclaw/agentserver/deep_agent/interface_deep.py@@ -2864,8 +2864,6 @@ class JiuWenClawDeepAdapter:)elif request_id.startswith("evolve_simplify_"):resolved = await self._handle_governance_approval(request_id, answers, "simplify")- elif request_id.startswith("evolve_rebuild_"):- resolved = await self._handle_governance_approval(request_id, answers, "rebuild")elif request_id.startswith("skill_evolve_"):resolved = await self._handle_evolution_approval(request_id, answers)@@ -3148,113 +3146,6 @@ class JiuWenClawDeepAdapter:return SkillEvolutionRail._parse_messages(raw_messages)- async def _handle_evolve_rewrite_command(self, query: str) -> dict[str, Any]:- """/evolve_rewrite <skill_name> [--min-score <float>] [--dry-run] [<user_query>...]-- Rewrite SKILL.md by deeply integrating evolution experiences using LLM.- Unlike solidify() which appends experiences, this rewrites the document- for a more natural, coherent result.- """- rail = self._skill_evolution_rail- assert rail is not None- store = rail.store-- # Parse arguments- parts = query.split()- usage_msg = (- "请指定 Skill 名称:\n"- "`/evolve_rewrite <skill_name> [--min-score <float>] [--dry-run] [<user_query>...]`"- )- if len(parts) < 2:- return {"output": usage_msg, "result_type": "error"}-- skill_name = parts[1]- if skill_name.startswith("--"):- return {"output": usage_msg, "result_type": "error"}-- if not store.skill_exists(skill_name):- available = "、".join(store.list_skill_names()) or "(无可用 Skill)"- return {- "output": f"未找到 Skill '{skill_name}'。当前可用:{available}",- "result_type": "error",- }-- # Parse flags- min_score = 0.5- dry_run = False- user_query_parts = []-- i = 2- while i < len(parts):- part = parts[i]- if part == "--min-score" and i + 1 < len(parts):- try:- min_score = float(parts[i + 1])- i += 2- continue- except ValueError:- return {- "output": f"--min-score 参数无效:{parts[i + 1]}",- "result_type": "error",- }- elif part == "--dry-run":- dry_run = True- i += 1- continue- else:- # Remaining parts are user_query- user_query_parts = parts[i:]- break- i += 1-- user_query = " ".join(user_query_parts)-- try:- result = await rail.rewrite_skill(- skill_name,- min_score=min_score,- dry_run=dry_run,- user_query=user_query,- )- except Exception as exc:- logger.warning("[JiuWenClaw] evolve_rewrite failed: %s", exc)- return {- "output": f"重写失败:{exc}",- "result_type": "error",- }-- if result is None:- return {- "output": f"Skill '{skill_name}' 没有符合条件的演进经验(当前 min_score={min_score})。",- "result_type": "answer",- }-- if dry_run:- # Preview mode: show summary and content preview- preview_lines = result.rewritten_content.split("\n")[:30]- preview = "\n".join(preview_lines)- if len(result.rewritten_content.split("\n")) > 30:- preview += "\n... (truncated)"-- return {- "output": (- f"**Skill '{skill_name}' 重写预览(dry-run,未执行):**\n\n"- f"{result.summary}\n\n"- f"**重写后内容预览(前30行):**\n```markdown\n{preview}\n```"- ),- "result_type": "answer",- }-- # Applied mode- return {- "output": (- f"**Skill '{skill_name}' 重写完成:**\n\n"- f"{result.summary}\n\n"- f"已清理 {result.records_cleaned} 条已应用的经验记录。"- ),- "result_type": "answer",- }-async def _handle_evolve_list_command(self, query: str) -> dict[str, Any]:"""/evolve_list <skill_name> [--sort score] — show experiences with scores."""rail = self._skill_evolution_rail@@ -3357,7 +3248,7 @@ class JiuWenClawDeepAdapter:}async def _handle_evolve_rebuild_command(self, query: str) -> dict[str, Any]:- """/evolve_rebuild <skill_name> [user_intent] — Rebuild skill body with approval."""+ """/evolve_rebuild <skill_name> [user_intent] — Build followup prompt for rebuild."""rail = self._skill_evolution_railassert rail is not Nonestore = rail.store@@ -3380,22 +3271,22 @@ class JiuWenClawDeepAdapter:}try:- request_id = await rail.request_rebuild(skill_name, user_intent)+ followup_prompt = await rail.request_rebuild(skill_name, user_intent)except Exception as exc:logger.warning("[JiuWenClaw] evolve_rebuild failed: %s", exc)return {"output": f"重建分析失败:{exc}", "result_type": "error"}- if not request_id:+ if not followup_prompt:return {- "output": f"Skill '{skill_name}' 重建生成失败(LLM 未输出有效内容)。",+ "output": f"Skill '{skill_name}' 未生成可执行的重建指令。","result_type": "error",}- approval_chunks = await rail.drain_pending_approval_events()return {- "output": f"Skill '{skill_name}' 重建方案已生成,请在审批弹框中确认。",- "result_type": "answer",- "approval_chunks": approval_chunks,+ "action": "run_rebuild_followup",+ "followup_prompt": followup_prompt,+ "skill_name": skill_name,+ "result_type": "followup",}async def _handle_evolve_rollback_command(self, query: str) -> dict[str, Any]:@@ -3486,13 +3377,13 @@ class JiuWenClawDeepAdapter:async def _handle_governance_approval(self, request_id: str, answers: list, kind: str) -> bool:- """Unified handler for simplify/rebuild governance approvals."""+ """Unified handler for simplify governance approvals."""rail = self._skill_evolution_railif rail is None:logger.warning("[JiuWenClaw] governance approval failed: no SkillEvolutionRail")return False- accept_labels = {"执行", "重建"} if kind in ("simplify", "rebuild") else set()+ accept_labels = {"执行"} if kind == "simplify" else set()accepted = any(isinstance(ans, dict)and bool(accept_labels & set(ans.get("selected_options", [])))@@ -3504,11 +3395,6 @@ class JiuWenClawDeepAdapter:await rail.on_approve_simplify(request_id)else:await rail.on_reject_simplify(request_id)- elif kind == "rebuild":- if accepted:- await rail.on_approve_rebuild(request_id)- else:- await rail.on_reject_rebuild(request_id)logger.info("[JiuWenClaw] governance %s %s: request_id=%s",@@ -3516,6 +3402,19 @@ class JiuWenClawDeepAdapter:)return True+ @staticmethod+ def _extract_rebuild_followup_prompt(slash_result: dict[str, Any] | None) -> str | None:+ """Return followup prompt when slash_result requests rebuild continuation."""+ if not isinstance(slash_result, dict):+ return None+ if slash_result.get("action") != "run_rebuild_followup":+ return None+ prompt = slash_result.get("followup_prompt")+ if not isinstance(prompt, str):+ return None+ prompt = prompt.strip()+ return prompt or None+def _ensure_evolution_rail_for_slash(self, mode: str) -> str | None:"""Check evolution availability for slash commands; lazily init rail if needed.@@ -3551,10 +3450,10 @@ class JiuWenClawDeepAdapter:stripped = query.strip()if stripped.startswith("/evolve_rewrite"):- err = self._ensure_evolution_rail_for_slash(mode)- if err:- return {"output": err, "result_type": "error"}- return await self._handle_evolve_rewrite_command(stripped)+ return {+ "output": "`/evolve_rewrite` 已删除,请使用 `/evolve_rebuild <skill_name> [user_intent]`。",+ "result_type": "error",+ }if stripped.startswith("/evolve_simplify"):err = self._ensure_evolution_rail_for_slash(mode)@@ -3580,7 +3479,7 @@ class JiuWenClawDeepAdapter:return {"output": err, "result_type": "error"}return await self._handle_evolve_list_command(stripped)- if stripped.startswith("/evolve"):+ if stripped == "/evolve" or stripped.startswith("/evolve "):err = self._ensure_evolution_rail_for_slash(mode)if err:return {"output": err, "result_type": "error"}@@ -3676,19 +3575,24 @@ class JiuWenClawDeepAdapter:slash_result = await self._handle_slash_command(query, session_id, mode)if slash_result is not None:- approval_chunks = slash_result.get("approval_chunks")- if approval_chunks:- payload: dict[str, Any] = {"approval_chunks": approval_chunks}+ followup_prompt = self._extract_rebuild_followup_prompt(slash_result)+ if followup_prompt is not None:+ inputs = dict(inputs)+ inputs["query"] = followup_promptelse:- content = slash_result.get("output", str(slash_result))- payload = {"content": content}- return AgentResponse(- request_id=request.request_id,- channel_id=request.channel_id,- ok=slash_result.get("result_type") != "error",- payload=payload,- metadata=request.metadata,- )+ approval_chunks = slash_result.get("approval_chunks")+ if approval_chunks:+ payload: dict[str, Any] = {"approval_chunks": approval_chunks}+ else:+ content = slash_result.get("output", str(slash_result))+ payload = {"content": content}+ return AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=slash_result.get("result_type") != "error",+ payload=payload,+ metadata=request.metadata,+ )cron_context_tokens = self._bind_runtime_cron_context(channel_id=request.channel_id,@@ -3780,30 +3684,35 @@ class JiuWenClawDeepAdapter:# 拦截斜杠命令slash_result = await self._handle_slash_command(query, session_id, mode)if slash_result is not None:- approval_chunks = slash_result.get("approval_chunks", [])- if approval_chunks:- for chunk in approval_chunks:+ followup_prompt = self._extract_rebuild_followup_prompt(slash_result)+ if followup_prompt is not None:+ inputs = dict(inputs)+ inputs["query"] = followup_prompt+ else:+ approval_chunks = slash_result.get("approval_chunks", [])+ if approval_chunks:+ for chunk in approval_chunks:+ yield AgentResponseChunk(+ request_id=request.request_id,+ channel_id=request.channel_id,+ payload=chunk,+ is_complete=False,+ )yield AgentResponseChunk(request_id=request.request_id,channel_id=request.channel_id,- payload=chunk,- is_complete=False,+ payload={"event_type": "chat.done"},+ is_complete=True,)- yield AgentResponseChunk(- request_id=request.request_id,- channel_id=request.channel_id,- payload={"event_type": "chat.done"},- is_complete=True,- )- else:- content = slash_result.get("output", str(slash_result))- yield AgentResponseChunk(- request_id=request.request_id,- channel_id=request.channel_id,- payload={"event_type": "chat.final", "content": content},- is_complete=True,- )- return+ else:+ content = slash_result.get("output", str(slash_result))+ yield AgentResponseChunk(+ request_id=request.request_id,+ channel_id=request.channel_id,+ payload={"event_type": "chat.final", "content": content},+ is_complete=True,+ )+ returnhas_streamed_content = Falseaccumulated_text = ""@@ -4449,29 +4358,40 @@ class JiuWenClawDeepAdapter:"payload": payload,})- timed_out = Falsetry:- await _push_status("start", "collecting", "Running evolution analysis...")+ if self._skill_evolution_rail is None:+ return- if self._skill_evolution_rail is not None:- events = await self._skill_evolution_rail.drain_pending_approval_events(- wait=True, timeout=300+ events = await self._skill_evolution_rail.drain_pending_approval_events(+ wait=True,+ timeout=300,+ )+ outcomes = self._skill_evolution_rail.drain_evolution_outcomes()+ await self._skill_evolution_rail.cleanup_background_tasks()++ approval_events = [evt for evt in events if self._is_approval_event(evt)]+ outcome = outcomes[-1] if outcomes else None+ if not approval_events and outcome is None:+ logger.info(+ "[JiuWenClawDeepAdapter] evolution watcher finished without approval/outcome: "+ "request_id=%s session_id=%s",+ rid,+ session_id,)- await self._skill_evolution_rail.cleanup_background_tasks()- else:- events = []+ return++ await _push_status("start", "collecting", "Running evolution analysis...")- if not events:- timed_out = True+ for evt in approval_events:+ await _push_approval(evt)- for evt in events:- if self._is_approval_event(evt):- await _push_approval(evt)+ if outcome is not None:+ stage = str(outcome.get("status") or "failed")+ message = str(outcome.get("message") or "Evolution analysis failed")+ await _push_status("end", stage, message)+ return- if timed_out:- await _push_status("end", "timed_out", "Evolution analysis timed out")- else:- await _push_status("end", "completed", "Evolution analysis completed")+ await _push_status("end", "completed", "Evolution analysis completed")except Exception as exc:logger.warning("[JiuWenClawDeepAdapter] evolution watcher failed: %s", exc)try:diff --git a/jiuwenclaw/agentserver/deep_agent/team_helpers.py b/jiuwenclaw/agentserver/deep_agent/team_helpers.pyindex 09854a9b59..ce6fc6c506 100644--- a/jiuwenclaw/agentserver/deep_agent/team_helpers.py+++ b/jiuwenclaw/agentserver/deep_agent/team_helpers.py@@ -110,6 +110,45 @@ def _ensure_team_evolution_watcher(tm.register_team_evolution_watcher(session_id, task)+async def _resolve_team_rebuild_followup(+ channel_id: str | None,+ session_id: str,+ query: str,+) -> tuple[str | None, str | None]:+ """Resolve /evolve_rebuild into a followup prompt for the team session."""+ stripped = str(query or "").strip()+ if not stripped.startswith("/evolve_rebuild"):+ return None, None++ tm = get_team_manager(channel_id)+ rail = tm.get_team_skill_rail(session_id)+ if rail is None:+ return None, "团队技能重建不可用:未找到 TeamSkillRail。"++ store = rail.store+ parts = stripped.split(maxsplit=2)+ skill_name = parts[1] if len(parts) > 1 else ""+ user_intent = parts[2] if len(parts) > 2 else None++ if not skill_name:+ return None, "请指定 Skill 名称:`/evolve_rebuild <skill_name> [user_intent]`"++ if not store.skill_exists(skill_name):+ available = "、".join(store.list_skill_names()) or "(无可用 Skill)"+ return None, f"未找到 Skill '{skill_name}'。当前可用:{available}"++ try:+ followup_prompt = await rail.request_rebuild(skill_name, user_intent)+ except Exception as exc:+ logger.warning("[TeamHelpers] evolve_rebuild failed: session_id=%s error=%s", session_id, exc)+ return None, f"团队技能重建分析失败:{exc}"++ if not followup_prompt:+ return None, f"Skill '{skill_name}' 未生成可执行的重建指令。"++ return followup_prompt, None++async def process_team_message_stream(request: Any,inputs: dict[str, Any],@@ -153,6 +192,28 @@ async def process_team_message_stream(is_first_request = not team_manager.has_stream_task(session_id)request_queue: asyncio.Queue | None = None+ followup_prompt, rebuild_error = await _resolve_team_rebuild_followup(+ channel_id,+ session_id,+ str(query or ""),+ )+ if rebuild_error is not None:+ yield AgentResponseChunk(+ request_id=rid,+ channel_id=channel_id,+ payload={"event_type": "chat.error", "error": rebuild_error},+ is_complete=False,+ )+ yield AgentResponseChunk(+ request_id=rid,+ channel_id=channel_id,+ payload=None,+ is_complete=True,+ )+ return+ if followup_prompt is not None:+ query = followup_prompt+try:if is_first_request:request_queue = asyncio.Queue()diff --git a/jiuwenclaw/cli/src/core/commands/builtins/evolve.ts b/jiuwenclaw/cli/src/core/commands/builtins/evolve.tsindex 0490c981bb..f3543ae264 100644--- a/jiuwenclaw/cli/src/core/commands/builtins/evolve.ts+++ b/jiuwenclaw/cli/src/core/commands/builtins/evolve.ts@@ -105,15 +105,15 @@ export function createEvolveSimplifyCommand(): SlashCommand {}/**- * /evolve_rewrite - Rewrite SKILL.md by deeply integrating evolution experiences using LLM- * Usage: /evolve_rewrite <skill_name> [--min-score <float>] [--dry-run] [<user_query>...]+ * /evolve_rebuild - Rebuild SKILL.md via followup execution+ * Usage: /evolve_rebuild <skill_name> [<user_query>...]*/-export function createEvolveRewriteCommand(): SlashCommand {+export function createEvolveRebuildCommand(): SlashCommand {return {- name: "evolve_rewrite",- description: "Rewrite SKILL.md by deeply integrating evolution experiences using LLM",- usage: "/evolve_rewrite <skill_name> [--min-score <float>] [--dry-run] [<user_query>...]",- example: "/evolve_rewrite pptx --min-score 0.7 --dry-run improve error handling",+ name: "evolve_rebuild",+ description: "Rebuild SKILL.md from archived history and evolution records",+ usage: "/evolve_rebuild <skill_name> [<user_query>...]",+ example: "/evolve_rebuild pptx improve error handling",kind: CommandKind.BUILT_IN,takesArgs: true,action: (ctx, args) => {@@ -125,21 +125,19 @@ export function createEvolveRewriteCommand(): SlashCommand {makeItem(ctx.sessionId,"error",- "usage: /evolve_rewrite <skill_name> [--min-score <float>] [--dry-run] [<user_query>...] - Provide the name of the skill",+ "usage: /evolve_rebuild <skill_name> [<user_query>...] - Provide the name of the skill",),);return;}- // Forward all arguments to backend (including flags and user_query)- const requestId = ctx.sendMessage(`/evolve_rewrite ${args.trim()}`);+ const requestId = ctx.sendMessage(`/evolve_rebuild ${args.trim()}`);if (!requestId) {ctx.addItem(- makeItem(ctx.sessionId, "error", "offline: waiting for reconnect before sending evolve_rewrite request"),+ makeItem(ctx.sessionId, "error", "offline: waiting for reconnect before sending evolve_rebuild request"),);}},};}-diff --git a/jiuwenclaw/cli/src/core/commands/registry.ts b/jiuwenclaw/cli/src/core/commands/registry.tsindex adbaec68b3..61d837b91e 100644--- a/jiuwenclaw/cli/src/core/commands/registry.ts+++ b/jiuwenclaw/cli/src/core/commands/registry.ts@@ -9,7 +9,7 @@ import { createDiffCommand } from "./builtins/diff.js";import {createEvolveCommand,createEvolveListCommand,- createEvolveRewriteCommand,+ createEvolveRebuildCommand,createEvolveSimplifyCommand,} from "./builtins/evolve.js";import { createExitCommand } from "./builtins/exit.js";@@ -41,7 +41,7 @@ export function createBuiltinCommands(): SlashCommand[] {createDiffCommand(),createEvolveCommand(),createEvolveListCommand(),- createEvolveRewriteCommand(),+ createEvolveRebuildCommand(),createEvolveSimplifyCommand(),createExitCommand(),createModelCommand(),diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/SKILL.md b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/SKILL.mdnew file mode 100644index 0000000000..63fcc77f92--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/SKILL.md@@ -0,0 +1,314 @@+---+name: teamskill-creator+description: |+ Creates, converts, or modifies Teamskills — the multi-role extension of the Skills standard (specialized roles + workflow + bind constraints).+ Use when the user wants to author a multi-role agent team, convert a single-agent skill into one, or refactor an existing team.+ Do NOT use for single-agent Skills — use create-skill instead.+version: "0.2"+---++# Teamskill Creator++Authoring tool for Teamskills — the multi-role extension of the Anthropic Skills standard. Encodes the Teamskill spec into a repeatable workflow with templates, decision trees, and an automated validator.++## Workflow++This skill has **three modes**. Pick one based on the user's request, then follow the matching pipeline:++| Mode | Trigger | Output |+|---|---|---|+| **CREATE** | User has a fresh need ("build a team for X") | New `<teamskill-name>/` directory with the full 5-file set |+| **CONVERT** | User points at an existing single-agent skill | Transformed `<teamskill-name>/` directory + a delta report explaining what the team adds |+| **MODIFY** | User edits an existing Teamskill (add/remove role, change workflow, adjust bind, fix validator errors) | Updated files in the existing `<teamskill-name>/` directory |++> **All three modes share Stages 2–6**. CONVERT differs only in Stage 1 (decomposition replaces fresh design). MODIFY skips Stage 0 and Stage 1 (justification and pattern are already settled — re-open them only if the change alters the pattern, e.g. adding a parallel role to a pipeline team), touches only the affected stages in 2–5, and **MUST run Stage 6 (validator) — this is the most-skipped, most-critical step in MODIFY mode**. See the [MODIFY impact matrix](#modify-impact-matrix) for which stages to re-run per change type.++### Stage 0: Triage — is a Teamskill even justified?++A Teamskill is **only justified** when at least one of these is true:++1. **Adversarial blind spot** — a single agent role-playing N personas produces converging outputs because it cannot escape its own analytical priors. Examples: PR review, security audit, design critique.+2. **Parallel decomposition gain** — N independent sub-tasks can run concurrently and the integration is non-trivial. Examples: multi-angle research, multi-perspective due diligence.+3. **Specialization pipeline with hard handoffs** — sequential stages with quality gates where blurring stage boundaries causes regressions. Examples: marketing copy (brief → draft → edit → audit), incident response (declare → triage → mitigate → postmortem).++**If none apply → STOP. Recommend a single-agent skill instead.** Teamskills cost more tokens, more wall-clock, and more authoring overhead. Do not build one out of novelty.++Ask the user: *"Which of these failure modes does a single agent hit on this task today?"* If they cannot answer, the Teamskill is premature.++### Stage 1a (CREATE only): Pattern selection++Pick the architectural pattern (A / B / C / mixed) based on Stage 0 justification. The detailed decision tree with worked examples is in [reference/pattern-selection.md](reference/pattern-selection.md). Quick reference:++| Pattern | When | Role count | Roles see each other? |+|---|---|---|---|+| **A. Adversarial / Cross-check** | Justification #1 (blind spot) | 2–4 | No — isolation is the value |+| **B. Parallel decomposition** | Justification #2 (independent sub-tasks) | 2–N (variable) | No until integration |+| **C. Specialization pipeline** | Justification #3 (sequential expert stages) | 3–5 | Each stage sees prior stage output |+| **Mixed (A+B / B+C / C+A)** | Multiple justifications stack | 4–6 | Pattern-by-stage |+| **Debate (Mixed B+A+C)** | #1 + #2 (blind spot + parallel breadth) | 3–N+1 | Phase-scoped: isolated → mutual |++Read [reference/pattern-selection.md](reference/pattern-selection.md) before committing — picking the wrong pattern is the most common authoring error.++### Stage 1b (CONVERT only): Decompose the existing skill++Read the source SKILL.md and identify natural role boundaries. Use this checklist:++1. **Find embedded personas** — does the skill ask one agent to "act as" multiple roles (e.g., "Persona 1: Saboteur / Persona 2: New Hire / Persona 3: Security Auditor")? Each embedded persona is a Teamskill role candidate.+2. **Find sequential stages with quality gates** — does the skill have phases like "first do X, then validate Y, then produce Z"? Each phase is a pipeline stage candidate.+3. **Find checklists that branch by category** — a checklist like "[ ] security [ ] performance [ ] readability" is parallel-decomposition fuel.+4. **Identify what's lost in single-agent form** — the answer becomes the Teamskill's "why" (the Stage 0 justification). If you cannot articulate this, the conversion is not worth it.++Full conversion methodology: [reference/conversion-guide.md](reference/conversion-guide.md).++### Stage 2: Role design (count depends on pattern, no overlap)++Default role counts by pattern (soft heuristics, not hard limits — see [reference/pattern-selection.md](reference/pattern-selection.md) Q4):++- **A. Adversarial / Cross-check**: 2–4 roles+- **B. Parallel decomposition**: 2–N roles (use `count: [min, max]` for elastic fan-out)+- **C. Specialization pipeline**: 3–5 stages+- **Mixed (A+B / A+C)**: 4–6 roles total++If you need more, prefer splitting into multiple sequential Teamskills over one mega-team.++For each role, write 5 mandatory sections:++1. `## Identity` — **first line MUST be a 1-line motto** that crystallizes the POV (e.g., *"I am trying to break this code in production."*). This is the #1 anti-convergence mechanism. 0–2 paragraphs of context after.+2. `## Success Criteria` — bullet list + a "Focus areas" line.+3. `## Boundary` — explicit `**Forbidden**:` (prevent role overlap) + `**Mandatory**:` (prevent laziness).+4. `## Output Schema` — Markdown or JSON template.+5. `## Inline Persona for Teammate` — full pasteable prompt (most adopting agents do NOT auto-load role files; the Leader must inline this into the dispatch prompt).++Detailed authoring guide with examples: [reference/role-design.md](reference/role-design.md).++**Anti-overlap test**: write each role's 1-line motto, then ask *"could one role's deliverable substitute for another's?"* If yes, the boundaries are blurred — redesign before proceeding.++**Output**: write each role as `roles/<id>.md` using [templates/role.md.template](templates/role.md.template) as the starting skeleton. Delete the `<!-- TEMPLATE NOTES -->` block before finalizing.++**Auto-matching: assign locally available skills and tools**++After all role files are written, automatically match each role with locally available skills and tools. This is a **silent sub-step** — no user interaction needed (already-installed skills have zero adoption cost).++1. **Scan local skills** — use whatever mechanism the host framework provides. Common approaches (non-exhaustive):+ - **System prompt / context injection**: many frameworks inject an `available_skills` list at startup — this is the most reliable source.+ - **Workspace-level convention scan**: glob for `**/SKILL.md` under known skill directories.+ - **CLI query**: if the framework provides a skill listing command (e.g., `npx skills list -g`), use it.+ - **Do NOT hardcode paths for a specific framework** — the Teamskill spec is framework-agnostic.+2. **Scan local tools** — probe CLI tools available in the current environment (e.g., `gh`, `python`, `rg`, `jq`, `curl`, `docker`). Use `where` (Windows) or `which` (Unix).+3. **Match and assign** — for each role, read its `purpose`, `Success Criteria`, and `Boundary`. Evaluate whether any discovered skill/tool would materially help fulfil the role's purpose (a match = removing it would force the role into a significantly weaker operating mode). Assign matches to the correct field with `source: local` in `dependencies.yaml`.++ **Classification rule — do NOT mix skills and tools:**+ - `roles[].skills` → **Skills only**: items that have a `SKILL.md` (agent skills providing instructions/workflows). Examples: `web-research`, `code-review`, `canvas-design`.+ - `roles[].tools` → **Tools only**: CLI executables, MCP servers, or shell commands. Examples: `gh`, `python`, `rg`, `docker`, `curl`.+ - A CLI binary is NEVER a skill. A SKILL.md-based capability is NEVER a tool. If unsure, check: does it have a `SKILL.md`? → skill. Is it invoked via shell/MCP? → tool.++### Stage 3: Write `workflow.md` (mermaid + steps + gates)++Author `workflow.md` using [templates/workflow.md.template](templates/workflow.md.template) as the starting skeleton. Three mandatory sections:++1. `## Overview` — **mermaid `graph LR/TD`** showing Leader entry, parallel/sequential teammate nodes, decision diamonds (degraded mode branches), integration node, output node. Mermaid is the primary expression difference vs single-agent skills. **Debate pattern**: MUST keep the **inter-member communication preference** note from the template — do NOT delete it when replacing the mermaid placeholder.+2. `## Detailed Steps` — numbered steps; each step contains: executor / input / output / serial-or-parallel / **quality gate** (what to do if this step's output fails). The last step contains the final report format template.+3. `## Acceptance Criteria` — judgement of a successful single run.++Quality gates are the contract surface between stages — design them per [reference/role-design.md](reference/role-design.md) § Gate Design.++### Stage 4: Write `bind.md` (numbers + behavior + failure)++Author `bind.md` using [templates/bind.md.template](templates/bind.md.template) as the starting skeleton. Three mandatory sections:++1. `## Resource Constraints` — table with at least: `max_parallel_teammates`, `total_wall_clock_budget`, `total_token_budget`. Add per-role limits if asymmetric.+2. `## Behavioral Constraints` — **team-level** rules (Leader does not write content / teammates cannot see each other's output / Leader does not resolve contradictions / etc.). Distinct from per-role `Boundary`. **Debate pattern MUST include**: phase-scoped visibility rules (which rounds are isolated, which are mutually visible) AND the inter-member communication preference order (direct peer-to-peer > shared blackboard > Leader-relay).+3. `## Failure Handling` — must cover **(a)** teammate failure (timeout, malformed output, retry policy, how missing outputs appear in the report) and **(b)** input-overscale degradation (e.g., diff > 2000 LOC → degrade to single-role mode).++Heuristic: if a constraint has a number or an exception path, it belongs in `bind.md`. If it's the main flow, it belongs in `workflow.md`.++### Stage 5: Write `dependencies.yaml` + `SKILL.md`++The remaining two files. Write them last because they reference content produced in Stages 2–4.++**5a. `dependencies.yaml`** — use [templates/dependencies.yaml.template](templates/dependencies.yaml.template). This file codifies the **auto-matching results from Stage 2**, not a blank-slate design. Both `skills:` and `tools:` segments are mandatory — write `[]` if empty, but only after the auto-matching scan confirms no matches (signals "checked, confirmed none" — different from "never looked"). Each `roles[].skills` and `roles[].tools` declared in SKILL.md frontmatter MUST appear here (the validator enforces this).++**5b. `SKILL.md`** — use [templates/SKILL.md.template](templates/SKILL.md.template). This is the entry point that ties together all other files. Body MUST contain `## Workflow` + `## Roles` + `## Files`.++**Naming rules** (enforced by the validator):+- Directory name = `name` field in SKILL.md frontmatter (kebab-case, ends with `-team` by convention).+- Each `roles/<id>.md` filename MUST equal the corresponding `roles[].id` in SKILL.md frontmatter.+- All 5 files are mandatory (the validator fails on any missing file).++**Description discipline** (enforced by the validator — these are the most-violated rules):+- ≤ 4 lines, ≤ 500 chars total.+- 3-line structure only: WHAT / WHEN / NOT. Do NOT add a separate `Triggers:` line.+- NO synonym enumeration — modern semantic match handles all variants from one natural sentence.+- NO numeric scope thresholds (e.g. `">200 LOC"`) → those belong in `bind.md`.+- NO Stage 0 justification rationale → that belongs in the body's intro paragraph.+- Per-role `purpose:` field has a ≤150 char HARD CAP. Detail belongs in `roles/<id>.md`, not in SKILL.md frontmatter.++**Calibration benchmark**: aim for **≤ 500 chars** (platform hard cap: 1024). Teamskills are inherently more complex than single-agent skills — multi-role composition, workflow scope, and trigger scenarios may need more words. Stay concise, but don't sacrifice clarity for arbitrary brevity.++### Stage 6: Validate++Run the automated validator:++```bash+python scripts/validate_teamskill.py path/to/<teamskill-name>/+```++The validator checks:+- **Structural**: 5 files present, role file names match `roles[].id`, no orphan role files+- **Frontmatter**: `name` / `description` / `version` / `kind: team-skill` / `roles[]` present; each role has `id` + `purpose`; `name` == directory name+- **Section presence**: SKILL.md body has `## Workflow` / `## Roles` / `## Files`; each `roles/*.md` has all 5 mandatory sections; `workflow.md` has `## Overview` / `## Detailed Steps` / `## Acceptance Criteria` (and at least one mermaid block); `bind.md` has all 3 mandatory sections+- **Cross-file consistency**: every `roles[].skills` and `roles[].tools` in SKILL.md appears in `dependencies.yaml`; every `## Identity` in roles starts with a `> *"..."*` motto line+- **Output discipline**: `## Inline Persona for Teammate` present in each role file; `dependencies.yaml` skills/tools segments present even if empty++**Exit code 0 = compliant**. Non-zero exit prints the failing checks with file:line references.++The manual checklist (for design-time judgment calls the script cannot automate, like "is this content really redundant?") lives in [reference/compliance-checklist.md](reference/compliance-checklist.md). Read it before declaring the Teamskill done.++### Post-generation: Creation Summary + Community Enrichment++After Stage 6 passes, present a **creation summary** to the user. This is the natural point to assess capability coverage and offer community enrichment — the Teamskill is already complete and functional, so community search is a zero-risk enhancement.++**Summary format:**++```+Teamskill: <name>+Pattern: <A | B | C | Mixed>+Roles: <count> (<list of role ids>)+Validator: PASS+```++**Per-role capability coverage:**++| Role | Assigned skills/tools | Recommend community search? |+|---|---|---|+| `<role-id>` | `<matched skills/tools, or "none">` | `<Yes / No — with reason>` |++**Recommendation logic — default is to recommend:**++For each role, evaluate whether to recommend community skill search:++- **Recommend** (default) — any role that could benefit from a **domain-specific** community skill. This includes roles that already have generic utility skills (like `web-research` or `curl`) but lack **domain-specialized** skills. A generic skill is NOT a substitute for domain expertise — see the anti-pattern below.+- **Do NOT recommend** — only when the role is **inherently self-sufficient**: its task is pure reasoning, judgment, or text generation that would not benefit from any external skill or tool. Examples: an adversarial critic whose job is to find logical flaws, a copy-editor whose job is to refine prose. These roles operate entirely within the LLM's native capabilities.++**Design intent**: the agent is structurally biased toward skipping community search. Two common rationalizations:++1. *"The role has no skills → but it can function on LLM knowledge alone"* — wrong in most cases. A role *can* function, but a matching skill often dramatically improves output quality.+2. *"The role already has a generic skill (e.g. `web-research`) → covered"* — **equally wrong and harder to catch**. A generic information-retrieval skill does NOT substitute for a domain-specific operational skill. `web-research` can search the web; a Taobao shopping skill knows store tiers, coupon stacking rules, platform-specific risk signals, and API-level price tracking — capabilities that no amount of generic search can replicate.++The default must be **recommend**, with the burden of proof on **not** recommending. The test is: *"Does a domain-specific community skill exist that would give this role capabilities beyond what its current generic skills provide?"* If plausible → recommend.++> **Anti-pattern: "通用即覆盖" (generic = covered)**+>+> In `ecommerce-compare-debate-team`, three platform shopper roles (`taobao-shopper`, `pinduoduo-shopper`, `jingdong-shopper`) each had `web-research` assigned. The agent concluded "already covered — no community search needed." This is wrong: `web-research` is general-purpose retrieval; it knows nothing about Taobao store tiers, PDD subsidy eligibility, or JD self-operated logistics. Community registries carry platform-specific shopping and buyer-agent skills that fill exactly this gap.+>+> **Rule**: if a role's identity is tied to a specific platform or professional domain, a generic utility skill does NOT count as coverage — always recommend community search for domain-specific skills.++**High-signal scenarios — MUST recommend** (non-exhaustive):++- **Binary/office file output** (PPTX, DOCX, XLSX, PDF) — LLM cannot generate binary formats natively; needs a skill wrapping python-pptx / docx etc.+- **Diagram/chart rendering** (Mermaid, Excalidraw, matplotlib) — LLM can describe but cannot render visuals without a generation skill.+- **Specific file format parsing** (CSV, images, audio, JSON-LD) — specialized parsing/validation skill is far more reliable than raw LLM attempts.+- **Domain-specific platform / service interaction** (e-commerce platforms, social media, financial services, travel booking, healthcare systems, government portals, etc.) — community registries often have skills that encode platform-specific rules, workflows, API integrations, or operational knowledge that generic retrieval skills cannot replicate. Examples: 淘宝/天猫购物 skills with store-tier logic, 京东 price-tracking skills, 拼多多 deal-finding skills, 买手/personal-shopper skills. A role whose identity is tied to a specific platform or professional domain should **always** trigger a community search, even if generic skills like `web-research` are already assigned.++If any role hits these patterns and no **domain-specific** local skill covers it, recommend "Yes" — do not rationalize it away with "the role can still produce text instructions" or "generic retrieval already handles it."++**Community enrichment prompt:**++If one or more roles are marked "Recommend: Yes", ask:++> *"The following roles have no domain-specific skills and could benefit from community skill enhancement:*+> *[table: Role | Current skills (if any) | What domain-specific skill would help]*+> *Shall I search community skill registries? The Teamskill is already complete — this is an optional enhancement. (Y/N)"*++If user says **Yes**:++Read [reference/community-search.md](reference/community-search.md) and follow its full procedure. Quick summary:++1. **Derive search queries** from each role's `purpose`, `Success Criteria`, and `Output Schema` — generate 2–3 keyword variants per role (see §1 Keyword Derivation).+2. **Multi-source parallel search** — run both Tier 1 CLIs simultaneously:+ - `npx skills find '<query>'` (skills.sh — keyword matching, install counts)+ - `skillnet search '<query>' --mode vector` (SkillNet — semantic vector search, quality evaluation)+ - If results are insufficient, escalate to Tier 2 web platforms (LLMBase, SkillsMP, LobeHub) and Tier 3 curated lists (awesome-agent-skills, awesome-claude-skills).+3. **Quality gates** — every candidate must pass: install count (≥ 1K preferred), source reputation, security rating, freshness (see §3).+4. **Role-skill fit test** — verify capability match and run the removal test: "would removing this skill significantly degrade the role's output?" (see §4).+5. **Present enrichment summary** to the user with the standardized format (see §5) — full transparency on what was searched, found, selected, and rejected.+6. Install approved skills, update `roles[].skills` in SKILL.md frontmatter + `dependencies.yaml` with `source: <community-url>`.+7. Re-run `python scripts/validate_teamskill.py` to confirm consistency.++If user says **No** → done. The Teamskill is fully functional as-is.++**Decision rules:**+- **Default: recommend** — empty `skills: []` = recommend community search; **also recommend** when a role only has generic utility skills (e.g. `web-research`) but lacks domain-specific skills matching its identity. Burden of proof is on NOT recommending.+- Prefer local over community — never search for capabilities already covered by a **domain-equivalent** local skill. A generic retrieval skill does NOT count as domain coverage.+- Per-role soft limit ≤ 1 community skill — if a role needs 2+, it may be too broad (consider splitting).+- Team-level soft limit: community deps ≤ role count — exceeding this signals over-engineering.+- Never force a dependency — mark `required: false` if the role can function without it.++## Roles++This skill has no Teamskill roles itself — it is a **single-agent skill** that authors Teamskills. The agent loading this skill plays the author/architect role.++## Files++| File | What it contains | When to read |+|---|---|---|+| [reference/pattern-selection.md](reference/pattern-selection.md) | A/B/C/Mixed pattern decision tree with worked examples | Stage 1a (before committing to a pattern) |+| [reference/role-design.md](reference/role-design.md) | How to author the 5 mandatory role sections; gate design between stages; anti-convergence techniques | Stage 2 + Stage 3 |+| [reference/conversion-guide.md](reference/conversion-guide.md) | Step-by-step methodology for converting a single-agent skill into a Teamskill, with a worked example | Stage 1b (CONVERT mode only) |+| [reference/compliance-checklist.md](reference/compliance-checklist.md) | Responsibility-attribution tests + manual-review checklist; explains what the validator can and cannot catch | Stage 6 (after the script passes) |+| [reference/community-search.md](reference/community-search.md) | Multi-source search strategy (keyword derivation, quality gates, role-skill fit test) for finding community skills | Post-generation (community enrichment step) |+| [templates/](templates/) | 5 file skeletons with placeholders and inline guidance comments | Stages 2–5 (each stage references its template) |+| [scripts/validate_teamskill.py](scripts/validate_teamskill.py) | Automated structural + frontmatter + section + cross-file consistency checks | Stage 6 (run on every Teamskill before declaring done) |++## Common pitfalls++Detailed pitfall analysis is in the reference files — read them during the corresponding stage:++- **Role authoring mistakes** (motto, boundary, persona): [reference/role-design.md](reference/role-design.md) § Putting it together: a role file checklist+- **Content quality judgment calls** (anti-convergence, gate strength, bind numbers): [reference/compliance-checklist.md](reference/compliance-checklist.md) Part B+- **Pattern selection errors** (council of clones, pipeline without gates, decomposition without disjointness): [reference/pattern-selection.md](reference/pattern-selection.md) § Anti-patterns++The three most common **structural** mistakes (caught by the validator, but worth internalizing):++1. **Skipping auto-matching in Stage 2** — jumping from role design to empty `skills: []` / `tools: []` without scanning locally available skills/tools. Fix: always run the auto-matching sub-step; empty lists are valid only after the scan confirms no matches.+2. **`roles[].skills` declared in SKILL.md but missing from `dependencies.yaml`** — silent contract violation. Fix: run the validator.+3. **Mermaid in SKILL.md body** — duplicating the diagram from `workflow.md`. Mermaid belongs only in `workflow.md`.++## Quick start++For a CREATE request:++1. Confirm Stage 0 justification with the user (which failure mode does single-agent hit?)+2. Read [reference/pattern-selection.md](reference/pattern-selection.md) and pick A / B / C / mixed+3. Write all `roles/<id>.md` files (motto, boundary, schema, inline persona) + auto-match local skills/tools+4. Write `workflow.md` → `bind.md` → `dependencies.yaml` → `SKILL.md` (each using its template)+5. Run `python scripts/validate_teamskill.py <teamskill-name>/` until exit 0+6. Present creation summary with per-role capability coverage → recommend community search for roles lacking **domain-specific** skills (default: recommend; generic utility skills do NOT satisfy the threshold)+7. Manual review with [reference/compliance-checklist.md](reference/compliance-checklist.md)++For a CONVERT request:++1. Read the source single-agent SKILL.md+2. Apply [reference/conversion-guide.md](reference/conversion-guide.md) decomposition checklist+3. Articulate "what is lost in single-agent form" — this is the Stage 0 justification+4. Continue from CREATE step 2 (pattern selection) onward+5. Add a `MIGRATION.md` (optional) to the new Teamskill explaining the source skill, the decomposition rationale, and the team-vs-single delta++For a MODIFY request:++1. Identify the change type from the impact matrix below+2. Re-run the indicated stages; apply edits honoring the section + structure rules (mottos, Forbidden+Mandatory, Inline Persona, gates, numeric bind constraints)+3. Run `python scripts/validate_teamskill.py <teamskill-name>/` — **Stage 6 is mandatory regardless of edit size**++#### MODIFY impact matrix++| Change type | Re-run stages | Files to update |+|---|---|---|+| Edit role Identity / Boundary / Schema | Stage 2 (affected role only) | `roles/<id>.md` |+| Add or remove a role | Stage 1a + 2 + 3 + 4 + 5 | All 5 files |+| Change workflow steps / topology | Stage 3 | `workflow.md` + `bind.md` (if constraints change) |+| Change bind constraints | Stage 4 | `bind.md` |+| Change dependencies | Stage 2 (auto-match) + 5 | `dependencies.yaml` + `SKILL.md` frontmatter |+| Edit SKILL.md description / purpose | Stage 5b | `SKILL.md` |++All rows require **Stage 6 (validator)** as the final step.diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/reference/community-search.md b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/reference/community-search.mdnew file mode 100644index 0000000000..727a82e3a9--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/reference/community-search.md@@ -0,0 +1,177 @@+# Community Skill Search Guide++How to find, evaluate, and install community skills for Teamskill roles. Read this file when executing the Post-generation community enrichment step.++## 1. Keyword Derivation++The #1 failure mode is bad search queries. Do NOT freestyle keywords — derive them systematically from the role spec.++### Extraction sources (in priority order)++For each role that needs a community skill, read these fields and extract terms:++1. **`purpose` field** (SKILL.md frontmatter) — the most compressed description of what the role does. Extract the **verb** (generate, parse, render, analyze, review, audit) and the **object** (diagram, pptx, security, performance).+2. **`Success Criteria`** (roles/\<id\>.md) — look for deliverable types and quality dimensions. Example: "Produces an Excalidraw JSON diagram" → search terms: `excalidraw`, `diagram`.+3. **`Output Schema`** (roles/\<id\>.md) — if the output is a specific file format, that format IS the search term. Example: output is `.pptx` → search `pptx` or `presentation`.++### Query formulation rules++- **Structure**: `<capability-verb> <domain-noun>` — e.g., `generate pptx`, `review security`, `parse csv`.+- **Always generate 2–3 query variants** per role. Use synonyms and specificity levels:+ - Specific: `excalidraw diagram`+ - Broader: `diagram generation`+ - Domain: `architecture visualization`+- **English only** — all major registries index in English. Translate Chinese terms before searching.+- **Avoid generic terms alone** — `code`, `review`, `write` are too broad. Always pair with a domain noun.+- **Include output format when applicable** — `pptx`, `docx`, `xlsx`, `pdf`, `svg`, `mermaid` are high-signal terms that dramatically narrow results.++### Worked example++Role: a "diagram-renderer" whose purpose is "Render architecture diagrams as Excalidraw JSON files."++| Source | Extracted terms |+|---|---|+| purpose | render, architecture, diagram, excalidraw, JSON |+| Success Criteria | "valid Excalidraw JSON", "auto-layout" |+| Output Schema | `.excalidraw` file |++Generated queries:+1. `excalidraw diagram` (specific)+2. `architecture diagram` (broader)+3. `canvas design` (alternative — Excalidraw skills sometimes use "canvas" in their name)++## 2. Multi-Source Search Strategy++Do NOT rely on a single registry. Use the two CLI sources **in parallel**, then cross-verify on web platforms.++### Tier 1: CLI Search (parallel — run both)++| Source | CLI | Search command | Install command | Strength |+|---|---|---|---|---|+| **skills.sh** | `npx skills` (Node) | `npx skills find '<query>'` | `npx skills add <owner/repo@skill> -g -y` | Largest install-count dataset, security scores |+| **SkillNet** | `skillnet` (Python: `pip install skillnet-ai`) | `skillnet search '<query>' --mode vector` | `skillnet download <url> -d ./skills` | **Semantic vector search** — finds results even when keywords don't exactly match |++**Why both**: skills.sh uses keyword matching and may miss relevant skills when your query terms don't match the skill's title/description verbatim. SkillNet uses vector similarity and finds semantically related skills even with imperfect queries. They index overlapping but not identical skill sets.++**Windows note**: on Windows, wrap `npx` commands in `powershell -Command "..."` to avoid empty output. `skillnet` (Python) works natively in any terminal.++### Tier 2: Web Verification + Broader Search++After CLI search returns candidates, or if CLI results are poor, use these web platforms:++| Source | URL | Use for |+|---|---|---|+| **LLMBase** | [llmbase.ai/skills/](https://llmbase.ai/skills/) | Verify install counts + security ratings (Safe/Medium/Critical); Top Sources ranking |+| **SkillsMP** | [skillsmp.com](https://skillsmp.com) | Broadest GitHub index (425K+); AI-powered search; category filtering |+| **LobeHub** | [lobehub.com/skills](https://lobehub.com/skills) | Community feedback; alternative categorization |+| **SkillNet Web** | [skillnet.openkg.cn](http://skillnet.openkg.cn/) | Browse curated collections; skill relationship graph |+| **skills.sh Leaderboard** | [skills.sh](https://skills.sh/) | Quick scan of top-installed skills by category |++### Tier 3: Curated Lists (high signal-to-noise fallback)++When CLI + web search return no good matches, browse these human-curated lists:++| Source | URL | Coverage |+|---|---|---|+| **awesome-agent-skills** | [github.com/heilcheng/awesome-agent-skills](https://github.com/heilcheng/awesome-agent-skills) | Cross-agent (Claude, Cursor, Copilot), tutorials + directories |+| **awesome-claude-skills** | [github.com/ComposioHQ/awesome-claude-skills](https://github.com/ComposioHQ/awesome-claude-skills) | Claude ecosystem deep-dive |+| **Antigravity awesome-skills** | [github.com/antigravity-ai/awesome-skills](https://github.com/antigravity-ai/awesome-skills) | 1200+ skills organized by **role bundles** (Web Wizard, Security Engineer, etc.) — particularly useful for Teamskill roles since the bundles map to role archetypes |++### Search procedure (step by step)++```+1. Derive 2–3 query variants per role (§1 above)+2. Run BOTH Tier 1 CLIs in parallel with each query variant+ - npx skills find '<query>'+ - skillnet search '<query>' --mode vector+3. Collect unique candidates from both sources+4. If < 2 candidates found → try Tier 2 web platforms with the same queries+5. If still < 2 candidates → browse Tier 3 curated lists by role archetype+6. Apply quality gates (§3 below) to all candidates+7. Apply role-fit test (§4 below) to surviving candidates+```++## 3. Quality Gates++Do NOT install a skill just because it appeared in search results. Every candidate MUST pass these gates:++### Gate 1: Install Count++| Threshold | Action |+|---|---|+| ≥ 10K installs | **Strong signal** — use with confidence |+| 1K–10K installs | **Moderate** — acceptable if source is reputable |+| 100–1K installs | **Weak** — only if no better alternative exists AND source passes Gate 2 |+| < 100 installs | **Reject** — too risky for a dependency |++Where to check: skills.sh leaderboard, LLMBase skill page, `npx skills` output (shows install count).++### Gate 2: Source Reputation++Prefer skills from known, maintained sources:++**Trusted sources** (non-exhaustive):+- `vercel-labs/agent-skills` — React, Next.js, web design+- `anthropics/skills` — frontend design, document processing (pdf, pptx)+- `microsoft/azure-skills` — cloud, infrastructure+- `firebase/agent-skills` — Firebase ecosystem+- `supabase/agent-skills` — database, backend+- `coreyhaines31/marketingskills` — marketing, SEO, copywriting+- `remotion-dev/skills` — video generation+- `google-labs-code/stitch-skills` — Google design system+- `expo/skills`, `flutter/skills` — mobile development++**Caution signals**:+- Unknown author with no GitHub profile+- Repository with < 50 stars+- No commits in the last 6 months+- Skill description is vague or generic++### Gate 3: Security Rating++Check the security rating on LLMBase or skills.sh:++| Rating | Action |+|---|---|+| **Safe** | Install freely |+| **Medium** | Acceptable — review the skill content before installing |+| **Critical** | Do NOT install unless explicitly approved by the user. Flag in the enrichment summary |++### Gate 4: Freshness++Check the source repository's last commit date. Skills based on framework best practices become stale quickly.++| Last updated | Action |+|---|---|+| Within 3 months | Current |+| 3–6 months | Acceptable |+| > 6 months | Flag as potentially stale — verify the content still applies |++## 4. Role-Skill Fit Test++After a candidate passes quality gates, evaluate whether it actually fits the role. Ask:++1. **Capability match**: Does this skill provide a capability the role's `Success Criteria` requires? If the skill teaches "React best practices" but the role produces "security audit reports," it's not a fit — even if both mention "code."+2. **Removal test**: If you removed this skill, would the role's output quality **significantly** drop? "Significantly" means: the role would produce noticeably worse deliverables, not just slightly less polished ones. If the answer is "no," don't install.+3. **Overlap test**: Does this skill's capability overlap with another role's assigned skill? Cross-role skill sharing is a code smell — each skill should enhance exactly one role.+4. **Format necessity**: If the role outputs a specific file format (PPTX, XLSX, Excalidraw JSON), the skill MUST handle that format's generation/manipulation. A skill that only provides "guidelines" without generation capability is not sufficient.++## 5. Enrichment Summary Format++After completing the search, present results in this format:++```+## Community Skill Search Results++| Role | Query used | Candidates found | Selected | Install count | Security | Reason |+|---|---|---|---|---|---|---|+| <role-id> | <best query> | <N total> | <skill name or "none"> | <count> | <Safe/Med/Crit> | <1-line fit rationale> |++### Install commands+<for each selected skill, the exact install command>++### Skipped candidates+<for each rejected candidate: name, rejection reason (failed which gate)>+```++This format gives the user full transparency on what was searched, what was found, and why each decision was made.diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/reference/compliance-checklist.md b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/reference/compliance-checklist.mdnew file mode 100644index 0000000000..ecc2e55581--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/reference/compliance-checklist.md@@ -0,0 +1,180 @@+# Compliance Checklist++> Read in **Stage 6** after the validator script passes. The script catches structural / frontmatter / section-presence / cross-file errors. This checklist catches **judgment calls the script cannot automate** — the responsibility-attribution tests that decide whether new fields belong in the spec, plus content-quality checks.++## What the validator script catches (do not duplicate here)++The validator handles:+- Five-file structure (SKILL.md / roles/ / workflow.md / bind.md / dependencies.yaml)+- Frontmatter required fields (`name`, `description`, `version`, `kind: team-skill`, `roles[]`)+- Each `roles[].id` has matching `roles/<id>.md`+- Each role file has the 5 mandatory sections+- Each Identity starts with `> *"..."*`+- `workflow.md` has Overview/Detailed Steps/Acceptance Criteria + at least one mermaid block+- `bind.md` has Resource Constraints / Behavioral Constraints / Failure Handling+- `dependencies.yaml` has both `skills:` and `tools:` segments+- Every `roles[].skills` and `roles[].tools` declared in SKILL.md appears in dependencies.yaml++If the script reports failures, fix them first. **This checklist starts where the script ends.**++---++## Part A: Responsibility-attribution tests++For each new section / field / rule you introduce beyond the templates, run these tests. Any candidate that fails one or more tests should be rejected or moved out of the spec.++### Test 1 — Consumer-and-time check (run BEFORE any redundancy claim)++Before declaring two things "redundant", verify their **consumers and timing** are the same.++- `description` (system-prompt-time, decides trigger) vs `## Workflow` (already-triggered Agent reading body) → different consumers → NOT redundant.+- `## Workflow` in SKILL.md (prose summary) vs `workflow.md` (full mermaid + steps) → same consumer (Leader), different depth → NOT redundant; SKILL.md links to workflow.md.+- mermaid in SKILL.md body vs mermaid in workflow.md → SAME consumer (reader visualizing flow) → REDUNDANT → keep only in workflow.md.++### Test 2 — Registry / store concern?++If the candidate field is about discovery, recommendation, download counts, tier, popularity → **registry concern, not Teamskill spec**. Examples: `tier`, `downloads`, `category` for browsing.++### Test 3 — Runtime / framework concern?++If the candidate field is about how the framework wires dependencies, dispatches teammates, or implements messaging → **framework concern, not Teamskill spec**. Examples: `teammate_mode`, `install_command`, message format. The Teamskill MAY declare a **preference order** for inter-member communication (e.g., direct peer-to-peer > shared blackboard > Leader-relay), but MUST NOT mandate a specific mechanism.++### Test 4 — Tutorial / docs concern?++If the candidate content is long-form examples, anti-patterns, common pitfalls — and it's NOT actionable at runtime → **docs concern**. Move to `examples/` directory or external README. **Exception**: short bullet-style guidance in templates is fine.++### Test 5 — Already in git / filesystem metadata?++If the candidate field is mtime, author, commit history, file size → **already in git / FS**. Do not duplicate.++### Test 6 — Already defined elsewhere?++After Test 1 (consumer-and-time check), if two locations carry the same content for the same consumer at the same time → keep one, delete the other.++### Test 7 — Internal implementation leaking?++If the candidate field exposes session IDs, internal trace handles, framework-specific identifiers → **leak**. Hide it.++### Test 8 — Machine-verifiable?++If the field is purely human-written prose with no machine-checkable correctness → **risky**. Keep only if the value-to-verifiability ratio is high. Most natural-language sections are accepted because their value is high; new fields should justify themselves.++### Test 9 — Future-use safety net++Before deleting a long-unused field, consider whether a planned future field would give it new purpose. Leave it as **optional** if uncertain. Do not judge a field in isolation when the surrounding spec is still evolving.++---++## Part B: Content-quality manual checks (judgement calls)++The validator confirms structure exists. These checks confirm the structure is **good**:++### B1. Identity mottos — anti-convergence++Read all role mottos as a list. Apply this test:++> *"If I shuffled these mottos and asked a reader to assign each motto to a role file, could they do it correctly without context?"*++If yes → mottos are distinctive. If no → roles will converge in output. Rewrite the offending mottos using [role-design.md](role-design.md) § Anti-convergence techniques.++### B2. Boundary completeness++For each role, read its `Boundary` and ask:++- **Forbidden**: does the list mention every sibling role's territory? (For A/B patterns where overlap is the risk.)+- **Mandatory**: does the list prevent silent under-delivery? (For roles that might output "looks fine" or skip slices.)++A `Boundary` with only Forbidden tends to produce empty findings. A `Boundary` with only Mandatory tends to produce role overlap. Both halves work as opposing forces.++### B3. Inline Persona self-containment++For each role's `## Inline Persona for Teammate`, do this test:++> *"If I copy-pasted this prompt verbatim into a fresh agent with no other context, could it produce a valid output that matches the schema?"*++Common gaps:+- Persona references "the team" or "the Leader" without explaining → opaque to a teammate+- Persona mentions methodology (STRIDE, SCQA) without defining it → teammate might not know it+- Placeholders like `{INPUT}` are present but not labeled → unclear what to fill in+- Output format described in prose but not shown as a literal template → teammate guesses structure++### B4. Workflow gates have teeth++For each step in `workflow.md > Detailed Steps`, verify:++- The step has a **quality gate** declared (pass criteria + fail action).+- The fail action is **specific** ("retry once, then mark missing in report" — not "handle failure").+- For C-pattern stage transitions, `bind.md` declares "Stage N+1 MUST refuse to start if gate FAIL".++A workflow without enforceable gates is just prose; the team will skip steps under load.++### B5. Bind numbers are real++Check `bind.md > Resource Constraints` numbers against the workflow:++- `max_parallel_teammates` ≥ the largest parallel fan-out in the mermaid diagram+- `total_wall_clock_budget` ≥ sum of sequential stage budgets+- `total_token_budget` ≥ rough estimate of (per-role tokens × N roles)++Numbers that don't match the workflow are theater.++### B6. Failure handling covers both required scenarios++`Failure Handling` MUST cover:++- (a) **Teammate failure** — timeout, malformed output, retry policy, missing-output reporting+- (b) **Input over-scale degradation** — what triggers degraded mode, what the degraded mode does, how the user is warned++Re-read your `Failure Handling` and confirm both are present. Most authoring errors omit (b).++### B7. dependencies.yaml has user-facing `purpose` lines++Each `skills[]` and `tools[]` entry has a `purpose` field that is **human-readable** and **explains the consequence of missing**:++- Good: `purpose: locate symbols and call sites in the diff`+- Bad: `purpose: code-search dependency`+- Bad: `purpose: required for the skill`++The `purpose` field is shown to the user during pre-flight checks when a dependency is missing. Write it for that audience.++### B8. SKILL.md description is a real trigger++Read the `description` and ask:++- Does it state **WHEN** to use? ("Use when: ...")+- Does it state **WHEN NOT** to use? ("DO NOT use for: ...")+- Does it list 1–3 **trigger phrases** that the agent should recognize?+- Is it 1–5 lines (system prompts hard-cap descriptions)?++A description that omits "when not to use" causes the skill to over-trigger. A description without trigger phrases causes the skill to under-trigger.++---++## Part C: Cross-Teamskill consistency (only when publishing multiple together)++When publishing a batch of Teamskills as a coherent set:++- [ ] Naming convention: all Teamskills end with `-team` suffix+- [ ] Frontmatter `version` consistent across the batch+- [ ] Description structure follows the same template ("Use when..." / "DO NOT use for..." / "Triggers...")+- [ ] No two Teamskills overlap in trigger conditions (they would compete in the trigger system)+- [ ] All Teamskills produce structurally similar Final Reports (tiered, schema-based) so users learn one mental model++Cross-Teamskill consistency is a usability concern, not a per-skill compliance rule.++---++## Final sign-off ritual++Once all above checks pass, write a 2-line sign-off in the conversation (not in any file):++```+Teamskill: <name>+Pattern: <A | B | C | A+B | B+C | C+A | C+B+A | Debate>+Roles: <count> (<list of role ids>)+Validator: PASS+Manual checks: PASS (all responsibility-attribution and content-quality tests)+Justification: <1-line Stage 0 reason this team beats single-agent>+```++This forces a final articulation of the Teamskill's reason to exist.diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/reference/conversion-guide.md b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/reference/conversion-guide.mdnew file mode 100644index 0000000000..6177c6e1be--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/reference/conversion-guide.md@@ -0,0 +1,167 @@+# Conversion Guide: Single-agent Skill → Teamskill++> Read this in **Stage 1b** when the user points at an existing single-agent skill and asks to convert it. After this stage, return to the main SKILL.md workflow at Stage 1a (pattern selection) onward.++## When NOT to convert++Conversion is only worth it if you can answer **"yes"** to at least one of these:++1. **The source skill embeds 2+ personas inside one prompt** (e.g., `adversarial-reviewer` has Saboteur + New Hire + Security Auditor inside one SKILL.md). The single agent cannot truly hold multiple POVs simultaneously — outputs converge. → **A-pattern conversion.**+2. **The source skill has 3+ checklist categories that are independently investigable** (e.g., a security skill with separate auth / input-validation / dependency / config sections). Running these in parallel buys both wall-clock and depth per slice. → **B-pattern conversion.**+3. **The source skill describes a sequential workflow with quality steps** (e.g., a copywriting skill that says "first write a brief, then draft, then edit, then audit"). Single agents cut corners on phase boundaries. Enforcing them via separate roles + gates lifts quality. → **C-pattern conversion.**++If none apply: **stop**. Tell the user the skill is already well-suited to a single agent. Conversion would add overhead without clear benefit.++## Conversion pipeline (5 steps)++### Step 1: Read the source skill end-to-end++Look for these structural signals:++| Signal in source skill | Maps to |+|---|---|+| `## Persona 1 / ## Persona 2 / ...` sections | A-pattern roles (1 per persona) |+| `## Checklist: A / B / C / ...` sections | B-pattern roles (1 per disjoint category) |+| `## Step 1 / ## Step 2 / ...` workflow with explicit deliverables | C-pattern stages (1 per step with handoff) |+| `## Anti-patterns` enumerating common single-agent failures | Each anti-pattern hints at the team value (what the team prevents) |+| `MUST find at least N issues` or similar forced-output rules | These become role-level `Boundary > Mandatory` |+| `Inspection process: 1. ... 2. ... 3. ...` | These become Inline Persona steps |++### Step 2: Articulate "what is lost in single-agent form"++Write a one-paragraph **conversion rationale** answering:++> *"Today, when a single agent runs this skill, what does it systematically miss or under-deliver on?"*++If you cannot answer crisply, conversion is premature. Examples of crisp answers:++- **`adversarial-reviewer` → `pr-review-team`**: "The single agent role-plays 3 personas serially, but its outputs converge because it cannot escape its own analytical priors. Independent parallel agents produce genuinely different findings."+- A multi-stage incident-response skill → team form: "The single agent skips the postmortem after mitigation succeeds, because the user's perceived crisis is over. Separating roles + gating mitigation→postmortem enforces the discipline."+- A copywriting skill → team form: "The single agent collapses brief and copy into one pass, losing the audit trail and the discipline of editing without rewriting."++This rationale becomes the Stage 0 justification and gets cited in the new Teamskill's SKILL.md `description` (use case) + workflow.md Overview.++### Step 3: Decompose into roles++Apply the heuristics from Step 1 to extract role candidates. Then run the **disjointness test**:++For each pair of role candidates (A, B), ask: *"Could one role's deliverable substitute for the other's?"*++- If yes for any pair → roles overlap → merge or redesign.+- If no for all pairs → decomposition is clean, proceed.++Record each role as a tuple: `(id, motto, success criteria 1-liner, methodology)`.++### Step 4: Pick the pattern++Use [pattern-selection.md](pattern-selection.md). For converted skills, the pattern is usually obvious from Step 1's structural signals:++| Source signal dominant | Pattern |+|---|---|+| Multiple personas in one SKILL.md | A |+| Multiple disjoint checklists | B |+| Multi-step workflow with deliverables | C |+| Personas + checklists | A + B |+| Multi-step workflow with adversarial review at one step | C + A |+| Multi-step workflow with parallel research at one step | C + B |++### Step 5: Generate the new Teamskill via the standard pipeline++Continue from main SKILL.md **Stage 2 onward** (Role design → Workflow → Bind → Dependencies → Templates → Validate).++When filling in templates, **port content from the source skill aggressively**:++| Source skill content | Goes to |+|---|---|+| Persona descriptions | `roles/<id>.md` `## Identity` (rewrite first line as 1-line motto!) |+| Per-persona "Inspection Process" or steps | `roles/<id>.md` `## Inline Persona for Teammate` |+| `MUST find` rules / forced output rules | `roles/<id>.md` `## Boundary > Mandatory` |+| Output format templates | `roles/<id>.md` `## Output Schema` |+| Workflow / sequence descriptions | `workflow.md` `## Detailed Steps` |+| Anti-patterns / pitfalls | `bind.md` `## Behavioral Constraints` (if team-level) or `## Failure Handling` (if recovery-related) |+| Tool lists (`gh`, `grep`, `python`) | `roles[].tools` in SKILL.md frontmatter + `dependencies.yaml` `tools` segment |+| Required Skills (cross-references) | `roles[].skills` in SKILL.md frontmatter + `dependencies.yaml` `skills` segment with `source: <URL>` if external |++## Worked example: `adversarial-reviewer` → `pr-review-team`++This is the canonical conversion. Walk through it as a template.++### Source structure++A real public single-agent skill `adversarial-reviewer` (an engineering-team skill that runs 3 review personas serially inside a single SKILL.md):++```+---+name: adversarial-reviewer+description: Reviews PRs by running 3 internal personas...+---++## Persona 1: The Saboteur+Mindset: ...+Priorities: ...+Review Process: ...+MUST-Find Rule: ...++## Persona 2: The New Hire+Mindset: ...+Priorities: ...+...++## Persona 3: The Security Auditor+Mindset: ...+Priorities: ...+...++## Severity Table+- BLOCK / SIGNIFICANT-RISK / ACCEPTABLE-RISK / LOW-RISK++## Output Format+...+```++### Conversion steps applied++1. **Read end-to-end** → 3 distinct personas with distinct mindsets, distinct priorities, distinct MUST-find rules. Severity table is shared. Output format is shared.++2. **Articulate loss** → "A single agent serially role-playing 3 personas converges to similar findings because it cannot drop its priors between persona switches. Independent parallel agents produce genuinely different findings; running them in isolation is the value."++3. **Decompose** → 3 roles emerge naturally: `code-reviewer` (forward review of quality/test coverage; New Hire-flavored), `critique-adversarial` (Saboteur), `architect` (Security Auditor + cross-cutting). Disjointness check: each role has a distinct domain (quality / risks / architecture). PASS.++4. **Pattern** → A (parallel adversarial). Add Architect for cross-cutting view.++5. **Generate**:+ - Each persona's Mindset → role's `## Identity` 1-line motto (rewrite the prose Mindset into a single quotable sentence).+ - Each persona's Priorities → role's `## Success Criteria` "Focus areas" line.+ - Each persona's MUST-Find Rule → role's `## Boundary > Mandatory`.+ - Severity Table → shared `## Output Schema` Verdict enum across all 3 roles.+ - Output Format → role-specific `## Output Schema` template.+ - The 3 personas' Inspection Process content → each role's `## Inline Persona for Teammate`.+ - New file: `workflow.md` with mermaid showing parallel dispatch + Leader integration node.+ - New file: `bind.md` with `max_parallel_teammates: 3`, `total_token_budget: 200k`, "Leader does not write review content", "Teammates MUST NOT see each other's output".+ - New file: `dependencies.yaml` with `gh` (required) and `grep` (required) — preserved from source skill's tool list.++### Result++`pr-review-team`. The conversion preserves all source content while adding:++- **True parallelism** (3 isolated agents instead of 1 serial agent)+- **Anti-overlap boundaries** (each role's `**Forbidden**:` block names the other roles)+- **Quality gates** (workflow surfaces contradictions verbatim instead of letting one agent silently mediate)+- **Resource accounting** (`bind.md` makes the 3× token cost explicit)++---++## Conversion compliance checklist++Before declaring a conversion done, verify:++- [ ] **Stage 0 justification written** (1 paragraph: "what is lost in single-agent form")+- [ ] **Pattern picked** with reference to source signals (Step 1 table)+- [ ] **All source persona Mindsets** rewritten as 1-line mottos+- [ ] **All source MUST-Find rules** ported into role `Boundary > Mandatory`+- [ ] **All source Output Formats** preserved in role `Output Schema`+- [ ] **All source tools** declared in `roles[].tools` + `dependencies.yaml > tools`+- [ ] **All source cross-referenced Skills** declared in `roles[].skills` + `dependencies.yaml > skills`+- [ ] **`bind.md` Behavioral Constraints** explicitly state isolation rule (A-pattern teams)+- [ ] **Validator passes** on the new Teamskill directory+- [ ] **Optional: `MIGRATION.md`** at the root of the new Teamskill, documenting the source skill, the conversion rationale, and the team-vs-single delta (useful for the user to understand what they gained)diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/reference/pattern-selection.md b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/reference/pattern-selection.mdnew file mode 100644index 0000000000..76b6461744--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/reference/pattern-selection.md@@ -0,0 +1,182 @@+# Pattern Selection Guide++> Read this in **Stage 1a** of the SKILL.md workflow, before writing any role files. Picking the wrong pattern is the most common authoring error — patterns dictate role count, isolation rules, integration logic, and `bind.md` failure modes.++## The three primitive patterns++### A. Adversarial / Cross-check++**Use when**: a single agent role-playing N personas converges to similar conclusions because it cannot escape its own priors. The value of the team is **disagreement surfaced as evidence**.++**Shape**: 2–4 roles, run **in parallel**, **isolated** (no cross-visibility), Leader **surfaces contradictions** rather than resolving them.++> When adversarial tension needs **mutual visibility** (e.g., structured debate with rebuttal rounds), use the [Debate mixed pattern](#debate-b--cross-exam--c) instead of standalone A.++**Identity test**: each role's 1-line motto should be **mutually antagonistic**. If two mottos could be spoken by the same person, the roles will converge.++**Example mottos that work** (from `pr-review-team`):+- Code reviewer: *"I am looking for what this code does well and how to ship it."*+- Adversarial critic: *"I am trying to break this change before it reaches production."*+- Architect: *"I care about whether this fits the system five years from now."*++**Example mottos that fail** (would converge):+- Reviewer A: *"I look for bugs and security issues."*+- Reviewer B: *"I look for security issues and bugs."*++**Integration rule**: ≥2 roles agree → MUST-FIX. 1 role flags + others silent → SHOULD-FIX. Roles directly contradict → surface verbatim, **do not mediate**.++**Examples**: `pr-review-team`, `paper-peer-review-team`, `contract-review-team` (buyer counsel vs seller counsel + neutral reviewer).++### B. Parallel decomposition++**Use when**: the task naturally splits into N independent sub-tasks that can run concurrently and the integration is non-trivial. The value of the team is **wall-clock speedup + breadth coverage**.++**Shape**: 2–N roles (often variable count via `count: [min, max]` in frontmatter), run **in parallel**, each role works on a **disjoint slice** of the input/problem space, Leader **integrates** by composition (not by judgment).++**Disjointness test**: each role must have a non-overlapping "assignment" (an angle, a category, a region, a layer). If two roles could produce the same finding, the decomposition is broken.++**Example assignments that work** (from `research-to-ppt-team`):+- Angle researcher #1: market dynamics+- Angle researcher #2: technology landscape+- Angle researcher #3: regulatory environment++**Example assignments that fail** (overlap):+- Researcher #1: "all things related to the topic"+- Researcher #2: "key information about the topic"++**Integration rule**: collect outputs by slice, deduplicate cross-slice findings, flag gaps where coverage is missing.++**Examples**: pure-B is rare in practice; usually combined with A or C. See `systematic-debug-team` (B for parallel hypothesis generation across distinct theory classes).++### C. Specialization pipeline++**Use when**: the task has **sequential expert stages** with **strict handoff contracts**, and blurring stage boundaries causes regressions (e.g., the editor rewriting the strategist's brief, the mitigator skipping triage). The value of the team is **enforced discipline + quality gates**.++**Shape**: 3–5 roles, run **sequentially**, each stage **sees prior stage output** but **cannot rewrite it**, **quality gates between stages** with explicit pass/fail criteria.++**Boundary test**: each role must have an explicit `**Forbidden**: do NOT redo upstream work` clause. Without it, roles drift back into earlier stages.++**Example stage chain** (from `marketing-copy-team`):+- Stage 1 brief-strategist → produces strategy brief (gate: brief approved)+- Stage 2 copywriter → produces draft (gate: draft matches brief)+- Stage 3 copy-editor → enhances draft (gate: no rewrites of brief or draft structure)+- Stage 4 conversion-auditor → audits final (gate: meets conversion criteria or kicks back)++**Gate rule**: a stage outputs a structured deliverable; the next stage refuses to start unless the gate passes; failed gates trigger explicit retry / kick-back paths declared in `bind.md` Failure Handling.++**Examples**: `marketing-copy-team`, `incident-response-team`, `seo-growth-team`.++## Mixed patterns (when to combine)++Most non-trivial Teamskills combine 2 patterns. The combinations and their use cases:++### A + B (parallel adversarial)++**Use when**: you need both adversarial breadth AND parallel coverage. Multiple parallel investigators with non-overlapping assignments + an adversarial reviewer at the end.++**Example**: `systematic-debug-team` (3 parallel hypothesis-generators with forced theory-class diversity + 1 evidence collector + 1 adversarial root-cause-analyst + 1 fix-validator).++**Example**: `security-audit-team` (3 parallel auditors: threat-modeler / vulnerability-scanner / dependency-auditor + 1 adversarial attack-chain-synthesizer who must connect their findings into exploit paths).++### B + C (parallel research → pipeline finalization)++**Use when**: parallel breadth is needed early, then a sequential editorial pipeline finalizes the output.++**Example**: `research-to-ppt-team` (2–4 parallel angle-researchers → 1 content-curator → 1 slide-designer).++### C + A (pipeline with adversarial gate)++**Use when**: a sequential pipeline benefits from an adversarial reviewer at one or more gates.++**Example**: `design-review-team` (analyst → critic → architect, where critic is the adversarial slot).++**Example**: `travel-planning-team` (planner-builder produces itinerary; budget-optimizer and experience-maximizer adversarially critique it; logistics-validator ratifies feasibility).++### C + B + A (full stack)++**Use when**: a hard quality gate at entry, then parallel multi-method analysis, then adversarial critique. Reserved for high-stakes analysis pipelines.++**Example**: `data-analysis-team` (Stage 0: data-quality-auditor as hard gate → Stage 1: 3 parallel analysts (descriptive / inferential / causal) → Stage 2: 1 adversarial critique-reviewer).++### Debate (B → Cross-exam → C)++**Use when**: roles need to first produce independent positions (isolation prevents premature alignment), then **rebut each other's specific claims** with mutual visibility, then a separate role synthesizes the resolution preserving unresolved disputes.++**Shape**: 2–N roles produce `POSITION` in parallel isolation → each role receives others' prior-round output and produces structured `CROSS_EXAM` in parallel with mutual visibility → 1 synthesizer/judge produces `DECISION`.++**Key distinction from standalone A**: pure A keeps roles permanently isolated — the value is independent judgment that never cross-contaminates. Debate **phase-scopes** the isolation: Round 1 isolated, Round 2+ mutually visible. The adversarial value comes from **structured clash on specific claims**, not permanent blindness.++**Rounds**: Debate supports 1–N cross-exam rounds (each round = all roles receive prior round's outputs and produce structured responses). Round count is a **resource/quality tradeoff** — declare it in `bind.md`, not here. Most scenarios converge in 1–2 rounds.++**Visibility semantics**: the Teamskill declares **who sees whose output at which phase**. How this is delivered is a **framework-level implementation choice**, not a Teamskill concern — but with a **recommended preference order**: (1) **direct peer-to-peer exchange** (most efficient, lowest information distortion); (2) shared blackboard / shared state; (3) Leader-relay (fallback when the framework does not support peer communication). Frameworks SHOULD implement the highest-priority mechanism they support.++**Example**: `china-ecommerce-compare-debate-team` (3 platform experts produce isolated position papers → cross-exam with mutual visibility → value-synthesizer produces verdict with unresolved disputes preserved).++## Decision tree++```+Q1. Does a single agent systematically miss something on this task today?+ NO → Stop. Build a single-agent skill with create-skill instead.+ YES → Q2.++Q2. What does it miss?+ (a) Adversarial blind spots / convergent self-review → A+ (b) Breadth / parallel coverage of independent slices → B+ (c) Discipline at handoffs in a multi-stage pipeline → C+ (d) Adversarial exchange requiring mutual visibility (debate/rebuttal)+ → Mixed: Debate (B → Cross-exam → C)++Q3. Does it miss only ONE of (a)/(b)/(c)?+ YES → Use that single pattern.+ NO → Combine: A+B / B+C / C+A / C+B+A.+ Order matters — pipelines flow stages first, then place A or B+ inside specific stages where the value is highest.++Q4. How many roles? (authoring defaults, not hard limits)+ A pattern: 2-4 roles (past 4, contradictions combinatorially explode)+ B pattern: 2-N roles (use count: [min, max]; only real cap is bind.md token budget)+ C pattern: 3-5 stages (past 5, stages tend to be mergeable)+ Mixed: 4-6 roles (past 6, integration becomes the bottleneck)++Q5. How does Leader integrate outputs?+ A: surface contradictions, do NOT mediate+ B: compose by slice, flag coverage gaps+ C: enforce gates, kick back on failure+ Mixed: stage-by-stage; the pattern of the LAST stage dictates final integration+```++## Anti-patterns++### "Council of clones"++Three roles with the same Identity prose and only nominal name differences. Their outputs converge. Symptom: roles all say "looks good" or all flag the same trivial issues.++**Fix**: rewrite Identity mottos to be mutually antagonistic. Re-read [role-design.md](role-design.md) § Anti-Convergence Techniques.++### "Pipeline that nobody follows"++C-pattern declared, but stages have no quality gates. Result: stages bleed into each other; the editor rewrites the brief; the mitigator skips triage.++**Fix**: every stage transition needs a gate definition with explicit pass/fail criteria, and every role's `Boundary` must have `**Forbidden**: do NOT redo upstream stage X` clauses.++### "Decomposition without disjointness"++B-pattern declared, but roles overlap on the problem space. Result: 3 researchers all return the same top-3 findings.++**Fix**: assign each role a non-overlapping slice **at dispatch time** (the Leader picks slices from a fixed list and passes the assignment as a parameter to the Inline Persona).++### "Mixed pattern justified by ambition"++Combining A+B+C because "more is better". Result: 6 roles, 3 integration nodes, and nobody can debug it.++**Fix**: only combine patterns when each one is independently justified by Stage 0. If C+B alone solves the problem, do not add A.++## How to record the pattern in the Teamskill++The spec **does not have a `pattern: A/B/C` frontmatter field** — declaring the pattern as a string would duplicate what the mermaid diagram already expresses, and the diagram is more precise. Instead, the pattern is expressed implicitly through:++1. **`workflow.md` mermaid diagram** — parallel branches = A or B, sequential chain = C, mixed shapes = mixed.+2. **`roles[]` purpose lines** — adversarial roles say "adversarial", "critic", "challenger"; pipeline stages number themselves or chain explicitly.+3. **`bind.md` Behavioral Constraints** — A-pattern teams have "teammates MUST NOT see each other's output"; C-pattern teams have "no rewriting upstream stage output".++You may add a brief `## Pattern` note in `workflow.md` `## Overview` if it aids the reader, but it is not required by the spec.diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/reference/role-design.md b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/reference/role-design.mdnew file mode 100644index 0000000000..efd089e557--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/reference/role-design.md@@ -0,0 +1,299 @@+# Role Design Guide++> Read this in **Stage 2** (and revisit during Stage 3 for gate design). This file teaches how to author a single `roles/<id>.md` file that passes both spec compliance and the anti-convergence test.++## The 5 mandatory sections++Every role file starts with an `# Role: <Name>` H1 title, then MUST contain exactly these 5 sections, in order:++1. `## Identity` — POV with mandatory 1-line motto first+2. `## Success Criteria` — what success looks like + focus areas+3. `## Boundary` — Forbidden + Mandatory+4. `## Output Schema` — structured output template+5. `## Inline Persona for Teammate` — pasteable prompt++The validator script enforces section presence. The judgment-call quality of each section is what this guide is about.++---++## Section 1: Identity++### Hard rule: first line is a 1-line motto++The motto is the **#1 anti-convergence mechanism** in the spec. Without it, prose Identity sections cause sibling roles to converge in output. The motto must:++- Be a **single sentence** in `> *"..."*` blockquote-italic format+- Be **first-person** (this is the role speaking)+- Be **mutually antagonistic** with sibling roles in an A-pattern team+- Crystallize a **point of view**, not a job title++**Good mottos**:++```markdown+> *"I am trying to break this code in production."*+> *"I am the user. I want to ship value, not perfect code."*+> *"I care about whether this fits the system five years from now."*+> *"I will refuse the deal if even one term smells wrong."*+> *"I am the data. I will tell you what is true even if it disappoints you."*+```++**Bad mottos** (and why):++| Bad | Why |+|---|---|+| *"I am a senior security engineer."* | Job title, not POV — could be said by 100 different roles |+| *"I find bugs and security issues."* | Capability description — converges with any reviewer role |+| *"I help the user."* | Vacuous — every role helps the user |+| Multi-sentence motto | Dilutes the POV — must be ONE sentence |+| Third-person ("This role looks for...") | Loses the in-character voice |++### After the motto: 0–2 paragraphs of context++Optional. Use these paragraphs to:++- Name the methodology the role applies (STRIDE, OWASP Top 10, SCQA, 5-Whys, etc.)+- Specify the role's "default mode" (skeptical / generous / adversarial / clinical)+- Explain the role's "when called in" — under what conditions does this POV add value++**Do not use these paragraphs to**:+- Repeat the Success Criteria — that's the next section, do not duplicate it here+- List checklists (those go in `Inline Persona`, where the teammate actually sees them)++---++## Section 2: Success Criteria++### Format++```markdown+## Success Criteria++- [Concrete deliverable 1]+- [Concrete deliverable 2]+- [Concrete deliverable 3]++**Focus areas**: [comma-separated list of what this role should prioritize examining]+```++### Quality bar++Each bullet should be **observable** — a reviewer should be able to look at the role's output and check ✓/✗ against it. Avoid:++| Vague | Concrete |+|---|---|+| "Provides good analysis" | "Returns at least 1 concrete failure scenario with evidence" |+| "Considers all angles" | "Coverage spans security / performance / readability — flagged separately" |+| "Helps the user" | "Output uses the schema in § Output Schema, no missing required fields" |++The "Focus areas" line tells the role what to prioritize examining — keep it tight, 5–10 comma-separated items.++---++## Section 3: Boundary++### Format (mandatory split)++```markdown+## Boundary++**Forbidden** (prevent role overlap):+- Do NOT [thing that another role does]+- Do NOT [thing that drifts upstream/downstream in the pipeline]++**Mandatory**:+- You MUST [thing the role tends to skip when it sees nothing obvious]+- You MUST [output discipline that the schema enforces]+```++### Why both halves are required++- **Forbidden** prevents **lateral drift** — in A/B patterns, roles bleed into each other's territory; in C patterns, stages drift upstream/downstream.+- **Mandatory** prevents **silent under-delivery** — adversarial roles default to "looks fine" when they cannot find obvious issues; coverage roles skip slices when the slice seems empty.++A role with only Forbidden tends to output empty findings. A role with only Mandatory tends to encroach on siblings. Both halves work as opposing forces.++### Examples++**A-pattern role** (`pr-review-team` adversarial-critic):++```markdown+**Forbidden**:+- Do NOT critique style or readability — that's the Code Reviewer's job.+- Do NOT propose architectural redesigns — that's the Architect's job.++**Mandatory**:+- You MUST find at least 1 concrete failure scenario.+ If you found nothing, you didn't look hard enough — recheck error paths and edge cases.+```++**C-pattern role** (`marketing-copy-team` copy-editor):++```markdown+**Forbidden**:+- Do NOT rewrite the strategy brief — the brief-strategist's output is the source of truth.+- Do NOT change the message hierarchy from the copywriter's draft.+- Do NOT add new value propositions not in the original brief.++**Mandatory**:+- You MUST preserve the brief's audience, tone, and CTA intent.+- You MUST track every edit as accept/reject so the audit stage can verify provenance.+```++---++## Section 4: Output Schema++### Format++```markdown+## Output Schema++\`\`\`markdown+## Role: <Role Name>++### <Section 1>+- [...]++### <Section 2>+- [...]++### Verdict / Decision / Output+- <enum: BLOCK / SHIP / KICK-BACK / ...>+\`\`\`+```++### Why a schema (not free text)++- **Leader integration depends on parseable structure** — A-pattern Leaders count agreements, B-pattern Leaders compose by slice, C-pattern Leaders check gates. All three need predictable output shapes.+- **Schemas force the role to commit** — a role that returns "here are some thoughts" lets the Leader off the hook. A role that must produce a `Verdict: BLOCK / SIGNIFICANT-RISK / ACCEPTABLE-RISK / LOW-RISK` is forced to take a position.++### Schema design rules++1. Always include a **Verdict / Decision / Output** terminal section that uses an **enum**, not free text. The Leader uses this for routing/integration.+2. Use **JSON** instead of Markdown if the output is consumed programmatically (rare for Teamskills — most consumers are LLMs reading Markdown).+3. Match the schema 1:1 with what `Inline Persona` tells the teammate to produce. Drift between the two = teammate output that doesn't match the schema = Leader integration failure.++---++## Section 5: Inline Persona for Teammate++### Why this section exists++> Most adopting agents do NOT auto-load role files when dispatching teammates. The Leader must extract this section verbatim and inline it into the dispatch prompt. **Without this section, Teamskills do not run on the majority of adopting agents.**++### Format++```markdown+## Inline Persona for Teammate++\`\`\`+ROLE: <Role Name> in a Teamskill.++[1-2 sentences: who you are, what your default mode is]++[1-2 sentences: what you must produce, the Mandatory + Forbidden in plain prose]++INPUTS YOU WILL RECEIVE:+- <input 1>: {INPUT_1_PLACEHOLDER}+- <input 2>: {INPUT_2_PLACEHOLDER}++OUTPUT FORMAT (use exactly this structure):+## Role: <Role Name>+### <Section 1>+- ...+### Verdict+- <enum value>+\`\`\`+```++### Quality rules++1. **Self-contained** — the teammate has no access to the parent context, the role file, the workflow, or the bind file. Everything needed to perform the role must be in this prompt.+2. **Use placeholders** — `{PR_DIFF}`, `{TOPIC}`, `{ANGLE_ASSIGNMENT}`, `{PRIOR_STAGE_OUTPUT}` are filled in by the Leader at dispatch time. Make them obvious.+3. **Reproduce the Output Schema verbatim** — do not paraphrase; the teammate's output must match what the Leader expects.+4. **Keep it < 50 lines** — longer personas indicate the role is doing too much; consider splitting.++---++## Anti-convergence techniques++When 2+ roles in an A-pattern team risk producing similar outputs, apply these techniques:++### Technique 1: Forced theory class assignment++Each role is assigned a **fixed category** at dispatch time. Used in `systematic-debug-team`:++- Hypothesis-generator-1 → "Data/State theories only"+- Hypothesis-generator-2 → "Concurrency/Timing theories only"+- Hypothesis-generator-3 → "Environment/Configuration theories only"++The Inline Persona contains: *"You are restricted to {THEORY_CLASS} hypotheses. Do not propose hypotheses outside this class."*++### Technique 2: Antagonistic mottos++Make each role's Identity motto explicitly contradict its siblings. See the "Bad mottos" table above for what to avoid.++### Technique 3: Different methodologies, same input++Each role applies a **different framework** to the same input:++- Threat-modeler → STRIDE+- Vulnerability-scanner → OWASP Top 10+- Dependency-auditor → CVE database + license audit++The methodology constrains the output shape, preventing convergence.++### Technique 4: Adversarial dispatch order (rare)++For C-patterns with an adversarial gate, dispatch the adversary **after** seeing the prior stage's output, with explicit instruction to disagree. Used in `data-analysis-team` critique-reviewer: *"Your job is to find the analysis's failure modes, not to validate it."*++---++## Gate design (for C-patterns and pipeline stages)++A quality gate sits between two stages and decides whether stage N's output is good enough to pass to stage N+1.++### Gate components++Every gate has 4 parts (declared in `workflow.md` Detailed Steps):++1. **Trigger** — when does the gate run? (Always after stage N completes; sometimes only on certain stage outcomes.)+2. **Pass criteria** — explicit, observable, ideally count-based (e.g., "brief contains all 5 mandatory sections").+3. **Fail action** — kick back to which stage? Retry how many times? Escalate to user when?+4. **Bypass conditions** (optional) — when can the user override the gate?++### Gate examples++**Brief gate** (`marketing-copy-team`, between Stage 1 and Stage 2):++> **Pass criteria**: brief contains audience definition, value proposition, message hierarchy, CTA, success metrics. All 5 sections must be present and ≥3 sentences each.+> **Fail action**: kick back to brief-strategist with the missing sections listed. Max 2 retries; on 3rd failure, surface to user with partial brief and ask how to proceed.++**Data quality gate** (`data-analysis-team`, before Stage 1 starts):++> **Pass criteria**: Data Quality Score (DQS) ≥ 0.7 across completeness, consistency, validity. GO verdict from data-quality-auditor.+> **Fail action** (NO-GO): halt the pipeline. Return DQS report to user with specific defects. Do not allow analysts to start.++### Gate anti-patterns++| Anti-pattern | Symptom | Fix |+|---|---|---|+| "Looks good to me" gate | Subjective; passes everything | Replace with count-based / enum-based criteria |+| Gate without retry policy | Pipeline halts on first failure | Add max retries + escalation rule |+| Gate that the next stage ignores | Stage N+1 starts even on FAIL | `bind.md` must declare "Stage N+1 MUST refuse to run if gate FAIL" |+| Gate redundant with `Boundary` | Forbidden rule in role file + Pass criteria in workflow say the same thing | Pick one — Boundary if it's per-role behavior, gate if it's per-stage transition |++---++## Putting it together: a role file checklist++Before declaring a role file done, verify:++- [ ] First line of `## Identity` is a `> *"..."*` motto (1 sentence, first-person, distinctive POV)+- [ ] Motto is mutually antagonistic with sibling roles in A-patterns / disjoint in B-patterns / non-overlapping in C-patterns+- [ ] `## Success Criteria` has 3–6 observable bullets + a "Focus areas" line+- [ ] `## Boundary` has BOTH `**Forbidden**:` and `**Mandatory**:` blocks+- [ ] `## Output Schema` has a terminal `Verdict / Decision / Output` enum+- [ ] `## Inline Persona for Teammate` is self-contained, uses placeholders, reproduces the schema, < 50 lines+- [ ] No section duplicates content from another section+- [ ] Role file size: ~80–200 lines (significantly more = role doing too much; less = role under-specified)diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/scripts/validate_teamskill.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/scripts/validate_teamskill.pynew file mode 100644index 0000000000..4327889af1--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/scripts/validate_teamskill.py@@ -0,0 +1,537 @@+#!/usr/bin/env python3+"""+validate_teamskill.py — Compliance checker for Teamskills (v0.1 spec).++Usage:+ python validate_teamskill.py <path/to/teamskill-name/>++Exit codes:+ 0 = PASS (no errors; warnings may still print)+ 1 = FAIL (one or more errors)+ 2 = USAGE error (bad arguments, missing PyYAML, etc.)++Requires: PyYAML (pip install pyyaml)++What this script catches (deterministic):+ - 5-file structure (SKILL.md, roles/, workflow.md, bind.md, dependencies.yaml)+ - Frontmatter required fields + types+ - `name` field equals directory name+ - roles/<id>.md exists for every roles[].id; no orphan role files+ - Each role file has the 5 mandatory sections (## Identity / Success Criteria /+ Boundary / Output Schema / Inline Persona for Teammate)+ - Each `## Identity` body's first non-blank line matches motto pattern `> *"..."*`+ - Each `## Boundary` contains both **Forbidden** and **Mandatory** markers+ - SKILL.md body has ## Workflow / ## Roles / ## Files+ - workflow.md has ## Overview / ## Detailed Steps / ## Acceptance Criteria+ and at least one ```mermaid``` block+ - bind.md has ## Resource Constraints / ## Behavioral Constraints / ## Failure Handling+ - dependencies.yaml has both `skills:` and `tools:` keys (even if empty)+ - Every roles[].skills / roles[].tools in SKILL.md appears in dependencies.yaml++What this script does NOT catch (judgment calls — see reference/compliance-checklist.md):+ - Whether mottos are mutually antagonistic (anti-convergence quality)+ - Whether Boundary lists really cover all sibling territories+ - Whether bind.md numbers actually match the workflow's needs+ - Whether the Teamskill is even justified vs a single-agent skill (Stage 0)+"""++from __future__ import annotations++import logging+import sys+import re+from pathlib import Path+from typing import Any++logging.basicConfig(level=logging.INFO, format="%(message)s")+logger = logging.getLogger(__name__)++try:+ import yaml+except ImportError:+ logger.info("[USAGE ERROR] PyYAML is required. Install with: pip install pyyaml")+ sys.exit(2)+++# ---------------------------------------------------------------------------+# Result accumulator+# ---------------------------------------------------------------------------++class Report:+ def __init__(self) -> None:+ self.errors: list[str] = []+ self.warnings: list[str] = []++ def err(self, file: str, msg: str) -> None:+ self.errors.append(f" [ERROR] {file}: {msg}")++ def warn(self, file: str, msg: str) -> None:+ self.warnings.append(f" [WARN] {file}: {msg}")++ def passed(self) -> bool:+ return not self.errors++ def emit(self) -> None:+ if self.errors:+ logger.info("\nERRORS:")+ for e in self.errors:+ logger.info(e)+ if self.warnings:+ logger.info("\nWARNINGS:")+ for w in self.warnings:+ logger.info(w)+ if self.passed():+ logger.info("\n[PASS] %s warning(s), 0 error(s).", len(self.warnings))+ else:+ logger.info(+ "\n[FAIL] %s error(s), %s warning(s).",+ len(self.errors),+ len(self.warnings),+ )+++# ---------------------------------------------------------------------------+# Frontmatter + section parsing helpers+# ---------------------------------------------------------------------------++FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n(.*)$", re.DOTALL)+++def split_frontmatter(text: str) -> tuple[dict[str, Any] | None, str]:+ """Split a Markdown file into (frontmatter_dict, body_str)."""+ m = FRONTMATTER_RE.match(text)+ if not m:+ return None, text+ try:+ fm = yaml.safe_load(m.group(1)) or {}+ except yaml.YAMLError as e:+ raise ValueError(f"frontmatter YAML parse error: {e}") from e+ return fm, m.group(2)+++def find_h2_sections(body: str) -> dict[str, int]:+ """Return mapping of `## Section Title` -> line number (1-indexed)."""+ sections: dict[str, int] = {}+ for i, line in enumerate(body.splitlines(), 1):+ m = re.match(r"^##\s+(.+?)\s*$", line)+ if m:+ sections[m.group(1).strip()] = i+ return sections+++def section_body(body: str, header: str) -> str | None:+ """Return the body text under `## <header>` up to the next `## ` heading or EOF."""+ lines = body.splitlines()+ start: int | None = None+ for i, line in enumerate(lines):+ if re.match(rf"^##\s+{re.escape(header)}\s*$", line):+ start = i + 1+ break+ if start is None:+ return None+ end = len(lines)+ for j in range(start, len(lines)):+ if re.match(r"^##\s+\S", lines[j]):+ end = j+ break+ return "\n".join(lines[start:end])+++# ---------------------------------------------------------------------------+# Per-file validators+# ---------------------------------------------------------------------------++def validate_skill_md(path: Path, report: Report) -> tuple[dict | None, list[str]]:+ """Validate <root>/SKILL.md. Returns (frontmatter, role_ids_declared)."""+ if not path.exists():+ report.err("SKILL.md", "missing — required by the 5-file structure")+ return None, []++ text = path.read_text(encoding="utf-8")++ try:+ fm, body = split_frontmatter(text)+ except ValueError as e:+ report.err("SKILL.md", str(e))+ return None, []++ if fm is None:+ report.err("SKILL.md", "missing YAML frontmatter (--- ... ---)")+ return None, []++ # Required frontmatter fields+ for field in ("name", "description", "version", "kind", "roles"):+ if field not in fm:+ report.err("SKILL.md", f"frontmatter missing required field `{field}`")++ if fm.get("kind") != "team-skill":+ report.err("SKILL.md", f"frontmatter `kind` must be `team-skill` (got: {fm.get('kind')!r})")++ # name == directory name+ dir_name = path.parent.name+ if fm.get("name") != dir_name:+ report.err(+ "SKILL.md",+ f"frontmatter `name` ({fm.get('name')!r}) must equal directory name ({dir_name!r})",+ )++ # description discipline (the trigger blob the model reads BEFORE loading the body)+ desc = fm.get("description")+ if isinstance(desc, str) and desc.strip():+ desc_chars = len(desc.strip())+ desc_lines = [ln for ln in desc.strip().splitlines() if ln.strip()]+ if desc_chars > 500:+ report.warn(+ "SKILL.md",+ f"description is {desc_chars} chars — HARD CAP is 500 (platform limit: 1024). "+ "Strip synonym enumeration / scope thresholds / Stage-0 rationale; see "+ "../teamskill-creator/SKILL.md Stage 5 for the discipline rules.",+ )+ if len(desc_lines) > 4:+ report.warn(+ "SKILL.md",+ f"description has {len(desc_lines)} non-blank lines — HARD CAP is 4. "+ "Use 3-line structure: WHAT / WHEN / NOT.",+ )+ if re.search(r"^\s*Triggers\s*:", desc, re.MULTILINE | re.IGNORECASE):+ report.warn(+ "SKILL.md",+ "description contains a `Triggers:` line — DEPRECATED. Merge synonym phrases "+ "into one natural-language `Use when` sentence; semantic match handles variants.",+ )++ # roles[] structure+ role_ids: list[str] = []+ roles = fm.get("roles", [])+ if not isinstance(roles, list) or not roles:+ report.err("SKILL.md", "frontmatter `roles` must be a non-empty list")+ else:+ for i, role in enumerate(roles):+ if not isinstance(role, dict):+ report.err("SKILL.md", f"roles[{i}] must be an object")+ continue+ if "id" not in role:+ report.err("SKILL.md", f"roles[{i}] missing required field `id`")+ else:+ role_ids.append(role["id"])+ if "purpose" not in role:+ report.err("SKILL.md", f"roles[{i}] (id={role.get('id')!r}) missing required field `purpose`")+ else:+ # Per-role purpose is a 1-line summary; details go in roles/<id>.md+ purpose = role.get("purpose") or ""+ if isinstance(purpose, str) and len(purpose) > 150:+ report.warn(+ "SKILL.md",+ f"roles[{i}] (id={role.get('id')!r}) `purpose` is {len(purpose)} "+ f"chars — HARD CAP is 150. Move detail into roles/{role.get('id')}.md.",+ )++ # Check if all roles have empty skills and tools (suggests auto-matching was skipped)+ if isinstance(roles, list) and roles:+ all_empty = all(+ (not role.get("skills")) and (not role.get("tools"))+ for role in roles+ if isinstance(role, dict)+ )+ if all_empty and len(role_ids) > 0:+ report.warn(+ "SKILL.md",+ "all roles have empty `skills` and `tools` — was Stage 2 auto-matching run? "+ "Empty lists are valid only when the local scan confirms no matches. "+ "Run the auto-matching sub-step in Stage 2 before declaring no dependencies.",+ )++ # Body required sections+ sections = find_h2_sections(body)+ for required in ("Workflow", "Roles", "Files"):+ if required not in sections:+ report.err("SKILL.md", f"body missing required section `## {required}`")++ # Anti-pattern: redundant sections that the description / workflow.md already cover+ for deprecated in ("When to Use", "Anti-Patterns", "Output Format"):+ if deprecated in sections:+ report.warn(+ "SKILL.md",+ f"body contains `## {deprecated}` which is already covered by `description` "+ "or `workflow.md` — remove to avoid duplication",+ )++ # Anti-pattern: mermaid in SKILL.md body (redundant with workflow.md)+ if re.search(r"```mermaid", body):+ report.warn(+ "SKILL.md",+ "body contains a ```mermaid``` block — keep mermaid only in workflow.md to "+ "avoid duplication",+ )++ return fm, role_ids+++def validate_role_file(path: Path, role_id: str, report: Report) -> dict[str, list[str]]:+ """Validate one roles/<id>.md.++ Returns extracted role-level skills/tools (currently unused — declared in+ SKILL.md frontmatter).+ """+ file_label = f"roles/{role_id}.md"+ if not path.exists():+ report.err(+ file_label,+ f"missing — required because SKILL.md frontmatter declares roles[].id = {role_id!r}",+ )+ return {}++ text = path.read_text(encoding="utf-8")+ sections = find_h2_sections(text)++ required_sections = (+ "Identity",+ "Success Criteria",+ "Boundary",+ "Output Schema",+ "Inline Persona for Teammate",+ )+ for s in required_sections:+ if s not in sections:+ report.err(file_label, f"missing required section `## {s}`")++ # Identity must start with a 1-line motto: > *"..."*+ identity_body = section_body(text, "Identity")+ if identity_body is not None:+ first_nonblank = next((ln.strip() for ln in identity_body.splitlines() if ln.strip()), "")+ # Accept either > *"..."* or > *'...'* (italic blockquote with quotes)+ motto_pattern = re.compile(r'^>\s*\*["\'].+["\']\*\s*$')+ if not motto_pattern.match(first_nonblank):+ report.err(+ file_label,+ "## Identity first non-blank line must be a 1-line motto in "+ f"`> *\"...\"*` format. Got: {first_nonblank[:80]!r}",+ )++ # Boundary must contain BOTH Forbidden and Mandatory markers+ # Accept common variations: **Forbidden**, **禁止**, **Forbidden actions**, etc.+ boundary_body = section_body(text, "Boundary")+ if boundary_body is not None:+ has_forbidden = re.search(r"\*\*(Forbidden|禁止)\*\*", boundary_body) is not None+ has_mandatory = re.search(r"\*\*(Mandatory|必须|必做)\*\*", boundary_body) is not None+ if not has_forbidden:+ report.err(file_label, "## Boundary missing `**Forbidden**` (or `**禁止**`) block")+ if not has_mandatory:+ report.err(+ file_label,+ "## Boundary missing `**Mandatory**` (or `**必须**` / `**必做**`) block",+ )++ # Inline Persona must be non-trivially long (sanity check — empty section is the+ # most common authoring error)+ persona_body = section_body(text, "Inline Persona for Teammate")+ if persona_body is not None and len(persona_body.strip()) < 100:+ report.warn(+ file_label,+ f"## Inline Persona for Teammate is suspiciously short ({len(persona_body.strip())} chars). "+ "It must be a self-contained pasteable prompt — see reference/role-design.md.",+ )++ # Anti-pattern: section names that should be merged into the 5 mandatory sections+ for deprecated in ("Mindset", "Priorities", "Inspection Process", "MUST-Find Rule", "Inline Persona for Sub-Agent"):+ if deprecated in sections:+ if deprecated == "Inline Persona for Sub-Agent":+ report.err(+ file_label,+ "uses old `## Inline Persona for Sub-Agent` heading — rename to "+ "`## Inline Persona for Teammate`",+ )+ else:+ report.warn(+ file_label,+ f"contains `## {deprecated}` — merge it into one of the 5 mandatory "+ "sections (Identity / Success Criteria / Boundary / Output Schema / "+ "Inline Persona for Teammate)",+ )++ return {}+++def validate_workflow_md(path: Path, report: Report) -> None:+ if not path.exists():+ report.err("workflow.md", "missing — required by the 5-file structure")+ return++ text = path.read_text(encoding="utf-8")+ sections = find_h2_sections(text)++ for required in ("Overview", "Detailed Steps", "Acceptance Criteria"):+ if required not in sections:+ report.err("workflow.md", f"missing required section `## {required}`")++ # Mermaid is required in workflow.md — the primary expression difference from single-agent skills+ if not re.search(r"```mermaid", text):+ report.err(+ "workflow.md",+ "missing ```mermaid``` block — workflow.md must contain at least one mermaid diagram",+ )+++def validate_bind_md(path: Path, report: Report) -> None:+ if not path.exists():+ report.err("bind.md", "missing — required by the 5-file structure")+ return++ text = path.read_text(encoding="utf-8")+ sections = find_h2_sections(text)++ for required in ("Resource Constraints", "Behavioral Constraints", "Failure Handling"):+ if required not in sections:+ report.err("bind.md", f"missing required section `## {required}`")++ # Resource Constraints should mention the 3 baseline items+ rc_body = section_body(text, "Resource Constraints")+ if rc_body is not None:+ for required_item in ("max_parallel_teammates", "total_wall_clock_budget", "total_token_budget"):+ if required_item not in rc_body:+ report.warn(+ "bind.md",+ f"## Resource Constraints does not mention `{required_item}` — "+ "recommended as a baseline item",+ )+++def validate_dependencies_yaml(path: Path, report: Report) -> dict[str, list[str]]:+ """Returns {'skills': [names], 'tools': [names]} for cross-file consistency check."""+ if not path.exists():+ report.err(+ "dependencies.yaml",+ "missing — required by the 5-file structure (write `skills: []` / `tools: []` "+ "if no deps)",+ )+ return {"skills": [], "tools": []}++ text = path.read_text(encoding="utf-8")++ try:+ data = yaml.safe_load(text) or {}+ except yaml.YAMLError as e:+ report.err("dependencies.yaml", f"YAML parse error: {e}")+ return {"skills": [], "tools": []}++ if not isinstance(data, dict):+ report.err("dependencies.yaml", "root must be a mapping with `skills` and `tools` keys")+ return {"skills": [], "tools": []}++ declared = {"skills": [], "tools": []}++ for segment in ("skills", "tools"):+ if segment not in data:+ report.err("dependencies.yaml", f"missing required `{segment}:` segment (write `{segment}: []` if empty)")+ continue++ entries = data[segment]+ if entries is None:+ entries = []+ if not isinstance(entries, list):+ report.err("dependencies.yaml", f"`{segment}:` must be a list (or `[]`)")+ continue++ required_fields = {+ "skills": ("name", "source", "required", "purpose"),+ "tools": ("name", "required", "purpose"),+ }[segment]++ for i, entry in enumerate(entries):+ if not isinstance(entry, dict):+ report.err("dependencies.yaml", f"{segment}[{i}] must be an object")+ continue+ for field in required_fields:+ if field not in entry:+ report.err(+ "dependencies.yaml",+ f"{segment}[{i}] (name={entry.get('name')!r}) missing required field "+ f"`{field}`",+ )+ if segment in declared and "name" in entry:+ declared[segment].append(entry["name"])++ return declared+++# ---------------------------------------------------------------------------+# Cross-file consistency+# ---------------------------------------------------------------------------++def cross_check_skills_tools(skill_fm: dict, declared: dict[str, list[str]], report: Report) -> None:+ """Every roles[].skills / roles[].tools in SKILL.md must appear in dependencies.yaml."""+ for role in skill_fm.get("roles", []):+ if not isinstance(role, dict):+ continue+ role_id = role.get("id", "?")+ for kind, segment in (("skills", "skills"), ("tools", "tools")):+ for item in role.get(kind, []) or []:+ if item not in declared[segment]:+ report.err(+ "dependencies.yaml",+ f"`{item}` is declared in SKILL.md `roles[id={role_id!r}].{kind}` "+ f"but missing from `{segment}:` segment",+ )+++def check_orphan_role_files(roles_dir: Path, declared_role_ids: list[str], report: Report) -> None:+ if not roles_dir.exists():+ return+ for f in roles_dir.glob("*.md"):+ role_id = f.stem+ if role_id not in declared_role_ids:+ report.warn(+ "roles/",+ f"orphan file `roles/{f.name}` — not declared in SKILL.md frontmatter `roles[]`",+ )+++# ---------------------------------------------------------------------------+# Main+# ---------------------------------------------------------------------------++def validate(root: Path) -> int:+ if not root.exists() or not root.is_dir():+ logger.info("[USAGE ERROR] %s is not a directory", root)+ return 2++ logger.info("Validating Teamskill: %s\n", root.resolve())++ report = Report()++ # 1. SKILL.md+ skill_fm, role_ids = validate_skill_md(root / "SKILL.md", report)++ # 2. roles/<id>.md+ roles_dir = root / "roles"+ if not roles_dir.exists():+ report.err("roles/", "directory missing — required by the 5-file structure")+ else:+ for role_id in role_ids:+ validate_role_file(roles_dir / f"{role_id}.md", role_id, report)+ check_orphan_role_files(roles_dir, role_ids, report)++ # 3. workflow.md+ validate_workflow_md(root / "workflow.md", report)++ # 4. bind.md+ validate_bind_md(root / "bind.md", report)++ # 5. dependencies.yaml + cross-check+ declared = validate_dependencies_yaml(root / "dependencies.yaml", report)+ if skill_fm is not None:+ cross_check_skills_tools(skill_fm, declared, report)++ report.emit()+ return 0 if report.passed() else 1+++def main() -> int:+ if len(sys.argv) != 2:+ logger.info(__doc__)+ return 2+ return validate(Path(sys.argv[1]))+++if __name__ == "__main__":+ sys.exit(main())diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/templates/SKILL.md.template b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/templates/SKILL.md.templatenew file mode 100644index 0000000000..18b2bf756b--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/templates/SKILL.md.template@@ -0,0 +1,99 @@+---+name: <teamskill-name>+description: |+ <One-line WHAT: this Teamskill does X via N-role pattern Y. e.g., "3-role adversarial PR review (Reviewer + Critic + Architect) that surfaces inter-role conflicts instead of papering over them">.+ Use when <one-line WHEN: the natural-language situation that should trigger — do NOT enumerate synonym phrases; semantic match handles variants>.+ Do NOT use for <one-line NOT: explicit non-cases that prevent over-firing on adjacent skills>.+version: "0.1"+kind: team-skill+roles:+ - id: <role-id-1>+ purpose: <≤150 chars HARD CAP: 1-line role responsibility — what this role does and why. Detail belongs in roles/<id>.md, not here>+ skills: [<dependent-skill-name>] # populated from Stage 2 auto-matching; mirror in dependencies.yaml+ tools: [<tool-name>] # populated from Stage 2 auto-matching; mirror in dependencies.yaml+ - id: <role-id-2>+ purpose: <...>+ skills: [] # [] = Stage 2 auto-matching confirmed no skill matches for this role+ tools: []+ - id: <role-id-3>+ purpose: <...>+---++# <Teamskill Display Name>++<1-2 sentences: an in-context introduction for an Agent that has already triggered this skill. Different from `description` (which gates the trigger). State the team's pattern (parallel adversarial / sequential pipeline / mixed) and the single failure mode it solves.>++## Workflow++<Describe the protocol in natural language. Use numbered steps. Step 0 MUST be dependency pre-flight.>++0. **Pre-flight: check dependencies** — read [dependencies.yaml](dependencies.yaml) and verify.+ Report missing items: `required: true` = likely fails without it; `required: false` = degraded but functional. **User decides** whether to proceed.+ The team can run on inline-persona-only mode if all skills are missing.+ Note: dependencies were populated during authoring via Stage 2 auto-matching (local scan) and optional post-generation community enrichment. Each entry's `source` field indicates origin (`local` or community URL).++1. **<Step name>** — <executor (Leader / role-id) / input / action>. <Conditions, links to+ detail files: see [bind.md](bind.md) § <Section> for limits, see [workflow.md](workflow.md)+ for the full step.>++2. **<Step name>** — <...>++3. **<Step name>** — <...>++4. **Final: emit <Report Name>** — <what the report contains>. <Decision rule for any+ ambiguity, e.g., "Leader surfaces contradictions verbatim, never mediates".>++## Roles++| id | Purpose | When dispatched | Input | Key dependencies | Role file |+|---|---|---|---|---|---|+| <role-id-1> | <1-line purpose> | <every run / on condition X / parallel with Y> | <what this role receives> | <skill / tool> | [roles/<role-id-1>.md](roles/<role-id-1>.md) |+| <role-id-2> | <...> | <...> | <...> | <...> | [roles/<role-id-2>.md](roles/<role-id-2>.md) |+| <role-id-3> | <...> | <...> | <...> | <...> | [roles/<role-id-3>.md](roles/<role-id-3>.md) |++> Before dispatching each teammate, read the corresponding role file and extract the+> `## Inline Persona for Teammate` section — paste it directly into the dispatch prompt.+> Most adopting agents do NOT auto-load role files for teammates.++## Files++| File | What it contains | When to read |+|---|---|---|+| [workflow.md](workflow.md) | Mermaid diagram, step-by-step protocol, integration rules, Final Report format | Before first dispatch — the complete playbook |+| [bind.md](bind.md) | Resource limits, behavioral constraints, failure handling and degraded modes | When hitting limits, handling failures, or needing degraded-mode rules |+| [roles/\*.md](roles/) | Per-role identity, success criteria, output schema, Inline Persona for Teammate | Before dispatching each teammate — extract Inline Persona |+| [dependencies.yaml](dependencies.yaml) | External skills and tools required to run | **Startup** — verify deps, report missing items, user decides go/no-go |++<!--+TEMPLATE NOTES (delete before publishing):++1. `description` is a TRIGGER read by the model BEFORE loading the body.+ HARD RULES (the validator enforces these):+ - ≤ 4 lines, ≤ 500 chars total.+ - 3-line structure only: WHAT / WHEN / NOT. Do NOT add a separate `Triggers:` line.+ - NO synonym enumeration. Modern semantic match handles "评审 PR / review this PR /+ team review / 多角色评审" from a single natural sentence. Listing 5+ phrases+ wastes tokens and signals to the validator that the WHAT line is unclear.+ - NO scope thresholds with numbers (e.g. ">200 LOC"). Those belong in bind.md.+ - NO Stage 0 justification rationale (e.g. "replaces the failure mode where...").+ That belongs in the body intro paragraph.+ Calibration benchmark: see ../SKILL.md frontmatter for a compliant example.++2. The first heading paragraph below the frontmatter is for an ALREADY-TRIGGERED Agent+ (more room — 1-2 sentences stating pattern + the failure mode this team solves).+ Different consumer + different timing from `description` — both are needed.++3. SKILL.md body MUST contain `## Workflow` + `## Roles` + `## Files`.+ Do NOT add `## When to Use` (already covered by description).+ Do NOT add `## Anti-Patterns` (already covered by description's "Do NOT use for").+ Do NOT add a mermaid diagram here — it belongs only in workflow.md.++4. The Roles table should include "When dispatched" / "Input" / "Key dependencies"+ columns to augment the structured `roles[]` frontmatter with runtime info.++5. Step 0 (dependency pre-flight) is MANDATORY. The Agent reports → user decides go/no-go.+ The Agent does NOT make the go/no-go call itself.++6. Per-role `purpose:` field has a ≤150-char HARD CAP (validator enforces).+ Detail goes in roles/<id>.md, not here.+-->diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/templates/bind.md.template b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/templates/bind.md.templatenew file mode 100644index 0000000000..df05c52576--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/templates/bind.md.template@@ -0,0 +1,79 @@+# Execution Guardrails++## Resource Constraints++| Item | Limit | Reason |+|---|---|---|+| `max_parallel_teammates` | <e.g., 3> | <e.g., matches the parallel fan-out in workflow.md mermaid> |+| `total_wall_clock_budget` | <e.g., 10 min> | <e.g., upper bound for one full run including all sequential stages> |+| `total_token_budget` | <e.g., 200k tokens> | <e.g., budget across all roles; prevents one teammate from exhausting context> |+| `<per_role_token_budget>` (optional) | <e.g., 60k per role> | <only if asymmetric — e.g., the curator role gets more than analysts> |+| `<per_role_wall_clock>` (optional) | <e.g., 3 min per role> | <only if asymmetric> |+| `debate_rounds` (Debate pattern only) | <e.g., 1–2> | Cross-exam round count; each round ≈ linear token growth |++## Behavioral Constraints++<Team-level rules — distinct from per-role Boundary which constrains a single role.+Behavioral Constraints govern what Leader and the team-as-a-whole must / must not do.>++- **Leader-as-orchestrator only**: the Leader dispatches teammates and integrates outputs.+ The Leader does NOT write findings, run analyses, or substitute any role's work.+- <Pattern-specific isolation rule:+ A-pattern: "Teammates MUST NOT see each other's output during their work — isolation is the value of adversarial review."+ C-pattern: "Each stage MUST NOT modify upstream stage outputs — only enhance / annotate."+ B-pattern: "Each parallel role works on its assigned slice ONLY — slices are dispatch-time fixed, not negotiated."+ Debate-pattern: "Round 1 teammates are isolated (no cross-visibility). Round 2+ teammates receive prior-round outputs from all other roles (mutual visibility). The Teamskill declares who sees whose output at which phase; how it is delivered is a framework-level choice with recommended preference: (1) direct peer-to-peer exchange; (2) shared blackboard; (3) Leader-relay as fallback.">+- **Contradiction handling**: when roles disagree, Leader surfaces contradictions verbatim+ in the Final Report. Leader NEVER mediates / picks a winner / averages opinions.+ Resolution is the human user's call.+- <Domain-specific behavioral rule, e.g., "no live-system testing without authorization"+ for security-audit-team, "blameless language only" for incident-response-team, etc.>++## Failure Handling++### (a) Teammate failure++| Failure mode | Response |+|---|---|+| Teammate timeout | Retry once (single retry only). On 2nd timeout, mark role's section in the Final Report as `[ROLE MISSING — teammate timed out]` and proceed with the remaining roles' outputs. |+| Malformed teammate output (does not match Output Schema) | Re-dispatch with the schema explicitly inlined and a "your previous output was malformed" preamble. Max 1 retry. On 2nd malformed output, mark as `[ROLE MISSING — malformed output]` and proceed. |+| Teammate refuses (e.g., claims it cannot find anything for an A-pattern adversarial role) | Re-dispatch with the role's `Boundary > Mandatory` rule restated. If it still refuses, mark as `[ROLE INCONCLUSIVE]` and surface verbatim in the report. |++### (b) Input over-scale degradation++| Trigger condition | Degraded mode |+|---|---|+| <e.g., diff > 2000 LOC> | <e.g., fall back to single-role mode using only the most critical role; warn the user before starting> |+| <e.g., topic too narrow for B-pattern decomposition> | <e.g., reduce to 1 role; warn user that the team's value is reduced> |+| <e.g., critical dependency missing per pre-flight> | <e.g., user already chose to proceed in Step 0 — record the missing dep in the Final Report> |++### Escalation rules++- If 50%+ of roles return `[ROLE MISSING]`, the run is **FAILED** — emit a partial report with explicit "FAILED: insufficient role coverage" header and surface to user.+- If `total_wall_clock_budget` is exceeded, halt all in-flight teammates, emit whatever partial outputs exist, and tag the report `INCOMPLETE: budget exceeded`.+- If `total_token_budget` is exceeded mid-run, halt new dispatches, allow in-flight to complete, emit partial report tagged `INCOMPLETE: token budget exceeded`.++<!--+TEMPLATE NOTES (delete before publishing):++1. Resource Constraints MUST contain at least:+ - max_parallel_teammates (matches workflow.md fan-out)+ - total_wall_clock_budget (upper bound for one run)+ - total_token_budget (across all roles)+ Add per-role limits ONLY if asymmetric (most teams are symmetric — keep it simple).++2. Behavioral Constraints govern THE TEAM as a whole.+ Per-role rules belong in roles/<id>.md `## Boundary`.+ Heuristic: if the rule mentions the Leader or "all teammates", it goes here.++3. Failure Handling MUST cover BOTH (a) teammate failure AND (b) input overscale.+ Most authoring errors omit (b). Add concrete numeric triggers for (b).++4. The "Escalation rules" subsection is optional but useful — it covers what happens+ when multiple failures stack on top of each other.++5. Heuristic for what goes in bind.md vs workflow.md:+ - Numbers (budgets, retry counts, thresholds) → bind.md+ - Exception paths and degraded modes → bind.md+ - Main flow steps → workflow.md+-->diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/templates/dependencies.yaml.template b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/templates/dependencies.yaml.templatenew file mode 100644index 0000000000..846a6ee33d--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/templates/dependencies.yaml.template@@ -0,0 +1,52 @@+# dependencies.yaml — Teamskill startup dependency check+#+# Agent reads this file in SKILL.md Workflow Step 0 (pre-flight).+# Each entry is checked. Results are reported to the user, who decides go/no-go.+#+# THIS FILE IS POPULATED FROM STAGE 2 AUTO-MATCHING RESULTS.+# Do NOT fill it from scratch — it codifies what was discovered during the+# local scan in Stage 2 (and optional post-generation community enrichment).+#+# RULES:+# - Both `skills:` and `tools:` segments are MANDATORY (write `[]` if empty).+# - Empty lists are valid ONLY when the auto-matching scan confirms no matches+# — they signal "checked, confirmed none", which is different from "never looked".+# - Every entry in `roles[].skills` and `roles[].tools` (in SKILL.md frontmatter)+# MUST appear here. The validator script enforces this consistency.+# - `purpose` is shown to the user when the dep is missing — write user-facing+# prose explaining the consequence, not internal jargon.++skills:+ # --- Local skills (discovered in Stage 2 auto-matching) ---+ - name: <skill-name-1>+ source: local # found in .claude/skills/ or .cursor/skills/ locally+ required: true # true = run will likely fail without; false = degraded mode.+ purpose: <one-line user-facing explanation of what this skill does for the team>++ # --- Community skills (added via post-generation community enrichment, user-authorized) ---+ - name: <skill-name-2>+ source: "https://github.com/<org>/<repo>" # community URL where this skill was installed from+ required: false+ purpose: <e.g., "Visualize cross-module dependency impact (skipped if unavailable)">++ # Use `skills: []` ONLY after Stage 2 auto-matching confirms no skill matches for any role.++tools:+ # --- Local tools (probed in Stage 2 auto-matching via `where`/`which`) ---+ - name: <tool-name-1> # e.g., gh, rg, python, jq, curl, docker+ required: true+ purpose: <one-line user-facing explanation>++ - name: <tool-name-2>+ required: false+ purpose: <one-line user-facing explanation>++ # Use `tools: []` ONLY after Stage 2 auto-matching confirms no tool matches for any role.++# EXAMPLES OF VALID EMPTY SEGMENTS (after auto-matching yields no matches):+#+# skills: []+# tools: []+#+# An empty list signals "checked, confirmed no dependency of this type" — DIFFERENT+# from omitting the segment, which is a spec violation.diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/templates/role.md.template b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/templates/role.md.templatenew file mode 100644index 0000000000..e6db5ac0fd--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/templates/role.md.template@@ -0,0 +1,106 @@+# Role: <Display Name>++## Identity++> *"<One-sentence first-person motto that crystallizes this role's POV. Must be mutually antagonistic with sibling roles in A-patterns / non-overlapping in B-patterns / stage-distinct in C-patterns. Examples: 'I am trying to break this code in production.' / 'I will refuse the deal if even one term smells wrong.' / 'I am the data — I will tell you what is true even if it disappoints you.'>"*++<Optional 0-2 paragraphs after the motto. Use them to: (a) name the methodology this+role applies (STRIDE / OWASP / SCQA / 5-Whys / etc.); (b) declare the role's default+mode (skeptical / generous / adversarial / clinical); (c) explain when this POV adds+value. DO NOT repeat Success Criteria here — that's the next section.>++## Success Criteria++- <Concrete observable deliverable 1 — a reviewer can check ✓/✗ against it>+- <Concrete observable deliverable 2>+- <Concrete observable deliverable 3>+- <...>++**Focus areas**: <comma-separated list of what this role should prioritize examining,+e.g., "error paths, retry logic, concurrent access, downstream consumers, OWASP-relevant+patterns, implicit type conversions, resource leaks">.++## Boundary++<!-- Anchor keywords: use **Forbidden** or **禁止**, and **Mandatory** or **必须**/**必做** — the validator matches these. -->+**Forbidden** (prevent role overlap):+- Do NOT <thing that another role does — name the sibling role explicitly>+- Do NOT <thing that drifts upstream/downstream in the pipeline>+- Do NOT <thing that lets the role escape its assigned slice / methodology>++**Mandatory**:+- You MUST <thing the role tends to skip when it sees nothing obvious>.+ <Add 1 sentence on what to do if you find nothing — usually "look harder".>+- You MUST <output discipline that the schema enforces>.+- You MUST <discipline specific to this role's methodology>.++## Output Schema++```markdown+## Role: <Display Name>++### <Section 1 — e.g., Findings / Hypotheses / Recommendations>+- <[item] [severity / category / confidence]>+- <...>++### <Section 2 — e.g., Evidence / Citations / Caveats>+- <...>++### <Verdict / Decision / Output>+- <ENUM: e.g., BLOCK / SIGNIFICANT-RISK / ACCEPTABLE-RISK / LOW-RISK>+```++## Inline Persona for Teammate++```+ROLE: <Display Name> in a Teamskill.++You are <1-sentence in-character description matching the Identity motto>.+<1-2 sentences: your default mode, what you prioritize examining>.++You MUST <Mandatory rule 1>.+You MUST <Mandatory rule 2>.+You MUST NOT <Forbidden rule 1>.+You MUST NOT <Forbidden rule 2>.++INPUTS YOU WILL RECEIVE:+- <input 1>: {INPUT_1_PLACEHOLDER}+- <input 2>: {INPUT_2_PLACEHOLDER}+- <input 3, optional>: {INPUT_3_PLACEHOLDER}++OUTPUT FORMAT (use exactly this structure, no preamble, no postscript):++## Role: <Display Name>++### <Section 1>+- <bullet point per finding>++### <Section 2>+- <bullet point per item>++### <Verdict / Decision / Output>+- <ENUM value from: A | B | C | D>+```++<!--+TEMPLATE NOTES (delete before publishing):++1. The motto on the FIRST LINE of `## Identity` is the #1 anti-convergence mechanism.+ Format MUST be: > *"single-sentence first-person motto."*+ Without it, prose Identity sections cause sibling roles to converge in output.++2. `## Boundary` MUST contain BOTH a Forbidden block and a Mandatory block.+ Accepted anchor keywords: **Forbidden** / **禁止**, **Mandatory** / **必须** / **必做**.+ Forbidden alone → roles output "looks fine".+ Mandatory alone → roles overlap with siblings.++3. `## Inline Persona for Teammate` MUST be self-contained — the teammate has NO access+ to this role file, the team SKILL.md, the workflow, or the bind file. Everything the+ teammate needs to play the role MUST be in this prompt.++4. `## Output Schema` and the OUTPUT FORMAT inside Inline Persona MUST match. Drift+ between them = teammate output that doesn't match Leader's parser = integration failure.++5. Recommended file size: 80-200 lines. Significantly larger = role doing too much+ (split into 2 roles). Significantly smaller = role under-specified.+-->diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/templates/workflow.md.template b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/templates/workflow.md.templatenew file mode 100644index 0000000000..5461fd4bfa--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/teamskill-creator/templates/workflow.md.template@@ -0,0 +1,138 @@+# Workflow: <One-line task pipeline summary>++## Overview++```mermaid+graph LR+ A[Leader: Pre-flight + Context] --> B{Input scale OK?}+ B -- No --> C[Degraded Mode<br/>see bind.md]+ B -- Yes --> D[role-id-1]+ B -- Yes --> E[role-id-2]+ B -- Yes --> F[role-id-3]+ D --> G[Leader: Integrate]+ E --> G+ F --> G+ G --> H[Final Report]+```++<Replace the diagram above with one that matches your team's pattern:++- A-pattern (parallel adversarial): all roles fan out from Leader, then fan in to Integrate.+- B-pattern (parallel decomposition): same shape as A; integration node composes by slice.+- C-pattern (specialization pipeline): linear chain `Leader → Stage 1 → gate → Stage 2 → gate → ...`+- Mixed: combine; e.g., C+A places an adversarial fan-out inside one stage.+- Debate pattern (B → Cross-exam → C): Round1 fan-out (isolated) → relay node+ (visibility switch point) → Round2 fan-out (mutual visibility) → synthesizer → final.+ The relay node represents WHERE visibility changes, not HOW — delivery mechanism is+ a framework-level choice with recommended preference: (1) direct peer-to-peer;+ (2) shared blackboard; (3) Leader-relay as fallback.+ For multi-round debate, annotate `×N rounds (see bind.md)` on the relay→Round2 edge+ instead of duplicating the fan-out block.++Include decision diamonds for degraded mode triggers (linked to bind.md § Failure Handling).+Include retry loops (back-edges) if roles can be re-dispatched on failure.>++<If Debate pattern, keep the following note (delete this instruction line, keep the content):>++- **Inter-member communication preference** (Debate pattern): this Teamskill declares **who sees whose output at which phase** (visibility semantics). Frameworks SHOULD implement the highest-priority delivery mechanism they support: **(1) direct peer-to-peer exchange** (most efficient) > **(2) shared blackboard** > **(3) Leader-relay** (fallback). See [bind.md](bind.md) § Behavioral Constraints for phase-scoped visibility rules.++## Detailed Steps++### Step 0 — Pre-flight: dependency check++- **Executor**: Leader+- **Input**: [dependencies.yaml](dependencies.yaml)+- **Action**: verify each `skills[]` and `tools[]` entry is available+- **Output**: pre-flight report to user+- **Quality gate**: user decides go/no-go on missing items (Agent does NOT auto-decide)++### Step 1 — <Step name>++- **Executor**: <Leader / role-id>+- **Input**: <what this step receives>+- **Action**: <what happens, in 1-3 sentences>+- **Output**: <structured deliverable name + brief shape>+- **Serial / Parallel**: <if parallel, list which roles run together>+- **Quality gate**: <pass criteria — count-based or enum-based, never "looks good"; fail action — kick back to which step / how many retries / when to escalate>++### Step 2 — <Step name>++- **Executor**: <...>+- **Input**: <...>+- **Action**: <...>+- **Output**: <...>+- **Serial / Parallel**: <...>+- **Quality gate**: <...>++### Step 3 — <Step name>++- **Executor**: <...>+- **Input**: <...>+- **Action**: <...>+- **Output**: <...>+- **Serial / Parallel**: <...>+- **Quality gate**: <...>++### Step N — Final: emit <Report Name>++- **Executor**: Leader+- **Input**: outputs from all upstream steps+- **Action**: <integration logic — A: surface contradictions verbatim; B: compose by slice; C: validate gates>+- **Output**: <Report Name> in the format below++#### Final Report Format++```markdown+# <Report Name>++## Summary+<1-3 sentence overview>++## <Tier 1 — e.g., MUST-FIX / Critical Findings / GO-NO-GO Verdict>+- <item> — <evidence reference>++## <Tier 2 — e.g., SHOULD-FIX / Recommendations>+- <item>++## <Tier 3 — e.g., FYI / Observations>+- <item>++## Contradictions (A-pattern only — surfaced verbatim, NOT mediated)+- <Role X said "...", Role Y said "..." — human decides>++## Coverage Map (B-pattern only)+- Slice 1: <covered by role X>+- Slice 2: <covered by role Y>+- Gaps: <slices nobody covered, if any>++## Unresolved Disputes (Debate-pattern — preserved from cross-exam, NOT mediated)+- <Claim by Role X> vs <Counter by Role Y> — <synthesizer's assessment + what user should verify>+```++## Acceptance Criteria++- All roles returned outputs matching their `## Output Schema` (no malformed responses).+- Final Report contains all mandatory tiers.+- <Pattern-specific check, e.g., "All A-pattern contradictions surfaced verbatim, none mediated by Leader" / "All C-pattern gates passed or explicit kick-back recorded" / "All Debate-pattern unresolved disputes preserved with cross-exam context, not silently dropped">.+- <Coverage check, e.g., "All B-pattern slices accounted for in the Coverage Map">.++<!--+TEMPLATE NOTES (delete before publishing):++1. Mermaid is REQUIRED in `## Overview` — the primary expression difference from+ single-agent skills (which are linear and need no diagram).+ Use `graph LR` for wide pipelines, `graph TD` for tall ones.++2. EVERY step's `Quality gate` MUST be specific. "Looks good" is not a gate.+ Use count-based ("≥3 sections present"), enum-based ("Verdict in {GO, NO-GO}"),+ or schema-based ("matches Output Schema") criteria.++3. Quality gates live INSIDE the steps (not in a separate `## Quality Gates` section).+ A gate is a property of a step, not an independent concept.++4. The Final Report Format is defined HERE (in the last step) — NOT in SKILL.md.+ Defining it in two places creates drift.++5. Acceptance Criteria judges a SUCCESSFUL SINGLE RUN. It is NOT a per-step gate.+ Failures of acceptance criteria → bind.md § Failure Handling.+-->diff --git a/jiuwenclaw/web/src/components/ChatPanel/ChatPanel.css b/jiuwenclaw/web/src/components/ChatPanel/ChatPanel.cssindex 9c2c1d53ce..c9a10789fa 100644--- a/jiuwenclaw/web/src/components/ChatPanel/ChatPanel.css+++ b/jiuwenclaw/web/src/components/ChatPanel/ChatPanel.css@@ -91,6 +91,40 @@min-width: 0;}+.chat-input-evolution-pill {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ min-width: 0;+ max-width: min(360px, 40vw);+ padding: 7px 12px;+ border-radius: var(--radius-full);+ border: 1px solid rgba(245, 158, 11, 0.28);+ background: var(--warn-subtle);+ color: var(--warn);+ box-shadow: inset 0 1px 0 color-mix(in srgb, var(--card-highlight) 65%, transparent);+}++.chat-input-evolution-pill__dot {+ width: 7px;+ height: 7px;+ border-radius: 999px;+ background: currentColor;+ box-shadow: 0 0 10px currentColor;+ animation: pulse-subtle 1.4s ease-in-out infinite;+ flex: 0 0 auto;+}++.chat-input-evolution-pill__label {+ display: block;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: var(--font-size-xs);+ font-weight: 600;+}+.chat-mode-switch {--chat-mode-gap: 4px;--chat-mode-pad: 4px;diff --git a/jiuwenclaw/web/src/components/ChatPanel/InputArea.tsx b/jiuwenclaw/web/src/components/ChatPanel/InputArea.tsxindex 83ec351fd7..9e4879491e 100644--- a/jiuwenclaw/web/src/components/ChatPanel/InputArea.tsx+++ b/jiuwenclaw/web/src/components/ChatPanel/InputArea.tsx@@ -5,6 +5,7 @@ import { stopAllTts } from '../../utils';import { useChatStore, useSessionStore } from '../../stores';import { AgentMode } from '../../types';import clsx from 'clsx';+import { getEvolutionPillLabel } from './evolution-status';interface InputAreaProps {onSubmit: (content: string) => void;@@ -30,7 +31,16 @@ export function InputArea({const activePointerIdRef = useRef<number | null>(null);const isVoicePressingRef = useRef(false);const { t } = useTranslation();- const { isPaused, taskQueue, addToTaskQueue, removeFromTaskQueue, inputValue, setInputValue, messages } = useChatStore();+ const {+ isPaused,+ taskQueue,+ addToTaskQueue,+ removeFromTaskQueue,+ inputValue,+ setInputValue,+ messages,+ evolutionStatus,+ } = useChatStore();const { mode } = useSessionStore();const isInterruptible = isProcessing || isPaused;const isAgentMode = mode === 'agent.fast';@@ -250,6 +260,7 @@ export function InputArea({const canSend = inputValue.trim().length > 0 || isListening;const modeIndex = Math.max(0, modes.findIndex((m) => m.value === mode));+ const evolutionLabel = getEvolutionPillLabel(mode, evolutionStatus, t);return (<div@@ -339,7 +350,12 @@ export function InputArea({</button>))}</div>-+ {evolutionLabel && (+ <div className="chat-input-evolution-pill" title={evolutionLabel}>+ <span className="chat-input-evolution-pill__dot" />+ <span className="chat-input-evolution-pill__label">{evolutionLabel}</span>+ </div>+ )}</div><div className="chat-input-actions">diff --git a/jiuwenclaw/web/src/components/ChatPanel/evolution-status.ts b/jiuwenclaw/web/src/components/ChatPanel/evolution-status.tsnew file mode 100644index 0000000000..104939500f--- /dev/null+++ b/jiuwenclaw/web/src/components/ChatPanel/evolution-status.ts@@ -0,0 +1,33 @@+import type { AgentMode } from '../../types/index.ts';+import type { EvolutionStatusPayload } from '../../types/websocket.ts';++type Translate = (key: string) => string;++const STAGE_KEY_MAP: Record<string, string> = {+ collecting: 'statusBar.evolutionStages.collecting',+ detecting: 'statusBar.evolutionStages.detecting',+ generating: 'statusBar.evolutionStages.generating',+ awaiting_approval: 'statusBar.evolutionStages.awaitingApproval',+ completed: 'statusBar.evolutionStages.completed',+ timed_out: 'statusBar.evolutionStages.timedOut',+ failed: 'statusBar.evolutionStages.failed',+};++export function getEvolutionPillLabel(+ _mode: AgentMode,+ evolutionStatus: EvolutionStatusPayload | null,+ t: Translate,+): string | null {+ if (!evolutionStatus) {+ return null;+ }++ const stage = (evolutionStatus.stage || '').trim().toLowerCase();+ const translationKey = STAGE_KEY_MAP[stage];+ if (translationKey) {+ return t(translationKey);+ }++ const message = typeof evolutionStatus.message === 'string' ? evolutionStatus.message.trim() : '';+ return message || t('statusBar.evolving');+}diff --git a/jiuwenclaw/web/src/components/ConfigPanel/index.tsx b/jiuwenclaw/web/src/components/ConfigPanel/index.tsxindex 8cde56b2ee..a809d29d4b 100644--- a/jiuwenclaw/web/src/components/ConfigPanel/index.tsx+++ b/jiuwenclaw/web/src/components/ConfigPanel/index.tsx@@ -434,9 +434,14 @@ const KEY_PLACEHOLDER_I18N: Record<string, string> = {free_search_proxy_url: "config.keys.freeSearchProxyUrlPlaceholder",memory_forbidden_description: "config.keys.memoryForbiddenDescriptionPlaceholder",};+const KEY_LABEL_HINT_I18N: Record<string, string> = {+ skill_create: "config.keyHelp.skillCreate",+};/** 组内字段排序优先级,数字越小越靠前 */const KEY_SORT_PRIORITY: Record<string, number> = {+ evolution_auto_scan: 0,+ skill_create: 1,free_search_ddg_enabled: 0,free_search_bing_enabled: 1,free_search_proxy_url: 2,@@ -451,8 +456,16 @@ const KEY_SORT_PRIORITY: Record<string, number> = {function getKeyDisplayLabel(key: string, t: (key: string) => string): string {if (KEY_DISPLAY_I18N[key]) return t(KEY_DISPLAY_I18N[key]);const m = key.match(/^(video|audio|vision)_(.+)$/);- if (m) return m[2];- return getBooleanKeyLabel(key, t) ?? key;+ return m ? m[2] : (getBooleanKeyLabel(key, t) ?? key);+}++function getKeyLabelHintText(key: string, t: (key: string) => string): string {+ const hintKey = KEY_LABEL_HINT_I18N[key];+ return hintKey ? t(hintKey) : "";+}++function getKeySortPriority(key: string): number {+ return KEY_SORT_PRIORITY[key] ?? 50;}function GroupSection({@@ -526,7 +539,14 @@ function GroupSection({<tbody>{group.keys.map(([key, value]) => (<tr key={key} className="border-t border-border first:border-t-0 even:bg-secondary/10 hover:bg-secondary/25 transition-colors">- <td className="px-4 py-2.5 align-middle mono text-xs text-text-muted w-[32%]" title={key}>{getKeyDisplayLabel(key, t)}</td>+ <td className="px-4 py-2.5 align-middle text-xs text-text-muted w-[32%]" title={key}>+ <div className="mono">{getKeyDisplayLabel(key, t)}</div>+ {getKeyLabelHintText(key, t) ? (+ <div className="mt-1 text-[11px] leading-4 text-text-muted">+ {getKeyLabelHintText(key, t)}+ </div>+ ) : null}+ </td><td className="px-4 py-2.5 break-all text-[13px] align-middle">{isBooleanKey(key) ? (<div className="flex items-center gap-2">@@ -1806,8 +1826,8 @@ export function ConfigPanel({}for (const entries of Object.values(buckets)) {entries.sort(([a], [b]) => {- const pa = KEY_SORT_PRIORITY[a] ?? 50;- const pb = KEY_SORT_PRIORITY[b] ?? 50;+ const pa = getKeySortPriority(a);+ const pb = getKeySortPriority(b);if (pa !== pb) return pa - pb;return a.localeCompare(b);});diff --git a/jiuwenclaw/web/src/hooks/useWebSocket.ts b/jiuwenclaw/web/src/hooks/useWebSocket.tsindex c237bd2907..a7c85d1214 100644--- a/jiuwenclaw/web/src/hooks/useWebSocket.ts+++ b/jiuwenclaw/web/src/hooks/useWebSocket.ts@@ -15,6 +15,7 @@ import {InterruptIntent,SubtaskUpdatePayload,AskUserQuestionPayload,+ EvolutionStatusPayload,UserAnswer,MediaItem,AgentMode,@@ -146,6 +147,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {updateMessage,setProcessing,setThinking,+ setEvolutionStatus,setPaused,setInterruptResult,addToolCall,@@ -784,6 +786,11 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {}}}),+ webClient.on('chat.evolution_status', ({ payload }) => {+ if (!shouldHandleSessionEvent(payload)) return;+ if (shouldDropDuplicatedEvent('chat.evolution_status', payload)) return;+ setEvolutionStatus(payload as unknown as EvolutionStatusPayload);+ }),webClient.on('chat.error', ({ payload }) => {if (!shouldHandleSessionEvent(payload)) return;if (shouldDropDuplicatedEvent('chat.error', payload)) return;@@ -1147,4 +1154,4 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {sendUserAnswer,getInflightCount: () => webClient.getInflightCount(),};-}\ No newline at end of file+}diff --git a/jiuwenclaw/web/src/i18n/locales/en.json b/jiuwenclaw/web/src/i18n/locales/en.jsonindex 48877833aa..bcf5c6cca8 100644--- a/jiuwenclaw/web/src/i18n/locales/en.json+++ b/jiuwenclaw/web/src/i18n/locales/en.json@@ -46,6 +46,16 @@"pause": "Pause","resume": "Resume","processing": "Processing...",+ "evolving": "Background skill evolution in progress...",+ "evolutionStages": {+ "collecting": "Background skill evolution in progress...",+ "detecting": "Detecting evolution signals...",+ "generating": "Generating evolution experience...",+ "awaitingApproval": "Evolution proposal ready, awaiting approval...",+ "completed": "Skill evolution completed",+ "timedOut": "Skill evolution timed out",+ "failed": "Skill evolution failed"+ },"paused": "Paused","pausedWithTask": "Paused: {{task}}..."},@@ -423,6 +433,9 @@"teamMemberPromptHint": "Prompt Hint","teamMemberAgentKey": "Agent Key"},+ "keyHelp": {+ "skillCreate": "Install `skill-creator` and `teamskill-creator` before enabling"+ },"hideValue": "Hide value","showValue": "Show value","validateModel": {diff --git a/jiuwenclaw/web/src/i18n/locales/zh.json b/jiuwenclaw/web/src/i18n/locales/zh.jsonindex 786236960a..01c5384c2b 100644--- a/jiuwenclaw/web/src/i18n/locales/zh.json+++ b/jiuwenclaw/web/src/i18n/locales/zh.json@@ -46,6 +46,16 @@"pause": "暂停","resume": "恢复","processing": "处理中...",+ "evolving": "后台技能演进中...",+ "evolutionStages": {+ "collecting": "后台技能演进中...",+ "detecting": "正在检测演进信号...",+ "generating": "正在生成演进经验...",+ "awaitingApproval": "演进经验已生成,等待审批...",+ "completed": "技能演进已完成",+ "timedOut": "技能演进已超时",+ "failed": "技能演进失败"+ },"paused": "已暂停","pausedWithTask": "已暂停: {{task}}..."},@@ -422,6 +432,9 @@"teamMemberPromptHint": "提示词","teamMemberAgentKey": "Agent Key"},+ "keyHelp": {+ "skillCreate": "建议先安装 `skill-creator` 和 `teamskill-creator`,再开启"+ },"hideValue": "隐藏明文","showValue": "显示明文","validateModel": {diff --git a/jiuwenclaw/web/src/stores/chatStore.ts b/jiuwenclaw/web/src/stores/chatStore.tsindex d32fc77f48..acc3b4436c 100644--- a/jiuwenclaw/web/src/stores/chatStore.ts+++ b/jiuwenclaw/web/src/stores/chatStore.ts@@ -12,11 +12,14 @@ import {InterruptResultPayload,SubtaskUpdatePayload,AskUserQuestionPayload,+ EvolutionStatusPayload,UsageSummary,} from '../types';import { useTodoStore } from './todoStore';const TOOL_TIMEOUT_MS = 12_000_000;+const EVOLUTION_STATUS_END_VISIBLE_MS = 3_000;+let evolutionStatusClearTimer: ReturnType<typeof setTimeout> | null = null;function computeTimeoutAt(baseIso: string): string {return new Date(Date.parse(baseIso) + TOOL_TIMEOUT_MS).toISOString();@@ -51,6 +54,7 @@ interface ChatState {messages: Message[];isProcessing: boolean;isThinking: boolean; // 思考中状态(显示闪烁动画)+ evolutionStatus: EvolutionStatusPayload | null;isPaused: boolean; // 任务是否暂停pausedTask: string | null; // 暂停的任务描述interruptResult: InterruptResultPayload | null; // 最近的中断结果@@ -80,6 +84,7 @@ interface ChatState {stopStreaming: (streamKey?: string) => void;setProcessing: (status: boolean) => void;setThinking: (status: boolean) => void;+ setEvolutionStatus: (status: EvolutionStatusPayload | null) => void;setPaused: (paused: boolean, task?: string | null) => void;setInterruptResult: (result: InterruptResultPayload | null) => void;addToolCall: (toolCall: ToolCall, options?: { startedAt?: string }) => void;@@ -106,6 +111,7 @@ export const useChatStore = create<ChatState>((set, get) => ({messages: [],isProcessing: false,isThinking: false,+ evolutionStatus: null,isPaused: false,pausedTask: null,interruptResult: null,@@ -186,6 +192,25 @@ export const useChatStore = create<ChatState>((set, get) => ({set({ isThinking: status });},+ setEvolutionStatus: (status) => {+ if (evolutionStatusClearTimer) {+ clearTimeout(evolutionStatusClearTimer);+ evolutionStatusClearTimer = null;+ }+ set({ evolutionStatus: status });+ if (status?.status === 'end') {+ evolutionStatusClearTimer = setTimeout(() => {+ set((state) => {+ if (state.evolutionStatus === status) {+ return { evolutionStatus: null };+ }+ return {};+ });+ evolutionStatusClearTimer = null;+ }, EVOLUTION_STATUS_END_VISIBLE_MS);+ }+ },+setPaused: (paused, task = null) => {set({ isPaused: paused, pausedTask: task ?? null });},@@ -470,11 +495,16 @@ export const useChatStore = create<ChatState>((set, get) => ({},clearMessages: () => {+ if (evolutionStatusClearTimer) {+ clearTimeout(evolutionStatusClearTimer);+ evolutionStatusClearTimer = null;+ }set({messages: [],currentStreamContent: '',currentStreamId: null,streamBuffers: new Map(),+ evolutionStatus: null,isPaused: false,pausedTask: null,interruptResult: null,@@ -529,4 +559,4 @@ export const useChatStore = create<ChatState>((set, get) => ({),}));},-}));\ No newline at end of file+}));diff --git a/jiuwenclaw/web/src/types/websocket.ts b/jiuwenclaw/web/src/types/websocket.tsindex 9c6085d71c..195d57295b 100644--- a/jiuwenclaw/web/src/types/websocket.ts+++ b/jiuwenclaw/web/src/types/websocket.ts@@ -66,6 +66,13 @@ export interface ProcessingStatusPayload {current_task?: string;}+export interface EvolutionStatusPayload {+ session_id?: string;+ status: 'start' | 'progress' | 'end';+ stage?: string;+ message?: string;+}+export interface ErrorPayload {error: string;code?: string;