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): fix the problems caused by complex f-strings

z2tng5e05461a59df
diff --git a/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/SKILL.md b/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/SKILL.md
index 19c59f8971..2019c2d166 100644
--- a/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/SKILL.md
+++ b/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/SKILL.md
@@ -159,26 +159,7 @@ For the full Markdown spec + SwarmFlow shape, Stage 3b has two passes:
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.
+Generate `scripts/workflow.py` from [templates/scripts/workflow.py.template](templates/scripts/workflow.py.template). Before editing, read that template's `TEMPLATE AUTHORING CONSTRAINTS` block; it is the single full source for executable SwarmFlow script constraints. Keep this stage focused on routing and topology synchronization rather than restating those rules.
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.
@@ -226,18 +207,23 @@ Run the automated validator:
python scripts/validate_swarmskill.py path/to/<swarmskill-name>/
```
-The validator checks:
+The validator checks two output shapes:
+
+**Full Markdown spec**
- **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`
+
+**Script-only SwarmFlow**
+- **Structural**: exactly `SKILL.md` + `scripts/workflow.py`; no `roles/`, `workflow.md`, `bind.md`, `dependencies.yaml`, or `prompts/`
+- **SKILL.md**: valid frontmatter plus `## Workflow` and `## Files`; `roles:` omitted or empty
+- **SwarmFlow script safety envelope**: standalone script shape, inline prompts, safe imports, phase/agent consistency, schema permissiveness, and blocked runtime patterns
**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 Swarm Skill done.
+The full script authoring constraint list lives only in [templates/scripts/workflow.py.template](templates/scripts/workflow.py.template). 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 Swarm Skill done.
### Post-generation: Creation Summary + Community Enrichment
diff --git a/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/reference/compliance-checklist.md b/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/reference/compliance-checklist.md
index 21a5488e9c..32fc23703b 100644
--- a/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/reference/compliance-checklist.md
+++ b/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/reference/compliance-checklist.md
@@ -4,8 +4,10 @@
## What the validator script catches (do not duplicate here)
-The validator handles:
-- Five-file structure (SKILL.md / roles/ / workflow.md / bind.md / dependencies.yaml)
+The validator handles two output shapes:
+
+**Full Markdown spec**
+- Five-file structure (`SKILL.md` / `roles/` / `workflow.md` / `bind.md` / `dependencies.yaml`)
- Frontmatter required fields (`name`, `description`, `version`, `kind: swarm-skill`, `roles[]`)
- Each `roles[].id` has matching `roles/<id>.md`
- Each role file has the 5 mandatory sections
@@ -15,7 +17,12 @@ The validator handles:
- `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.**
+**Script-only SwarmFlow**
+- Minimal `SKILL.md` + `scripts/workflow.py`
+- No `roles/`, `workflow.md`, `bind.md`, `dependencies.yaml`, or `prompts/`
+- Executable `scripts/workflow.py` safety envelope
+
+The full SwarmFlow script authoring constraints live in [templates/scripts/workflow.py.template](../templates/scripts/workflow.py.template) under `TEMPLATE AUTHORING CONSTRAINTS`. Do not duplicate that list here. If the script reports failures, fix them first. **This checklist starts where the script ends.**
---
@@ -148,6 +155,46 @@ Read the `description` and ask:
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.
+### B9. SwarmFlow barriers are justified
+
+For every `parallel(...)` barrier, ask:
+
+- Does the next step genuinely need all prior results together?
+- If each item can continue independently, is the barrier adding avoidable latency?
+- Does the final report make partial branch failure visible to the user?
+
+A barrier is a latency cost. Use it only when it carries real cross-item semantics.
+
+### B10. Dynamic fan-out has explicit bounds
+
+For every dynamic fan-out or loop over user-provided input, confirm:
+
+- The chosen bound is meaningful for the task size, not an arbitrary silent cap.
+- Skipped or truncated work is visible in the returned result or user-facing report.
+- Empty input produces a clear skip/degraded outcome, not a misleading success.
+
+The validator can warn on suspicious shapes; it cannot judge whether the bound is correct for the user's domain.
+
+### B11. Runtime values are injected, not discovered
+
+If validator warnings around time, randomization, or file access are intentionally accepted, confirm:
+
+- The workflow explains why the runtime value cannot be supplied through `args` or runtime-provided data.
+- Resume, journal replay, and cache behavior remain understandable.
+- The final sign-off names the accepted warning instead of silently ignoring it.
+
+Unexplained runtime discovery makes replay and cache behavior hard to reason about.
+
+### B12. Semantic success is stronger than schema success
+
+For every integration/final result, verify:
+
+- The chosen success fields actually prove the answer is useful for this workflow.
+- Empty-but-schema-valid outputs cannot be reported as complete success.
+- Missing teammate outputs are visible in the returned result or user-facing report.
+
+Schema shape only proves the container exists; it does not prove the answer is useful.
+
---
## Part C: Cross-Swarm-Skill consistency (only when publishing multiple together)
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 9c1228793f..4a400bccd7 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
@@ -29,9 +29,11 @@ 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
+ - scripts/workflow.py, when present, satisfies the executable SwarmFlow
+ safety envelope: standalone shape, literal META, inline prompts, safe
+ imports, phase/agent consistency, permissive schemas, and blocked runtime
+ patterns. The full authoring constraint list lives in
+ templates/scripts/workflow.py.template.
What this script does NOT catch (judgment calls — see reference/compliance-checklist.md):
- Whether mottos are mutually antagonistic (anti-convergence quality)
@@ -43,6 +45,7 @@ What this script does NOT catch (judgment calls — see reference/compliance-che
from __future__ import annotations
import ast
+import builtins
import sys
import re
import logging
@@ -477,6 +480,26 @@ def validate_dependencies_yaml(path: Path, report: Report) -> dict[str, list[str
# SwarmFlow script validator
# ---------------------------------------------------------------------------
+SUPPORTED_SWARMFLOW_OPERATORS = {
+ "agent",
+ "budget",
+ "compact",
+ "flatten_filter",
+ "log",
+ "map_parallel",
+ "parallel",
+ "phase",
+ "pipeline",
+ "pmap",
+}
+
+PROTECTED_SWARMFLOW_NAMES = SUPPORTED_SWARMFLOW_OPERATORS
+NON_DETERMINISTIC_IMPORTS = {"random", "time", "datetime"}
+FILESYSTEM_CALLS = {"open"}
+PATH_IO_METHODS = {"read_text", "write_text", "read_bytes", "write_bytes", "open"}
+ASYNCIO_ORCHESTRATION_CALLS = {"gather", "create_task"}
+
+
def _is_literal(node: ast.AST) -> bool:
try:
ast.literal_eval(node)
@@ -491,6 +514,98 @@ def _string_literal(node: ast.AST) -> str | None:
return None
+def _literal_or_none(node: ast.AST) -> Any:
+ try:
+ return ast.literal_eval(node)
+ except (ValueError, TypeError):
+ return None
+
+
+def _set_parent_links(tree: ast.AST) -> None:
+ for parent in ast.walk(tree):
+ for child in ast.iter_child_nodes(parent):
+ setattr(child, "_parent", parent)
+
+
+def _parent(node: ast.AST) -> ast.AST | None:
+ parent = getattr(node, "_parent", None)
+ return parent if isinstance(parent, ast.AST) else None
+
+
+def _call_name(node: ast.Call) -> str | None:
+ if isinstance(node.func, ast.Name):
+ return node.func.id
+ if isinstance(node.func, ast.Attribute):
+ parts = [node.func.attr]
+ value = node.func.value
+ while isinstance(value, ast.Attribute):
+ parts.append(value.attr)
+ value = value.value
+ if isinstance(value, ast.Name):
+ parts.append(value.id)
+ return ".".join(reversed(parts))
+ return None
+
+
+def _is_inside_parallel_lambda(node: ast.AST) -> bool:
+ current = _parent(node)
+ while current is not None:
+ if isinstance(current, ast.Lambda):
+ lambda_node = current
+ container = _parent(lambda_node)
+ while container is not None:
+ if isinstance(container, ast.Call):
+ return _call_name(container) == "parallel"
+ if isinstance(container, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ return False
+ container = _parent(container)
+ return False
+ if isinstance(current, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ return False
+ current = _parent(current)
+ return False
+
+
+def _is_directly_awaited(node: ast.AST) -> bool:
+ current = _parent(node)
+ while isinstance(current, ast.Attribute):
+ current = _parent(current)
+ return isinstance(current, ast.Await)
+
+
+def _first_effective_statement(body: list[ast.stmt]) -> ast.stmt | None:
+ for stmt in body:
+ if (
+ isinstance(stmt, ast.Expr)
+ and isinstance(stmt.value, ast.Constant)
+ and isinstance(stmt.value.value, str)
+ ):
+ continue
+ return stmt
+ return None
+
+
+def _run_starts_with_parse_args(run_node: ast.AsyncFunctionDef) -> bool:
+ stmt = _first_effective_statement(run_node.body)
+ if not isinstance(stmt, ast.Assign):
+ return False
+ if len(stmt.targets) != 1:
+ return False
+ target = stmt.targets[0]
+ value = stmt.value
+ return (
+ isinstance(target, ast.Name)
+ and target.id == "args"
+ and isinstance(value, ast.Call)
+ and isinstance(value.func, ast.Name)
+ and value.func.id == "parse_args"
+ and len(value.args) == 1
+ and not value.keywords
+ and isinstance(value.args[0], ast.Name)
+ and value.args[0].id == "args"
+ )
+
+
class _AgentCallCollector(ast.NodeVisitor):
def __init__(self) -> None:
self.calls: list[ast.Call] = []
@@ -510,16 +625,32 @@ class _AgentCallCollector(ast.NodeVisitor):
self.generic_visit(node)
-def _phase_call_value(stmt: ast.stmt) -> str | None:
+def _phase_call_info(stmt: ast.stmt) -> tuple[bool, str | None, int | str]:
if not isinstance(stmt, ast.Expr) or not isinstance(stmt.value, ast.Call):
- return None
+ return False, 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]:
+ if not isinstance(call.func, ast.Name) or call.func.id != "phase":
+ return False, None, "?"
+ if not call.args:
+ return True, None, getattr(call, "lineno", "?")
+ return True, _string_literal(call.args[0]), getattr(call, "lineno", "?")
+
+
+def _phase_titles_from_meta(meta: dict[str, Any]) -> set[str]:
+ phases = meta.get("phases")
+ if not isinstance(phases, list):
+ return set()
+ return {
+ phase["title"]
+ for phase in phases
+ if isinstance(phase, dict) and isinstance(phase.get("title"), str)
+ }
+
+
+def _agent_phase_mismatches(
+ run_node: ast.AsyncFunctionDef,
+ allowed_phases: set[str] | None = None,
+) -> list[str]:
mismatches: list[str] = []
current_phase: str | None = None
@@ -527,19 +658,38 @@ def _agent_phase_mismatches(run_node: ast.AsyncFunctionDef) -> list[str]:
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
+ is_phase_call, phase_value, phase_line = _phase_call_info(stmt)
+ if is_phase_call:
+ if phase_value is None:
+ mismatches.append(f"line {phase_line}: phase() must use a string literal")
+ else:
+ current_phase = phase_value
+ if allowed_phases is not None and phase_value not in allowed_phases:
+ mismatches.append(
+ f"line {phase_line}: phase {phase_value!r} is not declared in META.phases"
+ )
collector = _AgentCallCollector()
collector.visit(stmt)
for call in collector.calls:
+ line = getattr(call, "lineno", "?")
+ label_kw = next((kw for kw in call.keywords if kw.arg == "label"), None)
+ if label_kw is None:
+ mismatches.append(f"line {line}: agent must pass a stable label='...'")
+ else:
+ label_value = _string_literal(label_kw.value)
+ if label_value is None or not label_value.strip():
+ mismatches.append(f"line {line}: agent label must be a non-empty string literal")
+
phase_kw = next((kw for kw in call.keywords if kw.arg == "phase"), None)
- if phase_kw is None or current_phase is None:
+ if current_phase is None:
+ mismatches.append(f"line {line}: agent must appear after a phase(...) call")
+ continue
+ if phase_kw is None:
+ mismatches.append(f"line {line}: agent must pass phase={current_phase!r}")
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}"
@@ -552,6 +702,420 @@ def _agent_phase_mismatches(run_node: ast.AsyncFunctionDef) -> list[str]:
return mismatches
+def _phase_coverage_issues(
+ run_node: ast.AsyncFunctionDef,
+ required_phases: set[str],
+) -> list[str]:
+ if not required_phases:
+ return []
+
+ called_phases: set[str] = set()
+ for stmt in run_node.body:
+ is_phase_call, phase_value, _phase_line = _phase_call_info(stmt)
+ if is_phase_call and phase_value is not None:
+ called_phases.add(phase_value)
+
+ return [
+ f"META.phases declares {phase_title!r}, but run() never calls phase({phase_title!r})"
+ for phase_title in sorted(required_phases - called_phases)
+ ]
+
+
+def _validate_meta_shape(meta: dict[str, Any]) -> list[str]:
+ issues: list[str] = []
+ for field in ("name", "description"):
+ if not isinstance(meta.get(field), str) or not meta.get(field, "").strip():
+ issues.append(f"META.{field} must be a non-empty string literal")
+
+ phases = meta.get("phases")
+ if not isinstance(phases, list):
+ issues.append("META.phases must be a list of literal phase objects")
+ return issues
+
+ for index, item in enumerate(phases):
+ if not isinstance(item, dict):
+ issues.append(f"META.phases[{index}] must be an object")
+ continue
+ for field in ("title", "detail"):
+ if not isinstance(item.get(field), str) or not item.get(field, "").strip():
+ issues.append(f"META.phases[{index}].{field} must be a non-empty string")
+ return issues
+
+
+def _log_call_issues(tree: ast.Module) -> list[str]:
+ issues: list[str] = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ if not isinstance(node.func, ast.Name) or node.func.id != "log":
+ continue
+ if len(node.args) != 1 or node.keywords:
+ line = getattr(node, "lineno", "?")
+ issues.append(f"line {line}: log() must be called with exactly one positional argument")
+ return issues
+
+
+def _schema_strictness_issues(tree: ast.Module) -> list[str]:
+ issues: list[str] = []
+ candidate_dicts: list[ast.Dict] = []
+
+ for node in ast.walk(tree):
+ if isinstance(node, (ast.Assign, ast.AnnAssign)):
+ value = node.value
+ targets = [node.target] if isinstance(node, ast.AnnAssign) else list(node.targets)
+ if not isinstance(value, ast.Dict):
+ continue
+ for target in targets:
+ if isinstance(target, ast.Name) and "SCHEMA" in target.id.upper():
+ candidate_dicts.append(value)
+ elif isinstance(node, ast.Call):
+ for kw in node.keywords:
+ if kw.arg == "schema" and isinstance(kw.value, ast.Dict):
+ candidate_dicts.append(kw.value)
+
+ def visit_schema_dict(node: ast.Dict) -> None:
+ for key_node, value_node in zip(node.keys, node.values, strict=False):
+ key = _literal_or_none(key_node) if key_node is not None else None
+ line = getattr(key_node or node, "lineno", getattr(node, "lineno", "?"))
+ if key == "required":
+ issues.append(f"line {line}: JSON Schema must not use required")
+ if key == "additionalProperties" and _literal_or_none(value_node) is False:
+ issues.append(f"line {line}: JSON Schema must not use additionalProperties=False")
+
+ for key_node, value_node in zip(node.keys, node.values, strict=False):
+ key = _literal_or_none(key_node) if key_node is not None else None
+ if key == "properties" and isinstance(value_node, ast.Dict):
+ for property_schema in value_node.values:
+ if isinstance(property_schema, ast.Dict):
+ visit_schema_dict(property_schema)
+ continue
+ if isinstance(value_node, ast.Dict):
+ visit_schema_dict(value_node)
+ elif isinstance(value_node, (ast.List, ast.Tuple)):
+ for item in value_node.elts:
+ if isinstance(item, ast.Dict):
+ visit_schema_dict(item)
+
+ for schema_node in candidate_dicts:
+ visit_schema_dict(schema_node)
+ return sorted(set(issues))
+
+
+def _asyncio_orchestration_aliases(tree: ast.Module) -> tuple[set[str], set[str]]:
+ module_aliases: set[str] = set()
+ function_aliases: set[str] = set()
+
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ for alias in node.names:
+ if alias.name == "asyncio":
+ module_aliases.add(alias.asname or alias.name)
+ elif isinstance(node, ast.ImportFrom) and node.module == "asyncio":
+ for alias in node.names:
+ if alias.name in ASYNCIO_ORCHESTRATION_CALLS:
+ function_aliases.add(alias.asname or alias.name)
+
+ return module_aliases, function_aliases
+
+
+def _is_module_level_mutable_assignment(node: ast.Assign | ast.AnnAssign) -> bool:
+ value = node.value
+ targets = [node.target] if isinstance(node, ast.AnnAssign) else list(node.targets)
+ target_names = [target.id for target in targets if isinstance(target, ast.Name)]
+ is_constant = all(name.isupper() for name in target_names if name)
+ is_mutable_literal = isinstance(value, (ast.List, ast.Dict, ast.Set))
+ is_set_call = (
+ isinstance(value, ast.Call)
+ and isinstance(value.func, ast.Name)
+ and value.func.id in {"set", "dict", "list"}
+ )
+ if not target_names:
+ return False
+ if is_constant:
+ return False
+ return is_mutable_literal or is_set_call
+
+
+def _is_asyncio_orchestration_alias_call(node: ast.Call, asyncio_modules: set[str]) -> bool:
+ if not isinstance(node.func, ast.Attribute):
+ return False
+ if node.func.attr not in ASYNCIO_ORCHESTRATION_CALLS:
+ return False
+ if not isinstance(node.func.value, ast.Name):
+ return False
+ return node.func.value.id in asyncio_modules
+
+
+def _runtime_call_issues(tree: ast.Module) -> tuple[list[str], list[str]]:
+ errors: list[str] = []
+ warnings: list[str] = []
+ asyncio_modules, asyncio_functions = _asyncio_orchestration_aliases(tree)
+
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ for alias in node.names:
+ root = alias.name.split(".", 1)[0]
+ if root in NON_DETERMINISTIC_IMPORTS:
+ warnings.append(
+ f"line {getattr(node, 'lineno', '?')}: imports non-deterministic module "
+ f"{alias.name!r}; pass values via args"
+ )
+ elif isinstance(node, ast.ImportFrom):
+ module = node.module or ""
+ root = module.split(".", 1)[0]
+ if root in NON_DETERMINISTIC_IMPORTS:
+ warnings.append(
+ f"line {getattr(node, 'lineno', '?')}: imports non-deterministic module "
+ f"{module!r}; pass values via args"
+ )
+ elif isinstance(node, ast.While):
+ warnings.append(
+ f"line {getattr(node, 'lineno', '?')}: loop must document a stop condition "
+ "(max_rounds, dry_count, budget guard, or input cap)"
+ )
+ elif isinstance(node, (ast.Assign, ast.AnnAssign)) and isinstance(_parent(node), ast.Module):
+ if _is_module_level_mutable_assignment(node):
+ warnings.append(
+ f"line {getattr(node, 'lineno', '?')}: avoid module-level mutable state; "
+ "keep run state inside run(args)"
+ )
+ elif isinstance(node, ast.Call):
+ line = getattr(node, "lineno", "?")
+ call_name = _call_name(node)
+ if call_name in {"asyncio.gather", "asyncio.create_task"}:
+ errors.append(f"line {line}: use SwarmFlow parallel/pipeline instead of asyncio")
+ elif _is_asyncio_orchestration_alias_call(node, asyncio_modules):
+ errors.append(f"line {line}: use SwarmFlow parallel/pipeline instead of asyncio")
+ elif call_name in asyncio_functions:
+ errors.append(f"line {line}: use SwarmFlow parallel/pipeline instead of asyncio")
+ elif call_name == "print":
+ errors.append(f"line {line}: use swarmflow.log(), not print()")
+ elif call_name == "budget":
+ errors.append(f"line {line}: budget is an imported singleton; use budget.remaining(), not budget()")
+ elif call_name == "agent":
+ if node.args and _string_literal(node.args[0]) == "":
+ errors.append(f"line {line}: agent prompt must not be an empty string")
+ if not _is_directly_awaited(node) and not _is_inside_parallel_lambda(node):
+ errors.append(f"line {line}: agent() must be awaited or returned from a parallel thunk")
+ elif call_name in {"map_parallel", "pmap"}:
+ warnings.append(
+ f"line {line}: dynamic fan-out should declare an item cap and log skipped work "
+ "(no silent caps)"
+ )
+ elif call_name == "pipeline":
+ warnings.append(
+ f"line {line}: dynamic pipeline should declare an item cap and handle empty input"
+ )
+ for arg in node.args[1:]:
+ if isinstance(arg, ast.Lambda) and len(arg.args.args) != 3:
+ warnings.append(
+ f"line {getattr(arg, 'lineno', line)}: pipeline stage should accept "
+ "(prev, item, index)"
+ )
+ elif call_name in FILESYSTEM_CALLS:
+ warnings.append(f"line {line}: avoid direct filesystem access in workflow.py")
+ elif call_name in {"time.time", "datetime.now", "datetime.utcnow"}:
+ warnings.append(f"line {line}: current time access is non-deterministic; pass values via args")
+
+ if isinstance(node.func, ast.Attribute) and node.func.attr in PATH_IO_METHODS:
+ warnings.append(
+ f"line {line}: avoid direct filesystem access via Path.{node.func.attr} in workflow.py"
+ )
+
+ return sorted(set(errors)), sorted(set(warnings))
+
+
+def _swarmflow_imported_names(tree: ast.Module) -> set[str]:
+ names: set[str] = set()
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.ImportFrom):
+ continue
+ module = node.module or ""
+ if module != "swarmflow" and not module.startswith("swarmflow."):
+ continue
+ for alias in node.names:
+ names.add(alias.asname or alias.name)
+ return names
+
+
+def _swarmflow_import_issues(tree: ast.Module) -> list[str]:
+ issues: list[str] = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.ImportFrom):
+ continue
+ module = node.module or ""
+ if module != "swarmflow" and not module.startswith("swarmflow."):
+ continue
+ line = getattr(node, "lineno", "?")
+ if not isinstance(_parent(node), ast.Module):
+ issues.append(f"line {line}: swarmflow imports must be top-level")
+ if module != "swarmflow":
+ issues.append(f"line {line}: import primitives directly from `swarmflow`, not {module!r}")
+ for alias in node.names:
+ if alias.name == "*":
+ issues.append(f"line {line}: import * from swarmflow is not allowed")
+ continue
+ if alias.name not in SUPPORTED_SWARMFLOW_OPERATORS:
+ issues.append(f"line {line}: unsupported swarmflow operator {alias.name!r}")
+ if alias.asname:
+ issues.append(f"line {line}: import swarmflow.{alias.name} without aliasing it")
+ return sorted(set(issues))
+
+
+def _dynamic_import_issues(tree: ast.Module) -> list[str]:
+ issues: list[str] = []
+
+ def is_sys_modules_lookup(node: ast.AST) -> bool:
+ if not isinstance(node, ast.Subscript):
+ return False
+ if not isinstance(node.value, ast.Attribute):
+ return False
+ if not isinstance(node.value.value, ast.Name):
+ return False
+ if node.value.value.id != "sys":
+ return False
+ return node.value.attr == "modules"
+
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ line = getattr(node, "lineno", "?")
+ call_name = _call_name(node)
+ if call_name == "__import__":
+ issues.append(f"line {line}: dynamic import via __import__ is not allowed")
+ elif call_name == "importlib.import_module":
+ issues.append(f"line {line}: dynamic import via importlib.import_module is not allowed")
+ elif call_name == "getattr" and node.args:
+ first_arg = node.args[0]
+ if is_sys_modules_lookup(first_arg):
+ issues.append(f"line {line}: dynamic operator lookup through sys.modules is not allowed")
+ return sorted(set(issues))
+
+
+def _log_operator_issues(tree: ast.Module) -> list[str]:
+ issues: list[str] = []
+ swarmflow_names = _swarmflow_imported_names(tree)
+ if "log" not in swarmflow_names:
+ issues.append("missing `log` in explicit `from swarmflow import ...` primitive import")
+
+ for node in ast.walk(tree):
+ line = getattr(node, "lineno", "?")
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ if node.name in PROTECTED_SWARMFLOW_NAMES:
+ issues.append(
+ f"line {line}: local `{node.__class__.__name__} {node.name}` "
+ f"shadows swarmflow.{node.name}"
+ )
+ for arg in (
+ *node.args.posonlyargs,
+ *node.args.args,
+ *node.args.kwonlyargs,
+ ):
+ if arg.arg in PROTECTED_SWARMFLOW_NAMES:
+ issues.append(
+ f"line {getattr(arg, 'lineno', line)}: parameter `{arg.arg}` "
+ f"shadows swarmflow.{arg.arg}"
+ )
+ if node.args.vararg and node.args.vararg.arg in PROTECTED_SWARMFLOW_NAMES:
+ issues.append(
+ f"line {getattr(node.args.vararg, 'lineno', line)}: parameter "
+ f"`{node.args.vararg.arg}` shadows swarmflow.{node.args.vararg.arg}"
+ )
+ if node.args.kwarg and node.args.kwarg.arg in PROTECTED_SWARMFLOW_NAMES:
+ issues.append(
+ f"line {getattr(node.args.kwarg, 'lineno', line)}: parameter "
+ f"`{node.args.kwarg.arg}` shadows swarmflow.{node.args.kwarg.arg}"
+ )
+ elif isinstance(node, ast.Import):
+ for alias in node.names:
+ bound = alias.asname or alias.name.split(".", 1)[0]
+ if bound in PROTECTED_SWARMFLOW_NAMES:
+ issues.append(f"line {line}: import binds `{bound}` outside swarmflow.{bound}")
+ elif isinstance(node, ast.ImportFrom):
+ module = node.module or ""
+ for alias in node.names:
+ bound = alias.asname or alias.name
+ if bound in PROTECTED_SWARMFLOW_NAMES and module != "swarmflow":
+ issues.append(f"line {line}: import binds `{bound}` outside swarmflow.{bound}")
+ elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
+ if node.id in PROTECTED_SWARMFLOW_NAMES:
+ issues.append(f"line {line}: assignment target `{node.id}` shadows swarmflow.{node.id}")
+
+ return sorted(set(issues))
+
+
+def _collect_bound_names(tree: ast.Module) -> set[str]:
+ """Over-approximate every name that could be bound anywhere in the module.
+
+ Intentionally scope-agnostic: collecting names module-wide errs toward
+ fewer false positives for the f-string check below.
+ """
+ bound: set[str] = set()
+ for node in ast.walk(tree):
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ bound.add(node.name)
+ a = node.args
+ for arg in (*a.posonlyargs, *a.args, *a.kwonlyargs):
+ bound.add(arg.arg)
+ if a.vararg:
+ bound.add(a.vararg.arg)
+ if a.kwarg:
+ bound.add(a.kwarg.arg)
+ elif isinstance(node, ast.Lambda):
+ a = node.args
+ for arg in (*a.posonlyargs, *a.args, *a.kwonlyargs):
+ bound.add(arg.arg)
+ if a.vararg:
+ bound.add(a.vararg.arg)
+ if a.kwarg:
+ bound.add(a.kwarg.arg)
+ elif isinstance(node, ast.ClassDef):
+ bound.add(node.name)
+ elif isinstance(node, ast.Import):
+ for alias in node.names:
+ bound.add(alias.asname or alias.name.split(".")[0])
+ elif isinstance(node, ast.ImportFrom):
+ for alias in node.names:
+ bound.add(alias.asname or alias.name)
+ elif isinstance(node, ast.Name) and isinstance(node.ctx, (ast.Store, ast.Del)):
+ # Covers assignments, for/with targets, comprehension vars, walrus.
+ bound.add(node.id)
+ elif isinstance(node, ast.ExceptHandler) and node.name:
+ bound.add(node.name)
+ elif isinstance(node, (ast.Global, ast.Nonlocal)):
+ bound.update(node.names)
+ return bound
+
+
+def _fstring_undefined_names(tree: ast.Module) -> list[tuple[int, str]]:
+ """Find names referenced inside f-strings that are never bound anywhere.
+
+ Catches the literal-brace trap: a prompt with `{N}` inside an f-string is
+ parsed as the expression N and raises NameError at runtime (valid syntax,
+ so ast.parse alone never flags it).
+ """
+ bound = _collect_bound_names(tree)
+ builtin_names = set(dir(builtins))
+ findings: list[tuple[int, str]] = []
+ seen: set[tuple[int, str]] = set()
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.JoinedStr):
+ continue
+ for value in node.values:
+ if not isinstance(value, ast.FormattedValue):
+ continue
+ for sub in ast.walk(value.value):
+ if isinstance(sub, ast.Name) and isinstance(sub.ctx, ast.Load):
+ if sub.id in bound or sub.id in builtin_names:
+ continue
+ line = getattr(sub, "lineno", getattr(node, "lineno", 0))
+ key = (line, sub.id)
+ if key not in seen:
+ seen.add(key)
+ findings.append(key)
+ return findings
+
+
def validate_swarmflow_script(path: Path, skill_name: str, report: Report) -> None:
file_label = "scripts/workflow.py"
if not path.exists():
@@ -568,12 +1132,24 @@ def validate_swarmflow_script(path: Path, skill_name: str, report: Report) -> No
report.err(file_label, "contains an obvious local absolute path")
try:
- tree = ast.parse(text, filename=str(path))
+ feature_version = min(sys.version_info[:2], (3, 13))
+ tree = ast.parse(text, filename=str(path), feature_version=feature_version)
except SyntaxError as e:
report.err(file_label, f"Python syntax error: {e.msg} at line {e.lineno}")
return
+ _set_parent_links(tree)
+
+ for line, name in _fstring_undefined_names(tree):
+ report.err(
+ file_label,
+ f"line {line}: f-string references undefined name {name!r} — a literal "
+ f"brace like {{{name}}} in prompt text is parsed as a Python expression "
+ f"and crashes at runtime. Use string.Template ($-placeholders) or "
+ f"concatenate the dynamic part instead.",
+ )
meta_node: ast.AST | None = None
+ allowed_phases: set[str] | None = None
run_node: ast.AsyncFunctionDef | None = None
has_swarmflow_import = False
dangerous_imports: list[str] = []
@@ -626,6 +1202,9 @@ def validate_swarmflow_script(path: Path, skill_name: str, report: Report) -> No
report.err(file_label, "`META` must be a pure literal dict")
else:
meta = ast.literal_eval(meta_node)
+ allowed_phases = _phase_titles_from_meta(meta)
+ for issue in _validate_meta_shape(meta):
+ report.err(file_label, issue)
if meta.get("name") != skill_name:
report.warn(
file_label,
@@ -640,9 +1219,29 @@ def validate_swarmflow_script(path: Path, skill_name: str, report: Report) -> No
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)
+ if not _run_starts_with_parse_args(run_node):
+ report.err(file_label, "`run` must start with `args = parse_args(args)`")
+ phase_mismatches = _agent_phase_mismatches(run_node, allowed_phases)
for mismatch in phase_mismatches:
report.err(file_label, mismatch)
+ for issue in _phase_coverage_issues(run_node, allowed_phases or set()):
+ report.err(file_label, issue)
+
+ for issue in _log_call_issues(tree):
+ report.err(file_label, issue)
+ for issue in _log_operator_issues(tree):
+ report.err(file_label, issue)
+ for issue in _swarmflow_import_issues(tree):
+ report.err(file_label, issue)
+ for issue in _dynamic_import_issues(tree):
+ report.err(file_label, issue)
+ for issue in _schema_strictness_issues(tree):
+ report.err(file_label, issue)
+ runtime_errors, runtime_warnings = _runtime_call_issues(tree)
+ for issue in runtime_errors:
+ report.err(file_label, issue)
+ for issue in runtime_warnings:
+ report.warn(file_label, issue)
if not has_swarmflow_import:
report.err(file_label, "missing explicit `from swarmflow import ...` primitive import")
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
index bdf6dd8270..1d2cb3dcd9 100644
--- 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
@@ -1,190 +1,287 @@
-"""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.
+"""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 string import Template
+
+from swarmflow import agent, compact, log, 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.
+ """
+ fallback_value = {} if fallback is None else fallback
+ if isinstance(text, dict):
+ return text
+ if not isinstance(text, str):
+ return fallback_value
+ text = text.strip()
+ # Direct parse
+ try:
+ parsed = json.loads(text)
+ return parsed if isinstance(parsed, dict) else fallback_value
+ except (json.JSONDecodeError, ValueError):
+ pass
+ # Scan for outermost { ... }
+ depth = 0
+ start = None
+ in_string = False
+ escaped = False
+ for i, ch in enumerate(text):
+ if in_string:
+ if escaped:
+ escaped = False
+ elif ch == "\\":
+ escaped = True
+ elif ch == '"':
+ in_string = False
+ continue
+ if ch == '"':
+ in_string = True
+ if ch == '{':
+ if depth == 0:
+ start = i
+ depth += 1
+ elif ch == '}' and depth > 0:
+ depth -= 1
+ if depth == 0 and start is not None:
+ try:
+ parsed = json.loads(text[start:i + 1])
+ return parsed if isinstance(parsed, dict) else fallback_value
+ except (json.JSONDecodeError, ValueError):
+ start = None
+ return fallback_value
+
+
+def safe_get(obj, key, default=""):
+ """Safely get a key from an agent result, handling None/non-dict."""
+ if obj is None:
+ return str(default)
+ if isinstance(obj, dict):
+ return str(obj.get(key, default))
+ return str(default)
+
+
+def has_meaningful_result(obj):
+ """Return True only when semantic success fields are non-empty."""
+ return (
+ safe_get(obj, "verdict", "unknown") != "unknown"
+ and bool(safe_get(obj, "result", "").strip())
+ )
+
+
+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.
+# Use string.Template ($-placeholders) so literal braces in prompt prose or JSON
+# examples are never interpreted as Python expressions (an f-string would treat
+# a literal `{N}` as the variable N and raise NameError at runtime).
+# ---------------------------------------------------------------------------
+
+INLINE_PROMPT = Template(
+ """You are $role_id.
+
+Task input:
+$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.
+"""
+)
+
+
+def build_inline_prompt(role_id, payload):
+ """Build an inline prompt requesting JSON output."""
+ payload_text = (
+ json.dumps(payload, ensure_ascii=False)
+ if isinstance(payload, (dict, list))
+ else str(payload)
+ )
+ return INLINE_PROMPT.substitute(role_id=role_id, payload=payload_text)
+
+
+# ---------------------------------------------------------------------------
+# Workflow entrypoint
+# ---------------------------------------------------------------------------
+
+async def run(args):
+ """Execute the workflow and return a JSON-serializable result."""
+ args = parse_args(args)
+
+ phase("<Phase 1>")
+ log("Starting <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>")
+ log("Starting <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 has_meaningful_result(final) else "degraded",
+ "role_results": role_results,
+ "final": final,
+ }
+
+# TEMPLATE AUTHORING CONSTRAINTS (delete before publishing):
+# This block is the canonical full constraint list for SwarmFlow workflow
+# scripts generated by swarmskill-creator. SKILL.md, the compliance checklist,
+# and the validator summarize or enforce parts of this list; do not duplicate
+# the full list elsewhere.
+# - 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.
+# - Build prompts with string.Template as shown above, not f-strings/str.format
+# (see the prompt-builder comment for why). The validator rejects f-strings
+# that reference undefined names.
+# - Use top-level explicit `from swarmflow import ...` imports for the operators
+# this script actually uses. Do not use import *, delayed imports, aliases, or
+# dynamic import/importlib/getattr(sys.modules[...]) lookup. Do not import or
+# call workflow(...): sub-workflow composition is not part of this template's
+# supported surface. The supported operators are agent, budget, compact,
+# flatten_filter, log, map_parallel, parallel, phase, pipeline, and pmap.
+# - Do not define variables, functions, parameters, or classes named like
+# SwarmFlow operators. They shadow the imported runtime primitives.
+# - Use JSON Schema literals for structured agent outputs. Keep schema but
+# REMOVE schema-object keywords "additionalProperties": False and "required"
+# — both are too strict for LLM outputs and can cause agent() to silently
+# return None. A business output field named "required" under "properties" is
+# allowed; the ban is on the JSON Schema strictness keyword.
+# - For this template, every agent() call should request JSON and be wrapped
+# with extract_json(..., fallback={...}). agent() may return None (schema
+# validation failed) or a raw string (no schema match); extract_json handles
+# both gracefully.
+# - After extract_json(...), verify semantic key fields before treating a
+# result as successful. Missing or empty key fields should trigger fallback,
+# retry, or degraded handling.
+# - 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.
+# - Import and use `log` from swarmflow. Do not define a local log() helper,
+# assign to `log`, or import another logging function as `log`; those calls
+# will not show in SwarmFlow workflow logs.
+# - Use log(...), not print(...), for workflow-visible runtime messages.
+# - phase("...") is a stable workflow stage, not a progress log; use log("...")
+# for events. Every META["phases"][].title must have a matching phase("...")
+# call in run().
+# - Every agent(...) must pass phase="..." exactly equal to the nearest active
+# phase("...") string; no aliases, paraphrases, dynamic labels, or prefixes.
+# - Every agent(...) must pass a stable literal label="..."; dynamic labels are
+# rejected so progress groups and failure locations stay stable.
+# - log(...) takes exactly one positional argument; format details into one string.
+# - Default multi-stage item work to pipeline(items, stage1, stage2, ...).
+# Use parallel([...]) as a barrier only when the next step genuinely needs all
+# prior results together, such as dedup/merge, early zero-count exit, or
+# cross-item comparison.
+# - Fixed heterogeneous roles inside one phase: parallel([lambda: agent(...), ...]).
+# - Homogeneous dynamic item fan-out: map_parallel(items, fn). Declare an item
+# cap and log skipped work; do not silently truncate user input.
+# - Per-item ordered multi-stage processing: pipeline(items, stage1, stage2).
+# Each pipeline stage receives (prev_result, original_item, index), not just
+# the previous result.
+# If you use extra primitives such as pipeline/log/flatten_filter, add them
+# to the explicit swarmflow import.
+# - Do not use asyncio.gather/create_task around agent calls, including alias
+# forms such as import asyncio as aio or from asyncio import gather. Use
+# parallel() or pipeline() so resume, counters, and progress grouping stay
+# correct.
+# - Outside parallel thunks, await every agent() call. Inside parallel([...]),
+# pass thunks such as lambda: agent(...); if intermediate awaits are needed,
+# use an async def thunk.
+# - A single agent() or consecutive awaited agent() calls are sequential.
+# - Encode actual parallel/pipeline/gate/retry/degraded behavior here. When
+# workflow.md exists, it 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. Prefer map_parallel(items, fn) for homogeneous fan-out.
+# - parallel([...]) may return [dict, None, dict] when one branch fails. Always
+# compact/filter results before integration, and report missing branches.
+# - Dynamic fan-out and loops must have a visible stop condition. Use at least
+# one of: max_rounds, dry_count/no-new-results limit, budget guard, or input
+# length cap. Do not write unbounded while loops or recursive fan-out.
+# - Handle empty input sequences before indexing results[0] or assuming work ran.
+# - Avoid non-determinism inside workflow.py: no random values, current time, or
+# direct filesystem reads/writes. Pass timestamps, sampled inputs, and file
+# contents through args or runtime-provided data instead.
+# - Keep all mutable run state inside run(args). Do not use module-level lists,
+# dicts, sets, caches, counters, or accumulated results.
+# - 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.