Install
$ agentstack add skill-rokoss21-swarm-iosm-swarm-iosm ✓ scanned · ✓ verified — works with Claude Code, Cursor, and more.
Security review
✓ PassedNo issues found. Passed automated security review. · v0.1.0 How review works →
- ✓ Prompt-injection patterns
- ✓ Secret / credential exfiltration
- ✓ Dangerous shell & filesystem operations
- ✓ Untrusted network calls
- ✓ Known-malicious package signatures
What it can access
- ✓ Network access No
- ✓ Filesystem access No
- ✓ Shell / process execution No
- ✓ Environment & secrets No
- ✓ Dynamic code execution No
From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.
About
Swarm Workflow (IOSM)
A structured workflow for complex development tasks that combines PRD-driven planning, parallel subagent execution, and IOSM (Improve→Optimize→Shrink→Modularize) quality gates.
Quick Start
For new features/projects (Greenfield):
/swarm-iosm new-track "Add user authentication with JWT"
For existing codebases (Brownfield):
/swarm-iosm setup
/swarm-iosm new-track "Refactor payment processing module"
Check progress:
/swarm-iosm status
When to Use This Skill
Use Swarm Workflow when:
- Task requires multiple parallel work streams (exploration, implementation, testing, docs)
- Need formal PRD and decomposition for complex features
- Want structured reports and traceability ("who did what and why")
- Brownfield refactoring that needs careful planning and rollback strategy
- Team collaboration requiring artifact-based handoffs
- Quality gates (IOSM) are needed for acceptance
Don't use for:
- Simple single-file changes
- Quick bug fixes
- Exploratory tasks without implementation
Core Commands
/swarm-iosm setup
Initialize project context for Swarm workflow.
What it does:
- Creates
swarm/directory structure - Generates project context files (product.md, tech-stack.md, workflow.md)
- Initializes tracks.md registry
When to use: First time in a project, or when project context has significantly changed.
/swarm-iosm new-track ""
Create a new feature/task track with PRD and implementation plan.
What it does:
- Requirements gathering (AskUserQuestion for mode/priorities/constraints)
- Generate PRD (
swarm/tracks//PRD.md) - Create spec (
spec.md) and plan (plan.md) with phases/tasks/dependencies - Identify subagent roles needed
- Create metadata.json with track info
Arguments: Brief description of the feature/task (e.g., "Add OAuth2 authentication")
/swarm-iosm implement [track-id]
Execute the implementation plan using parallel subagents.
What it does:
- Load plan from track
- Identify parallelizable tasks vs. sequential chains
- Launch subagents (suggests background for long-running, foreground for interactive)
- Each subagent produces structured report in
reports/ - Monitor progress and collect outputs
Arguments: Optional track-id (defaults to most recent track)
/swarm-iosm status [track-id]
Show progress summary for a track.
What it does:
- Parse plan.md for task statuses
- List completed reports
- Show blockers and open questions
- Display dependency chain status
/swarm-iosm watch [track-id]
Open a live monitoring dashboard for a track. (v1.3)
What it does:
- Calculates real-time metrics (velocity, ETA, progress %)
- Renders an ASCII progress bar
- Shows status of all tasks in the track
- Refreshes data from reports and checkpoints
Example usage:
/swarm-iosm watch
/swarm-iosm simulate [track-id]
Run a dry-run simulation of the implementation plan. (v1.3)
What it does:
- Loads implementation plan and resource constraints
- Simulates dispatch loop with virtual time
- Identifies bottlenecks and potential conflicts
- Generates ASCII timeline and simulation report
- Estimates total parallel execution time vs serial
Example usage:
/swarm-iosm simulate
/swarm-iosm simulate 2026-01-17-001
/swarm-iosm resume [track-id]
Resume an interrupted implementation from the latest checkpoint. (v1.3)
What it does:
- Loads latest checkpoint from
checkpoints/latest.json - Reconciles state by reading all report files in
reports/ - Identifies completed vs pending tasks
- Recalculates the ready queue
- Shows a summary of progress and next steps
Example usage:
/swarm-iosm resume
/swarm-iosm resume 2026-01-17-001
/swarm-iosm retry [--foreground] [--reset-brief]
Retry a failed task with optional mode changes. (v1.2)
What it does:
- Reads error diagnosis from task report using parse_errors.py
- Shows error diagnosis to user with suggested fixes
- Asks user to choose: apply fix, manual fix, or skip
- Regenerates subagent brief with error context
- Relaunches task using Task tool
- Tracks retry count (max 3 per task)
Arguments:
- ``: Task to retry (e.g., T04)
--foreground: Force foreground execution (for interactive debugging)--reset-brief: Regenerate brief from scratch (vs. reuse existing)
Error-specific behaviors:
- Permission Denied: Always suggest --foreground
- MCP Tool Unavailable: Force foreground mode
- Import Error: Suggest pip install before retry
- Test Failed: Ask user: "Fix code or update tests?"
Example usage:
/swarm-iosm retry T04
/swarm-iosm retry T04 --foreground
/swarm-iosm retry T04 --reset-brief
Inter-Agent Communication (v2.0)
Subagents can share knowledge via shared_context.md.
Protocol:
- Subagent discovers a pattern (e.g., "Use
schemas.pyfor all models"). - Subagent writes to "Shared Context Updates" in their report.
- Orchestrator runs
merge_context.pyto updateshared_context.md. - Subsequent subagents read
shared_context.mdin their brief.
Example Report Update:
## Shared Context Updates
- [Error Handling]: Always wrap API calls in `try/except ApiError`.
/swarm-iosm integrate
Collect subagent reports and create integration plan.
What it does:
- Read all reports from
swarm/tracks//reports/ - Identify conflicts and resolution strategy
- Generate integration_report.md with merge order
- Run IOSM quality gates
- Create iosm_report.md with gate results and IOSM-Index
/swarm-iosm revert-plan
Generate rollback guide for a track (does not execute git revert).
What it does:
- Analyze files touched (from reports)
- Identify commits/changes to revert
- Suggest checkpoint/branch strategy
- Create rollback_guide.md with manual steps
Advanced Features (v2.0)
Task Dependencies Visualization (--graph)
Generate a Mermaid diagram of the task dependency graph.
Usage:
/swarm-iosm simulate --graph
Generates dependency_graph.mermaid.
Anti-Pattern Detection
The planner automatically checks for:
- Monolithic tasks (XL + many touches)
- Low parallelism (` (Project-specific)
.claude/skills/swarm-iosm/templates/(Skill defaults)
Supported Templates:
prd.md,plan.md,subagent_brief.md,subagent_report.md
Resource Constraints & Cost Control
Define limits in plan.md or metadata to prevent overload.
Defaults:
- Max Parallel Background: 6
- Max Parallel Foreground: 2
- Max Total: 8
- Cost Limit: $10.00
Model Selection:
- Auto-select: Haiku (read-only), Sonnet (standard), Opus (security/arch).
Instructions for Claude
ORCHESTRATOR RESPONSIBILITIES
CRITICAL: The main agent (Claude) acts as ORCHESTRATOR ONLY. You coordinate subagents but DO NOT do implementation work yourself.
MANDATORY RULES
✅ ORCHESTRATOR DOES:
- Analyze & Plan
- Parse
plan.mdand build dependency graph - Generate
orchestration_plan.mdwith waves/critical path - Detect file conflicts and resolve scheduling
- Launch Subagents
- Create detailed briefs for each subagent (using templates)
- Launch parallel waves in single message (multiple Task tool calls)
- Default to background mode (unless interactive)
- Pre-resolve all questions for background tasks
- Monitor & Handle Blockers
- Use
/bashesto track background tasks - Resume stuck tasks in foreground if needed
- Apply fallback strategy (retry → resume → recovery task)
- Integrate & Gate
- Collect all subagent reports
- Resolve merge conflicts
- Run IOSM quality gates
- Generate
integration_report.mdandiosm_report.md
- Meta-work (ONLY exception to "no implementation")
- Update
plan.mdstatus - Fix metadata (
metadata.json,tracks.md) - Resolve integration conflicts (merge reports)
- Generate final reports/docs
❌ ORCHESTRATOR NEVER DOES:
- Implementation work:
- ❌ Write application code (services, models, API, UI)
- ❌ Write tests (unit, integration, performance)
- ❌ Refactor existing code
- Analysis work:
- ❌ Explore codebase (that's Explorer's job)
- ❌ Design architecture (that's Architect's job)
- ❌ Run security scans (that's SecurityAuditor's job)
- Specialized work:
- ❌ Write documentation (that's DocsWriter's job)
- ❌ Debug performance (that's PerfAnalyzer's job)
Exception: If a task is trivial ( "Работай в режиме continuous scheduling: как только появляется READY задача без конфликтов touches и без needsuserinput — немедленно запускай её в background, даже если другие задачи ещё выполняются. После каждого батча собирай SpawnCandidates из отчётов и автоматически добавляй их в backlog. Продолжай цикл, пока не достигнуты заданные IOSM Gate targets."
Continuous Orchestration Loop
LOOP (до достижения Gate targets):
1. CollectReady()
└─── Собрать задачи, у которых deps выполнены
2. Classify()
└─── Каждой задаче присвоить режим:
- background: safe, no user input needed
- foreground: needs user decision
- blocked_user: needs_user_input=true, не можем авто-решить
- blocked_conflict: touches пересекаются с running
3. ConflictCheck()
└─── Parallel launch ТОЛЬКО tasks без пересечения touches (для write)
└─── Read-only tasks ВСЕГДА можно параллелить
4. DispatchBatch()
└─── Запустить READY tasks ОДНИМ СООБЩЕНИЕМ (max 3-6 per batch)
└─── Приоритет: critical_path > high_severity_spawn > read-only_fillers
└─── Каждый batch получает batch_id для трекинга
└─── Не ждать "конца волны" — dispatch immediately
5. Monitor()
└─── Периодически читать outputs background tasks
└─── Собирать SpawnCandidates из отчётов
6. AutoSpawn()
└─── Если найдены SpawnCandidates → создать новые tasks
└─── Добавить в backlog и вернуться к шагу 1
7. GateCheck()
└─── Проверить условия Gate-I/M/O/S
└─── Если достигнуты → остановиться + gate-report
└─── Если нет → авто-spawn remediation tasks и продолжить
END LOOP
Task States (внутренний трекинг)
| State | Описание | |-------|----------| | backlog | Все известные задачи | | ready | Deps satisfied, можно запускать | | running | Выполняется (background или foreground) | | blocked_user | needsuserinput=true, ждёт решения | | blocked_conflict | touches заняты другой running task | | done | Завершена |
Правило: Если задача стала READY в момент, когда другие выполняются — запускать сразу, не ждать checkpoint.
Touches Lock Manager
Для безопасного параллелизма оркестратор должен отслеживать "занятые" файлы:
touches_lock: Set[path] = {}
При запуске task:
1. Проверить: task.touches ∩ touches_lock == ∅ ?
2. Если да → touches_lock.add(task.touches), запустить
3. Если нет → blocked_conflict, ждать освобождения
При завершении task:
1. touches_lock.remove(task.touches)
2. Пересчитать ready_queue (кто разблокировался?)
Правила конфликтов:
read-onlyзадачи → всегда параллельно (не берут lock)write-local→ параллельно если touches не пересекаютсяwrite-shared→ строго последовательно
Lock Granularity (v1.1.1)
Иерархия конфликтов:
Lock по ПАПКЕ (core/) конфликтует:
├── с любым lock внутри (core/a.py, core/b.py)
└── с lock на саму папку (core/)
Lock по ФАЙЛУ (core/a.py) конфликтует:
├── только с тем же файлом
└── с lock на родительскую папку (core/)
Нормализация путей:
- Всегда использовать
/(forward slash) - Убирать trailing slash (
core/→core) - Приводить к lowercase (для Windows)
- Использовать относительные пути от корня проекта
Пример проверки конфликта:
def conflicts(lock_a: str, lock_b: str) -> bool:
a, b = normalize(lock_a), normalize(lock_b)
return a == b or a.startswith(b + '/') or b.startswith(a + '/')
Read-Only Safety Rules
Проблема: "read-only" задачи могут случайно писать в cache, lockfiles, __pycache__.
Решение: read-only задачи ДОЛЖНЫ:
- НЕ запускать команды, меняющие файлы (
npm install,pip install) - Писать временные артефакты ТОЛЬКО в
swarm/tracks//scratch/ - Использовать флаги
--dry-run,--checkгде возможно
scratch_dir правило:
swarm/tracks//scratch/ ← read-only tasks пишут сюда
├── T00_analysis.json
├── T03_coverage.xml
└── ...
Эта папка НЕ требует lock и НЕ конфликтует ни с кем.
Auto-Background Classification
Оркестратор автоматически классифицирует задачи:
Auto-background (safe, запускать без вопросов):
- Concurrency class =
read-only - Или
write-local+needs_user_input=false+ no policy conflicts - effort >= M и нет choice points
Auto-foreground (нужен пользователь):
- Меняется API контракт/формат ответа
- Нужна "истина" (источники, бизнес-логика, астрология)
- Падают тесты и нужно решить "фиксить код или тест"
- High-risk изменения без тестов
- needsuserinput=true
SpawnCandidates Protocol
Каждый субагент ОБЯЗАН писать в отчёте секцию SpawnCandidates:
## SpawnCandidates
При работе обнаружены новые work items:
| ID | Subtask | Touches | Effort | User Input | Severity | Dedup Key | Accept Criteria |
|----|---------|---------|--------|------------|----------|-----------|-----------------|
| SC-01 | Fix missing type annotation in auth.py | `backend/auth.py` | S | false | medium | auth.py|type-annot | mypy passes |
| SC-02 | Clarify API contract for /natal/aspects | `docs/api_spec.yaml` | M | true | high | api_spec|contract | Contract approved |
Dedup Key формат: |
- Используется для дедупликации одинаковых кандидатов от разных воркеров
Оркестратор обязан:
- После каждого task completion — читать SpawnCandidates
- Дедуплицировать по dedup_key (первый wins)
- Если
needs_user_input=falseиseverity != critical→ auto-spawn - Если
needs_user_input=true→ добавить в blocked_user queue - Прогнать новые tasks через планнер и dispatch
Spawn Protection (v1.1.1)
Защита от бесконечного размножения задач:
(A) Spawn Budget
В iosm_state.md отслеживать:
## Spawn Budget
- spawn_budget_total: 20
- spawn_budget_used: 7
- spawn_budget_remaining: 13
- spawn_budget_per_gate:
- Gate-I: 5 (used: 2)
- Gate-O: 8 (used: 3)
- Gate-M: 4 (used: 2)
- Gate-S: 3 (used: 0)
Правила:
- При исчерпании budget → STOP, спросить пользователя
severity=criticalигнорирует budget (всегда spawn)- User может увеличить budget командой
(B) Dedup Rules
def dedup_key(candidate) -> str:
return f"{candidate.touches[0]}|{candidate.intent_category}"
# Оркестратор хранит:
seen_dedup_keys: Set[str] = set()
# При обработке SpawnCandidate:
if candidate.dedup_key in seen_dedup_keys:
skip # дубль
else:
seen_dedup_keys.add(candidate.dedup_key)
process(candidate)
(C) Severity Threshold
| Severity | Auto-spawn условие | |----------|-------------------| | critical | ВСЕГДА (даже если budget=0), STOP loop и alert | | high | Если gate fail ИЛИ user запросил | | medium | Если gate fail И budget > 0 | | low | Только по явному запросу user |
(D) Anti-Loop Protection
## Anti-Loop Metrics (in iosm_state.md)
- loops_without_progress: 0 # сбрасывается при любом task completion
- max_loops_without_progress: 3
- total_loop_iterations: 15
- max_total_iterations: 50
Правило: Если loops_without_progress >= 3 → STOP, analyze why stuck
Model Selection & Cost (v1.2)
Model Selection Rules:
haiku: read-only tasks ($0.25/M tokens)sonnet: standard tasks, background automation ($3.00/M tokens)opus: security audits, critical architecture, user decisions ($15.00/M tokens)
Cost Tracking: Orchestrator tracks cost in iosm_state.md:
- Estimate:
…
Source & license
This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.
- Author: rokoss21
- Source: rokoss21/swarm-iosm
- License: MIT
- Homepage: https://github.com/rokoss21/IOSM
Install and usage instructions live in the source repository linked above.
Reviews
No reviews yet — be the first.
Write a review
Versions
- v0.1.0 Imported from the upstream source.