Skip to content

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

fix(swarmskill-creator): swarmskill-creator new version for swarmflow

z2tng161939af4ceb
diff --git a/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/SKILL.md b/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/SKILL.md
index 296592ad1d..19c59f8971 100644
--- a/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/SKILL.md
+++ b/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/SKILL.md
@@ -1,27 +1,63 @@
---
name: swarmskill-creator
description: |
- Creates, converts, or modifies Swarm Skills — 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"
+ Creates, converts, or modifies Swarm Skills — the multi-role (多角色团队) extension of the Skills standard, optionally with an executable SwarmFlow orchestration script.
+ Use when building or refactoring a multi-agent team, generating workflow (工作流/编排) orchestration code, or upgrading a single-agent skill into a collaborating team.
+ Do NOT use for ordinary single-agent skills — use create-skill instead.
+version: "0.4"
---
# Swarm Skill Creator
-Authoring tool for Swarm Skills — the multi-role extension of the Anthropic Skills standard. Encodes the Swarm Skill spec into a repeatable workflow with templates, decision trees, and an automated validator.
+Authoring tool for Swarm Skills — the multi-role extension of the Skills standard. Encodes the Swarm Skill 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:
+This skill has two independent routing dimensions:
+
+1. **Operation mode** — what kind of authoring work is being performed.
+2. **Output shape** — what files the resulting Swarm Skill should contain.
+
+Pick both before writing files. Output shape is a separate dimension, not an additional operation mode.
| Mode | Trigger | Output |
|---|---|---|
-| **CREATE** | User has a fresh need ("build a team for X") | New `<swarmskill-name>/` directory with the full 5-file set |
-| **CONVERT** | User points at an existing single-agent skill | Transformed `<swarmskill-name>/` directory + a delta report explaining what the team adds |
+| **CREATE** | User has a fresh need ("build a team for X") | New `<swarmskill-name>/` directory in the selected output shape |
+| **CONVERT** | User points at an existing single-agent skill | Transformed `<swarmskill-name>/` directory in the selected output shape + a delta report |
| **MODIFY** | User edits an existing Swarm Skill (add/remove role, change workflow, adjust bind, fix validator errors) | Updated files in the existing `<swarmskill-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.
+Each operation mode maps to the staged pipeline defined below (see Stage 0–6). Quick routing:
+
+- **CREATE / CONVERT** — share Stages 2–6; they differ only at Stage 1 (CREATE designs roles from scratch, CONVERT decomposes an existing skill).
+- **MODIFY** — skips Stage 0–1 *unless* the change alters the team pattern; edits only the affected files; **always re-runs Stage 6 (validator)**.
+- **Script-only output** — bypasses the role/workflow/bind/dependency stages entirely, since those files are intentionally absent.
+
+### Output shape triage — Markdown, script-only SwarmFlow, or Markdown + SwarmFlow
+
+Before Stage 0, classify the requested output shape. This is a silent routing step; do not ask the user unless their wording is genuinely ambiguous.
+
+| Output shape | Trigger | Files to produce |
+|---|---|---|
+| **Markdown spec (default)** | User asks to create/convert/modify a Swarm Skill, team skill, multi-role team, roles, bind, dependencies, human-readable workflow, or self-evolution metadata, and does not ask for executable orchestration | Standard 5-file set only: `SKILL.md`, `roles/`, `workflow.md`, `bind.md`, `dependencies.yaml` |
+| **Script-only SwarmFlow skill** | User asks for 工作流, workflow, SwarmFlow, `workflow.py`, executable orchestration, code orchestration, 可执行编排, or 编排脚本, without explicitly asking for a full team skill spec | `SKILL.md` + `scripts/workflow.py` only |
+| **Markdown spec + SwarmFlow script** | User explicitly asks for a full team/SwarmSkill spec and also asks for 工作流, workflow, SwarmFlow, `workflow.py`, executable orchestration, code orchestration, 可执行编排, or 编排脚本 | Standard 5-file set + `scripts/workflow.py` |
+
+Default is conservative in both directions: if the user does not ask for code orchestration, do **not** generate `scripts/workflow.py`; and if they ask for workflow/SwarmFlow/code orchestration *without* a full team skill spec, prefer script-only — do not expand to the full Markdown spec just because the output is still packaged as a Swarm Skill. In script-only mode:
+
+- `SKILL.md` is still required and must contain valid frontmatter plus `## Workflow` and `## Files`.
+- `roles:` must be omitted or empty in `SKILL.md` frontmatter.
+- The file set is exactly `SKILL.md` plus `scripts/workflow.py`.
+- `scripts/workflow.py` is the executable orchestration surface and must be listed in `SKILL.md` `## Files`.
+- All agent prompts, prompt-builder functions, schemas, and orchestration logic live inside `scripts/workflow.py`.
+- If the user also needs rich role personas, gates, dependency contracts, human-readable team docs, or self-evolution metadata, use the full Markdown spec + SwarmFlow script shape.
+
+Stage routing:
+
+| Output shape | Stage route |
+|---|---|
+| **Markdown spec (default)** | Run the normal full-spec stages: Stage 0 → 1 → 2 → 3 → 4 → 5 → 6 |
+| **Markdown spec + SwarmFlow script** | Run the normal full-spec stages, and add Stage 3b after `workflow.md`; revisit Stage 3b after `bind.md` if failure/retry behavior changes the script |
+| **Script-only SwarmFlow skill** | Write minimal `SKILL.md` + `scripts/workflow.py`, then run Stage 6. Do not fabricate role files, prompt files, or Markdown spec files just to satisfy the full-spec pipeline |
### Stage 0: Triage — is a Swarm Skill even justified?
@@ -112,6 +148,42 @@ Author `workflow.md` using [templates/workflow.md.template](templates/workflow.m
Quality gates are the contract surface between stages — design them per [reference/role-design.md](reference/role-design.md) § Gate Design.
+### Stage 3b: Generate `scripts/workflow.py` when requested
+
+Run this stage only for **Markdown spec + SwarmFlow script** and **script-only SwarmFlow skill** output shapes.
+
+For the full Markdown spec + SwarmFlow shape, Stage 3b has two passes:
+
+1. **Topology pass after Stage 3** — translate `workflow.md` into phases, parallel/sequential structure, integration points, and role labels.
+2. **Behavior pass after Stage 4** — revisit the script if `bind.md` introduces retry, timeout, budget, degraded-mode, or failure behavior that must be executable.
+
+Do not let the script invent a different workflow from `workflow.md`; do not let `workflow.md` describe behavior the script cannot execute.
+
+Generate `scripts/workflow.py` from [templates/scripts/workflow.py.template](templates/scripts/workflow.py.template). The script must follow the executable SwarmFlow template:
+
+1. Keep top-level `META` as a pure literal.
+2. Keep the entrypoint `async def run(args)`.
+3. Import runtime primitives explicitly from `swarmflow`.
+4. Keep agent prompts inside the script as constants or prompt-builder functions.
+5. Use JSON Schema literals for structured agent outputs. **Do NOT include `"additionalProperties": False` or `"required"`** — both are too strict for LLM outputs and cause `agent()` to silently return `None`. Use a permissive schema that only declares `"type": "object"` and `"properties"` to guide the LLM's output format, then extract only the fields you need with `safe_get()`.
+6. Use stable labels for every `agent(...)` call.
+7. When an `agent(...)` call passes a `phase=` argument, that value MUST equal the active `phase("...")` event for that block. Mismatched phase labels break runtime statistics.
+8. Choose the orchestration primitive that matches the topology:
+ - `map_parallel(items, fn)` for homogeneous fan-out over a list.
+ - `parallel([lambda: ...])` for a fixed heterogeneous set of roles or voters.
+ - `pipeline(items, stage1, stage2, ...)` for ordered per-item multi-stage processing.
+ - `compact(...)`, `flatten_filter(...)`, and `log(...)` when they make result cleanup or runtime tracing clearer.
+9. **Resilient data handling** — the template provides three helpers that every workflow MUST use:
+ - `parse_args(args)` — call at the top of `run()`. Swarmflow may pass `args` as a JSON string instead of a dict; this normalizes it to a dict unconditionally.
+ - `extract_json(raw, fallback={...})` — wrap every `agent()` return value. `agent()` may return `None` (schema validation failed) or a raw string (no schema match); `extract_json` handles both by extracting the first JSON object or falling back to defaults. Never use an `agent()` return value directly without this wrapper.
+ - `safe_get(obj, key, default)` — use instead of `obj["key"]` or `obj.get("key")`. Handles `None` results and missing keys uniformly.
+10. **Cache validation** — when loading cached results from incremental runs, verify key fields are non-empty (not just that the cache file exists). An empty `scores: []` or `signal: null` indicates a failed prior run and should be treated as a cache miss, not a valid result to skip.
+11. Delete all template notes and placeholder values before publishing.
+
+For the full Markdown spec + SwarmFlow shape, the final script must match the topology in `workflow.md` and the executable constraints in `bind.md`: same phases, same parallel or sequential structure, same integration point, and no extra hidden workflow that the Markdown spec does not describe.
+
+For script-only mode, derive the script directly from the user's requested orchestration. Keep `SKILL.md` minimal but explicit: describe when to invoke the skill, state that `scripts/workflow.py` is the execution definition, and list the script under `## Files`.
+
### 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:
@@ -134,16 +206,17 @@ The remaining two files. Write them last because they reference content produced
- Directory name = `name` field in SKILL.md frontmatter (kebab-case, ends with `-swarm` 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).
+- Exception: script-only SwarmFlow skills require only `SKILL.md` and `scripts/workflow.py`; the executable script is the single source for prompts, schemas, and orchestration.
**Description discipline** (enforced by the validator — these are the most-violated rules):
-- ≤ 4 lines, ≤ 500 chars total.
+- 3 lines, ≤ 500 chars (validator hard cap: 1024 — 500 is the target, not the ceiling).
- 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). Swarm Skills 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.
+**Calibration note**: 500 chars is the target; 1024 is the validator's hard ceiling. Swarm Skills are inherently more complex than single-agent skills, so the extra room exists — but use it only when multi-role composition or trigger scope genuinely needs it. Stay concise; don't sacrifice clarity for arbitrary brevity.
### Stage 6: Validate
@@ -155,10 +228,12 @@ python scripts/validate_swarmskill.py path/to/<swarmskill-name>/
The validator checks:
- **Structural**: 5 files present, role file names match `roles[].id`, no orphan role files
+- **Script-only structural**: when the skill intentionally contains only `SKILL.md` + `scripts/workflow.py`, skip the 5-file Markdown-spec checks and validate the executable script instead
- **Frontmatter**: `name` / `description` / `version` / `kind: swarm-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
+- **SwarmFlow script**: if `scripts/workflow.py` exists, it is legal Python, exports literal `META`, defines `async def run(args)`, imports primitives from `swarmflow`, contains no template placeholders, keeps prompts inline, keeps explicit `agent(..., phase=...)` values aligned with the active `phase("...")`, avoids local absolute paths, and avoids dangerous calls such as `eval`, `exec`, `os.system`, or `subprocess`
**Exit code 0 = compliant**. Non-zero exit prints the failing checks with file:line references.
@@ -190,12 +265,12 @@ 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:
+**Design intent**: the agent is structurally biased toward skipping community search. Reject the 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.
+1. *"No skills assigned → the role works on LLM knowledge alone."* A role *can* function, but a matching skill often dramatically improves output quality.
+2. *"It already has a generic skill (e.g. `web-research`) → covered."* Harder to catch and equally wrong — generic retrieval is not domain expertise (see the anti-pattern below).
-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.
+Default to **recommend**; the burden of proof is on *not* recommending. Test: *"Does a domain-specific community skill exist that would give this role capabilities beyond its current generic skills?"* If plausible → recommend.
> **Anti-pattern: "通用即覆盖" (generic = covered)**
>
@@ -208,9 +283,9 @@ The default must be **recommend**, with the burden of proof on **not** recommend
- **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.
+- **Domain-specific platform / service interaction** (e-commerce, social media, financial services, travel, healthcare, government portals, etc.) — community registries often encode platform-specific rules, workflows, or API integrations that generic retrieval cannot replicate (e.g. 淘宝/京东/拼多多 shopping skills, 买手/personal-shopper skills).
-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."
+If a role hits these patterns and no **domain-specific** local skill covers it, recommend "Yes".
**Community enrichment prompt:**
@@ -258,6 +333,7 @@ This skill has no Swarm Skill roles itself — it is a **single-agent skill** th
| [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) |
+| [templates/scripts/workflow.py.template](templates/scripts/workflow.py.template) | Executable SwarmFlow orchestration skeleton | Stage 3b when code orchestration is requested |
| [scripts/validate_swarmskill.py](scripts/validate_swarmskill.py) | Automated structural + frontmatter + section + cross-file consistency checks | Stage 6 (run on every Swarm Skill before declaring done) |
## Common pitfalls
@@ -281,10 +357,20 @@ 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_swarmskill.py <swarmskill-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)
+4. Write `workflow.md`; if output shape includes SwarmFlow, draft `scripts/workflow.py` topology from it
+5. Write `bind.md`; if output shape includes SwarmFlow, update `scripts/workflow.py` for executable retry/failure/degraded behavior
+6. Write `dependencies.yaml` → `SKILL.md` (each using its template)
+7. Run `python scripts/validate_swarmskill.py <swarmskill-name>/` until exit 0
+8. 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)
+9. Manual review with [reference/compliance-checklist.md](reference/compliance-checklist.md)
+
+For a script-only SwarmFlow CREATE request:
+
+1. Use this path when the request mentions 工作流 / workflow / SwarmFlow / `workflow.py` / executable orchestration / code orchestration / 可执行编排 / 编排脚本, unless the user also asks for a full team skill spec.
+2. Write a minimal `SKILL.md` with `kind: swarm-skill`, concise trigger description, no non-empty `roles:`, `## Workflow`, and `## Files`.
+3. Write `scripts/workflow.py` from [templates/scripts/workflow.py.template](templates/scripts/workflow.py.template), deleting placeholders and template notes. Inline every agent prompt in this script.
+4. Run `python scripts/validate_swarmskill.py <swarmskill-name>/` until exit 0.
+5. Present the script path and explain that this skill is optimized for SwarmFlow execution, not full-spec role evolution.
For a CONVERT request:
@@ -310,5 +396,6 @@ For a MODIFY request:
| 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` |
+| Add, remove, or change SwarmFlow code orchestration | Stage 3b + Stage 4 if failure behavior changes + 6 | `scripts/workflow.py` + `SKILL.md` `## Files` if needed |
All rows require **Stage 6 (validator)** as the final step.
diff --git a/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/scripts/validate_swarmskill.py b/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/scripts/validate_swarmskill.py
index 28ceaebf84..9c1228793f 100644
--- a/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/scripts/validate_swarmskill.py
+++ b/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/scripts/validate_swarmskill.py
@@ -14,6 +14,8 @@ Requires: PyYAML (pip install pyyaml)
What this script catches (deterministic):
- 5-file structure (SKILL.md, roles/, workflow.md, bind.md, dependencies.yaml)
+ - Script-only SwarmFlow structure (SKILL.md + scripts/workflow.py only;
+ prompts must be inline in the script)
- Frontmatter required fields + types
- `name` field equals directory name
- roles/<id>.md exists for every roles[].id; no orphan role files
@@ -27,6 +29,9 @@ What this script catches (deterministic):
- 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
+ - scripts/workflow.py, when present, is legal Python with literal META and
+ async def run(args), explicit swarmflow primitive imports, inline prompts,
+ no template placeholders, and no obvious dangerous calls or local absolute paths
What this script does NOT catch (judgment calls — see reference/compliance-checklist.md):
- Whether mottos are mutually antagonistic (anti-convergence quality)
@@ -37,9 +42,10 @@ What this script does NOT catch (judgment calls — see reference/compliance-che
from __future__ import annotations
-import logging
+import ast
import sys
import re
+import logging
from pathlib import Path
from typing import Any
@@ -90,6 +96,7 @@ class Report:
len(self.warnings),
)
+
# ---------------------------------------------------------------------------
# Frontmatter + section parsing helpers
# ---------------------------------------------------------------------------
@@ -141,10 +148,10 @@ def section_body(body: str, header: str) -> str | None:
# Per-file validators
# ---------------------------------------------------------------------------
-def validate_skill_md(path: Path, report: Report) -> tuple[dict | None, list[str]]:
+def validate_skill_md(path: Path, report: Report, script_only: bool = False) -> 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")
+ report.err("SKILL.md", "missing — required for every Swarm Skill")
return None, []
text = path.read_text(encoding="utf-8")
@@ -159,8 +166,12 @@ def validate_skill_md(path: Path, report: Report) -> tuple[dict | None, list[str
report.err("SKILL.md", "missing YAML frontmatter (--- ... ---)")
return None, []
- # Required frontmatter fields
- for field in ("name", "description", "version", "kind", "roles"):
+ # Required frontmatter fields. Script-only SwarmFlow skills do not need
+ # roles[] because the script is the execution definition.
+ required_fields = ("name", "description", "version", "kind")
+ if not script_only:
+ required_fields += ("roles",)
+ for field in required_fields:
if field not in fm:
report.err("SKILL.md", f"frontmatter missing required field `{field}`")
@@ -200,7 +211,11 @@ def validate_skill_md(path: Path, report: Report) -> tuple[dict | None, list[str
# roles[] structure
role_ids: list[str] = []
roles = fm.get("roles", [])
- if not isinstance(roles, list) or not roles:
+ if script_only:
+ if "roles" in fm and roles not in (None, []):
+ report.err("SKILL.md", "script-only SwarmFlow skills must omit `roles` or set `roles: []`")
+ roles = []
+ elif not isinstance(roles, list) or (not roles and not script_only):
report.err("SKILL.md", "frontmatter `roles` must be a non-empty list")
else:
for i, role in enumerate(roles):
@@ -217,7 +232,7 @@ def validate_skill_md(path: Path, report: Report) -> tuple[dict | None, list[str
report.err(
"SKILL.md",
f"roles[{i}] (id={role.get('id')!r}) `kind` must be "
- f"`ai_agent` or `human_agent` (got: {role['kind']!r})"
+ f"`ai_agent` or `human_agent` (got: {role['kind']!r})",
)
if "purpose" not in role:
report.err("SKILL.md", f"roles[{i}] (id={role.get('id')!r}) missing required field `purpose`")
@@ -249,7 +264,8 @@ def validate_skill_md(path: Path, report: Report) -> tuple[dict | None, list[str
# Body required sections
sections = find_h2_sections(body)
- for required in ("Workflow", "Roles", "Files"):
+ required_body_sections = ("Workflow", "Files") if script_only else ("Workflow", "Roles", "Files")
+ for required in required_body_sections:
if required not in sections:
report.err("SKILL.md", f"body missing required section `## {required}`")
@@ -262,12 +278,13 @@ def validate_skill_md(path: Path, report: Report) -> tuple[dict | None, list[str
"or `workflow.md` — remove to avoid duplication",
)
- # Anti-pattern: mermaid in SKILL.md body (redundant with workflow.md)
- if re.search(r"```mermaid", body):
+ # Anti-pattern: mermaid in SKILL.md body (redundant with workflow.md).
+ # Script-only skills have no workflow.md, so this warning does not apply.
+ if not script_only and re.search(r"```mermaid", body):
report.warn(
"SKILL.md",
- "body contains a ```mermaid``` block — keep mermaid only in workflow.md to "
- "avoid duplication",
+ "body contains a ```mermaid``` block — keep mermaid only in workflow.md "
+ "to avoid duplication",
)
return fm, role_ids
@@ -281,10 +298,7 @@ def validate_role_file(path: Path, role_id: str, report: Report) -> dict[str, li
"""
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}",
- )
+ 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")
@@ -331,7 +345,8 @@ def validate_role_file(path: Path, role_id: str, report: Report) -> dict[str, li
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). "
+ f"## Inline Persona for Teammate is suspiciously short "
+ f"({len(persona_body.strip())} chars). "
"It must be a self-contained pasteable prompt — see reference/role-design.md.",
)
@@ -371,7 +386,8 @@ def validate_workflow_md(path: Path, report: Report) -> None:
if not re.search(r"```mermaid", text):
report.err(
"workflow.md",
- "missing ```mermaid``` block — workflow.md must contain at least one mermaid diagram",
+ "missing ```mermaid``` block — workflow.md must contain at least one "
+ "mermaid diagram",
)
@@ -404,8 +420,8 @@ def validate_dependencies_yaml(path: Path, report: Report) -> dict[str, list[str
if not path.exists():
report.err(
"dependencies.yaml",
- "missing — required by the 5-file structure (write `skills: []` / `tools: []` "
- "if no deps)",
+ "missing — required by the 5-file structure (write `skills: []` / "
+ "`tools: []` if no deps)",
)
return {"skills": [], "tools": []}
@@ -448,8 +464,8 @@ def validate_dependencies_yaml(path: Path, report: Report) -> dict[str, list[str
if field not in entry:
report.err(
"dependencies.yaml",
- f"{segment}[{i}] (name={entry.get('name')!r}) missing required field "
- f"`{field}`",
+ f"{segment}[{i}] (name={entry.get('name')!r}) missing required "
+ f"field `{field}`",
)
if segment in declared and "name" in entry:
declared[segment].append(entry["name"])
@@ -457,6 +473,201 @@ def validate_dependencies_yaml(path: Path, report: Report) -> dict[str, list[str
return declared
+# ---------------------------------------------------------------------------
+# SwarmFlow script validator
+# ---------------------------------------------------------------------------
+
+def _is_literal(node: ast.AST) -> bool:
+ try:
+ ast.literal_eval(node)
+ return True
+ except (ValueError, TypeError):
+ return False
+
+
+def _string_literal(node: ast.AST) -> str | None:
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
+ return node.value
+ return None
+
+
+class _AgentCallCollector(ast.NodeVisitor):
+ def __init__(self) -> None:
+ self.calls: list[ast.Call] = []
+
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
+ return
+
+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
+ return
+
+ def visit_ClassDef(self, node: ast.ClassDef) -> None:
+ return
+
+ def visit_Call(self, node: ast.Call) -> None:
+ if isinstance(node.func, ast.Name) and node.func.id == "agent":
+ self.calls.append(node)
+ self.generic_visit(node)
+
+
+def _phase_call_value(stmt: ast.stmt) -> str | None:
+ if not isinstance(stmt, ast.Expr) or not isinstance(stmt.value, ast.Call):
+ return None
+ call = stmt.value
+ if not isinstance(call.func, ast.Name) or call.func.id != "phase" or not call.args:
+ return None
+ return _string_literal(call.args[0])
+
+
+def _agent_phase_mismatches(run_node: ast.AsyncFunctionDef) -> list[str]:
+ mismatches: list[str] = []
+ current_phase: str | None = None
+
+ for stmt in run_node.body:
+ if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ continue
+
+ phase_value = _phase_call_value(stmt)
+ if phase_value is not None:
+ current_phase = phase_value
+
+ collector = _AgentCallCollector()
+ collector.visit(stmt)
+ for call in collector.calls:
+ phase_kw = next((kw for kw in call.keywords if kw.arg == "phase"), None)
+ if phase_kw is None or current_phase is None:
+ continue
+
+ agent_phase = _string_literal(phase_kw.value)
+ line = getattr(call, "lineno", "?")
+ if agent_phase is None:
+ mismatches.append(
+ f"line {line}: agent phase must be the literal current phase {current_phase!r}"
+ )
+ elif agent_phase != current_phase:
+ mismatches.append(
+ f"line {line}: agent phase {agent_phase!r} does not match active phase {current_phase!r}"
+ )
+
+ return mismatches
+
+
+def validate_swarmflow_script(path: Path, skill_name: str, report: Report) -> None:
+ file_label = "scripts/workflow.py"
+ if not path.exists():
+ report.err(file_label, "missing — required for SwarmFlow script or script-only mode")
+ return
+
+ text = path.read_text(encoding="utf-8")
+
+ if "TEMPLATE NOTES" in text:
+ report.err(file_label, "contains template notes — delete before publishing")
+ if re.search(r"<[^>\n]+>", text):
+ report.err(file_label, "contains unresolved template placeholder(s) like `<...>`")
+ if re.search(r"([A-Za-z]:\\|/Users/|/home/)", text):
+ report.err(file_label, "contains an obvious local absolute path")
+
+ try:
+ tree = ast.parse(text, filename=str(path))
+ except SyntaxError as e:
+ report.err(file_label, f"Python syntax error: {e.msg} at line {e.lineno}")
+ return
+
+ meta_node: ast.AST | None = None
+ run_node: ast.AsyncFunctionDef | None = None
+ has_swarmflow_import = False
+ dangerous_imports: list[str] = []
+ blocked_imports: list[str] = []
+ dangerous_calls: list[str] = []
+ non_inline_prompt_calls: list[int] = []
+
+ for node in tree.body:
+ if isinstance(node, ast.Assign):
+ for target in node.targets:
+ if isinstance(target, ast.Name) and target.id == "META":
+ meta_node = node.value
+ elif (
+ isinstance(node, ast.AnnAssign)
+ and isinstance(node.target, ast.Name)
+ and node.target.id == "META"
+ ):
+ meta_node = node.value
+ elif isinstance(node, ast.AsyncFunctionDef) and node.name == "run":
+ run_node = node
+
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ for alias in node.names:
+ if alias.name.split(".", 1)[0] in {"os", "subprocess"}:
+ dangerous_imports.append(alias.name)
+ if alias.name.split(".", 1)[0] == "skill_context":
+ blocked_imports.append(alias.name)
+ elif isinstance(node, ast.ImportFrom):
+ module = node.module or ""
+ if module == "swarmflow" or module.startswith("swarmflow."):
+ has_swarmflow_import = True
+ if module.split(".", 1)[0] in {"os", "subprocess"}:
+ dangerous_imports.append(module)
+ if module.split(".", 1)[0] == "skill_context":
+ blocked_imports.append(module)
+ elif isinstance(node, ast.Call):
+ if isinstance(node.func, ast.Name) and node.func.id in {"eval", "exec"}:
+ dangerous_calls.append(node.func.id)
+ elif isinstance(node.func, ast.Attribute):
+ base = node.func.value
+ if isinstance(base, ast.Name) and base.id in {"os", "subprocess"}:
+ dangerous_calls.append(f"{base.id}.{node.func.attr}")
+ if node.func.attr == "build_prompt":
+ non_inline_prompt_calls.append(getattr(node, "lineno", 0))
+
+ if meta_node is None:
+ report.err(file_label, "missing top-level `META` assignment")
+ elif not isinstance(meta_node, ast.Dict) or not _is_literal(meta_node):
+ report.err(file_label, "`META` must be a pure literal dict")
+ else:
+ meta = ast.literal_eval(meta_node)
+ if meta.get("name") != skill_name:
+ report.warn(
+ file_label,
+ f"META.name ({meta.get('name')!r}) does not match "
+ f"directory name ({skill_name!r})",
+ )
+
+ if run_node is None:
+ report.err(file_label, "missing top-level `async def run(args)`")
+ else:
+ args = run_node.args.args
+ arg_names = [arg.arg for arg in args]
+ if arg_names != ["args"] or run_node.args.defaults:
+ report.err(file_label, f"`run` parameters must be exactly `(args)` (got: {arg_names})")
+ phase_mismatches = _agent_phase_mismatches(run_node)
+ for mismatch in phase_mismatches:
+ report.err(file_label, mismatch)
+
+ if not has_swarmflow_import:
+ report.err(file_label, "missing explicit `from swarmflow import ...` primitive import")
+ if dangerous_imports:
+ report.err(
+ file_label,
+ f"imports blocked module(s): {', '.join(sorted(set(dangerous_imports)))}",
+ )
+ if blocked_imports:
+ report.err(
+ file_label,
+ "uses a non-standard SwarmFlow context import; "
+ "use the standalone workflow format",
+ )
+ if dangerous_calls:
+ report.err(file_label, f"uses blocked call(s): {', '.join(sorted(set(dangerous_calls)))}")
+ if non_inline_prompt_calls:
+ lines = ", ".join(str(line) for line in sorted(set(non_inline_prompt_calls)) if line)
+ report.err(
+ file_label,
+ "SwarmFlow scripts must keep agent prompts inline in scripts/workflow.py "
+ f"(non-inline prompt call at line(s): {lines})",
+ )
+
+
# ---------------------------------------------------------------------------
# Cross-file consistency
# ---------------------------------------------------------------------------
@@ -483,7 +694,46 @@ def check_orphan_role_files(roles_dir: Path, declared_role_ids: list[str], repor
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[]`")
+ report.warn(
+ "roles/",
+ f"orphan file `roles/{f.name}` — not declared in SKILL.md "
+ "frontmatter `roles[]`",
+ )
+
+
+def detect_structure(root: Path, report: Report) -> tuple[bool, bool]:
+ """Return (has_swarmflow_script, is_script_only)."""
+ script_path = root / "scripts" / "workflow.py"
+ has_script = script_path.exists()
+ prompts_dir = root / "prompts"
+ markdown_paths = [
+ root / "roles",
+ root / "workflow.md",
+ root / "bind.md",
+ root / "dependencies.yaml",
+ ]
+ present = [p for p in markdown_paths if p.exists()]
+ has_partial_spec = 0 < len(present) < len(markdown_paths)
+
+ if has_script and not present:
+ if prompts_dir.exists():
+ report.err(
+ "prompts/",
+ "script-only SwarmFlow skills must keep prompts inline in "
+ "scripts/workflow.py; do not create prompts/",
+ )
+ return True, True
+
+ if has_script and has_partial_spec:
+ missing = [p.name for p in markdown_paths if not p.exists()]
+ report.err(
+ "structure",
+ "partial Markdown spec with SwarmFlow script — either provide the full "
+ "5-file spec or use script-only mode with only SKILL.md + "
+ f"scripts/workflow.py. Missing: {', '.join(missing)}",
+ )
+
+ return has_script, False
# ---------------------------------------------------------------------------
@@ -495,12 +745,22 @@ def validate(root: Path) -> int:
logger.info("[USAGE ERROR] %s is not a directory", root)
return 2
- logger.info("Validating Swarmskill: %s\n", root.resolve())
+ logger.info("Validating Swarm Skill: %s\n", root.resolve())
report = Report()
+ # 0. Structure shape
+ has_swarmflow_script, is_script_only = detect_structure(root, report)
+
# 1. SKILL.md
- skill_fm, role_ids = validate_skill_md(root / "SKILL.md", report)
+ skill_fm, role_ids = validate_skill_md(root / "SKILL.md", report, script_only=is_script_only)
+
+ if has_swarmflow_script:
+ validate_swarmflow_script(root / "scripts" / "workflow.py", root.name, report)
+
+ if is_script_only:
+ report.emit()
+ return 0 if report.passed() else 1
# 2. roles/<id>.md
roles_dir = root / "roles"
diff --git a/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/templates/SKILL.md.template b/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/templates/SKILL.md.template
index 2ac41d5f7a..ee6856b6e2 100644
--- a/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/templates/SKILL.md.template
+++ b/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/templates/SKILL.md.template
@@ -105,4 +105,11 @@ TEMPLATE NOTES (delete before publishing):
6. Per-role `purpose:` field has a ≤150-char HARD CAP (validator enforces).
Detail goes in roles/<id>.md, not here.
+
+7. If generating a SwarmFlow-backed full spec, add this row to `## Files`:
+ `| [scripts/workflow.py](scripts/workflow.py) | Executable workflow script | When running in SwarmFlow mode |`
+ For script-only SwarmFlow mode, use a minimal `SKILL.md` containing only
+ frontmatter plus `## Workflow` and `## Files`; omit `roles/`, `workflow.md`,
+ `bind.md`, and `dependencies.yaml` intentionally, and do not declare non-empty
+ `roles:` in frontmatter. All prompts live inside `scripts/workflow.py`.
-->
diff --git a/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/templates/scripts/workflow.py.template b/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/templates/scripts/workflow.py.template
new file mode 100644
index 0000000000..bdf6dd8270
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/templates/scripts/workflow.py.template
@@ -0,0 +1,190 @@
+"""Executable SwarmFlow workflow for <swarmskill-name>.
+
+Standalone Python workflow module: META + JSON Schema literals +
+explicit swarmflow primitive imports + async def run(args).
+"""
+import json
+
+from swarmflow import agent, compact, map_parallel, parallel, phase
+
+META = {
+ "name": "<swarmskill-name>",
+ "description": "<One-line description of the executable workflow>",
+ "whenToUse": "<When an Agent should REUSE this workflow directly>",
+ "phases": [
+ {"title": "<Phase 1>", "detail": "<What this phase accomplishes>"},
+ {"title": "<Phase 2>", "detail": "<What this phase accomplishes>"},
+ ],
+}
+
+# ---------------------------------------------------------------------------
+# JSON Schema for structured agent outputs.
+# agent() validates LLM response against this schema; if validation fails
+# the return may be None or a raw string — always wrap with extract_json().
+# ---------------------------------------------------------------------------
+ROLE_RESULT_SCHEMA = {
+ "type": "object",
+ "properties": {
+ "result": {"type": "string"},
+ "verdict": {"type": "string"},
+ },
+}
+
+
+# ---------------------------------------------------------------------------
+# Resilient helpers — every workflow gets these for free
+# ---------------------------------------------------------------------------
+
+def extract_json(text, fallback=None):
+ """Extract the first JSON object from text (LLM output may have prose).
+
+ Handles three cases:
+ 1. Already a dict — return as-is (agent() schema validation succeeded).
+ 2. Pure JSON string — parse directly.
+ 3. JSON embedded in prose — scan for outermost {…} and parse.
+ Falls back to *fallback* (default {}) if nothing parses.
+ """
+ if isinstance(text, dict):
+ return text
+ if not isinstance(text, str):
+ return fallback or {}
+ text = text.strip()
+ # Direct parse
+ try:
+ return json.loads(text)
+ except (json.JSONDecodeError, ValueError):
+ pass
+ # Scan for outermost { ... }
+ depth = 0
+ start = None
+ for i, ch in enumerate(text):
+ if ch == '{':
+ if depth == 0:
+ start = i
+ depth += 1
+ elif ch == '}':
+ depth -= 1
+ if depth == 0 and start is not None:
+ try:
+ return json.loads(text[start:i + 1])
+ except (json.JSONDecodeError, ValueError):
+ start = None
+ return fallback or {}
+
+
+def safe_get(obj, key, default=""):
+ """Safely get a key from an agent result, handling None/non-dict."""
+ if obj is None:
+ return default
+ if isinstance(obj, dict):
+ return obj.get(key, default)
+ return default
+
+
+def parse_args(args):
+ """Normalize args to dict. Swarmflow may pass JSON string or dict."""
+ if isinstance(args, dict):
+ return args
+ if isinstance(args, str):
+ try:
+ return json.loads(args) if args.strip() else {}
+ except json.JSONDecodeError:
+ return {}
+ return {}
+
+
+# ---------------------------------------------------------------------------
+# Prompt builders — keep prompts inside this script
+# ---------------------------------------------------------------------------
+
+def build_inline_prompt(role_id, payload):
+ """Build an inline prompt requesting JSON output."""
+ return f"""You are {role_id}.
+
+Task input:
+{json.dumps(payload, ensure_ascii=False) if isinstance(payload, (dict, list)) else payload}
+
+IMPORTANT: Return ONLY a valid JSON object. No markdown fences, no explanation, just JSON.
+Fields expected: "result" (string), "verdict" (string).
+You may include additional fields if they add value.
+"""
+
+
+# ---------------------------------------------------------------------------
+# Workflow entrypoint
+# ---------------------------------------------------------------------------
+
+async def run(args):
+ """Execute the workflow and return a JSON-serializable result."""
+ args = parse_args(args)
+
+ phase("<Phase 1>")
+ raw_results = await parallel(
+ [
+ lambda: agent(
+ build_inline_prompt("<role-id-1>", args),
+ label="<role-id-1>",
+ phase="<Phase 1>",
+ schema=ROLE_RESULT_SCHEMA,
+ ),
+ lambda: agent(
+ build_inline_prompt("<role-id-2>", args),
+ label="<role-id-2>",
+ phase="<Phase 1>",
+ schema=ROLE_RESULT_SCHEMA,
+ ),
+ ]
+ )
+ # Resilient extraction: schema validation may return None or raw string
+ role_results = compact([
+ extract_json(r, fallback={"result": "extraction_failed", "verdict": "unknown"})
+ for r in raw_results
+ ])
+
+ phase("<Phase 2>")
+ final_raw = await agent(
+ build_inline_prompt(
+ "<integrator-role-id>",
+ {"role_results": role_results, "original_args": args},
+ ),
+ label="integrate",
+ phase="<Phase 2>",
+ schema=ROLE_RESULT_SCHEMA,
+ )
+ final = extract_json(final_raw, fallback={"result": "integration_failed", "verdict": "unknown"})
+
+ return {
+ "status": "complete" if safe_get(final, "verdict") != "unknown" else "degraded",
+ "role_results": role_results,
+ "final": final,
+ }
+
+# TEMPLATE NOTES (delete before publishing):
+# - Keep META a pure literal; do not use calls, names, f-strings, or concatenation.
+# - Keep a top-level async def run(args) entrypoint.
+# - Keep all prompts in this file as constants or prompt-builder functions.
+# - Use explicit `from swarmflow import ...` imports.
+# - Use JSON Schema literals for structured agent outputs. Keep schema but
+# REMOVE "additionalProperties": False — it is too strict for LLM outputs and
+# causes agent() to silently return None when the LLM adds extra fields.
+# - ALWAYS wrap agent() return values with extract_json(..., fallback={...}).
+# agent() may return None (schema validation failed) or a raw string (no
+# schema match); extract_json handles both gracefully.
+# - ALWAYS call parse_args(args) at the top of run(). Swarmflow may pass args
+# as a JSON string instead of a dict.
+# - Use safe_get(obj, key, default) instead of obj["key"] or obj.get("key")
+# to handle None results and missing keys uniformly.
+# - If an agent(...) call passes phase="...", it must match the nearest active
+# phase("...") event for that block. Runtime statistics group by this value.
+# - Fixed heterogeneous roles: parallel([lambda: agent(...), ...]).
+# - Homogeneous dynamic item fan-out: map_parallel(items, fn).
+# - Per-item ordered multi-stage processing: pipeline(items, stage1, stage2).
+# - A single agent() or consecutive awaited agent() calls are sequential.
+# - Encode actual parallel/pipeline/gate/retry/degraded behavior here. workflow.md
+# explains this script but must not define a different topology.
+# - For custom parallel thunks, bind loop variables in lambda defaults to avoid
+# late-binding bugs.
+# - Cache validation: when loading cached results from incremental runs, verify
+# key fields are non-empty (not just that the cache file exists). An empty
+# scores list or null signal indicates a failed prior run and should be
+# treated as a cache miss, not a valid result to skip.