Make agent-swarm domain-neutral and adaptive

This commit is contained in:
Emil Shanaty
2026-10-27 19:27:11 +03:00
parent 464b610bf1
commit 20497d9c0c
11 changed files with 191 additions and 58 deletions
+6 -4
View File
@@ -4,14 +4,16 @@
## agent-swarm ## agent-swarm
Большие задачи, которые делятся на 8+ независимых кусков: миграции, аудиты, research, Универсальные большие задачи, которые делятся на 8+ независимых кусков: код и миграции,
многосекционные документы. Лид планирует и интегрирует, воркеры работают по пакетам с аудиты, research, многосекционные документы, данные, дизайн, инфраструктура. Лид планирует
непересекающимися файлами, независимые верификаторы проверяют артефакт, а не отчёт воркера. и интегрирует, воркеры работают по пакетам с непересекающимися файлами/артефактами, а
независимые верификаторы проверяют артефакт, а не отчёт воркера.
- [Описание на русском](agent-swarm/README.ru.md) - [Описание на русском](agent-swarm/README.ru.md)
- [Инструкции скилла](agent-swarm/SKILL.md) - [Инструкции скилла](agent-swarm/SKILL.md)
- [Runbook](agent-swarm/references/playbook.md) - [Runbook](agent-swarm/references/playbook.md)
- [Cookbook по `workflow`](agent-swarm/references/orchestration.md) - [Cookbook по `workflow`](agent-swarm/references/orchestration.md)
- [Domain-адаптеры](agent-swarm/references/domains.md)
- [Изолированное визуальное тестирование](agent-swarm/references/visual-testing.md) - [Изолированное визуальное тестирование](agent-swarm/references/visual-testing.md)
### Установка ### Установка
@@ -30,7 +32,7 @@ cp -r skills/agent-swarm ~/.dsh/skills/
agent-swarm/ agent-swarm/
├── SKILL.md # основной протокол ├── SKILL.md # основной протокол
├── README.ru.md # краткое описание ├── README.ru.md # краткое описание
├── references/ # playbook, packets, orchestration ├── references/ # playbook, packets, orchestration, domains, visual testing
├── assets/ # шаблоны, схемы, workflow-скрипты ├── assets/ # шаблоны, схемы, workflow-скрипты
└── scripts/audit-scope.mjs # проверка ownership └── scripts/audit-scope.mjs # проверка ownership
``` ```
+6 -3
View File
@@ -1,6 +1,6 @@
# agent-swarm # agent-swarm
Скилл для больших задач, которые делятся на 8+ независимых кусков: миграции, аудиты, research, документы. Лид (главный агент) планирует, пакует контекст, запускает волны через `workflow`, проверяет и интегрирует. Воркеры не пересекаются по файлам, каждый получает свой пакет и возвращает структурный отчёт. Универсальный скилл для больших задач, которые делятся на 8+ независимых кусков: код и миграции, аудиты, research, документы, данные, дизайн, инфраструктура. Лид планирует, пакует контекст, запускает волны (через `workflow`, `subagent` или последовательно — если инструмента нет) и интегрирует. Воркеры не пересекаются по файлам/артефактам, каждый получает пакет и возвращает структурный отчёт.
## Вызов ## Вызов
@@ -10,10 +10,12 @@
или просто опишите задачу — скилл подключится по описанию. или просто опишите задачу — скилл подключится по описанию.
Скилл не обязателен для каждой задачи: маленькую задачу можно делать напрямую, среднюю — с независимым критиком, и только широкую — через swarm. Пользователь выбирает стек, объём и темп; скилл добавляет координацию, когда она оправдана.
## Что происходит ## Что происходит
1. **Fit-check.** Если задача не делится на 8+ независимых юнитов, скилл скажет не использовать swarm. 1. **Fit-check.** Если задача не делится на 8+ независимых юнитов, скилл скажет не использовать swarm.
2. **Recon.** 2–4 агента картографируют репозиторий; лид пишет `.swarm/brief.md`. 2. **Recon.** 2–4 агента картографируют репозиторий/источники/данные; лид пишет `.swarm/brief.md`, `.swarm/profile.md` и выбирает domain-адаптер из `references/domains.md`.
3. **План.** Задачи, владельцы файлов, контракты, критерии приёмки. Гейт: без этого волны не стартуют. 3. **План.** Задачи, владельцы файлов, контракты, критерии приёмки. Гейт: без этого волны не стартуют.
4. **Волны.** Воркеры идут батчами по 6–8 (реальный лимит активных детей узнаётся перед запуском и записывается в `state.json`; recon не должен занимать слоты). Затем 4–6 независимых верификаторов на «замороженном» дереве, затем интегратор. 4. **Волны.** Воркеры идут батчами по 6–8 (реальный лимит активных детей узнаётся перед запуском и записывается в `state.json`; recon не должен занимать слоты). Затем 4–6 независимых верификаторов на «замороженном» дереве, затем интегратор.
5. **Аудит.** `scripts/audit-scope.mjs` сравнивает изменения с картой владения. 5. **Аудит.** `scripts/audit-scope.mjs` сравнивает изменения с картой владения.
@@ -21,7 +23,7 @@
## Артефакты ## Артефакты
Всё лежит в `.swarm/` в корне рабочей папки: бриф, план, карточки задач, отчёты, ревью, baseline, финальный отчёт. `.swarm/` можно удалить после задачи или добавить в `.gitignore`. Всё лежит в `.swarm/` в корне рабочей папки: бриф, профиль домена, план, карточки задач, отчёты, ревью, baseline, финальный отчёт. `.swarm/` можно удалить после задачи или добавить в `.gitignore`; структура подходит и для кода, и для research/контента/данных/дизайна.
## Ограничения ## Ограничения
@@ -30,6 +32,7 @@
- Дети не общаются между собой и не делегируют дальше; координация — через файлы и лида. - Дети не общаются между собой и не делегируют дальше; координация — через файлы и лида.
- Верификаторы работают на замороженном дереве; полный разбор пишется в `.swarm/reviews/Vxx.md`, а workflow возвращает только `{task_id, verdict, summary, review_file}`. - Верификаторы работают на замороженном дереве; полный разбор пишется в `.swarm/reviews/Vxx.md`, а workflow возвращает только `{task_id, verdict, summary, review_file}`.
- `blocked`-воркер не заменяется: лид правит контракт/shared-файл и продолжает того же агента через `send_message`. - `blocked`-воркер не заменяется: лид правит контракт/shared-файл и продолжает того же агента через `send_message`.
- Evidence зависит от домена: команда и тест для кода, источник и дата для research, отрендеренный артефакт для дизайна, reproducible metric для данных.
- Визуальные агенты работают в отдельных Xvfb/display-окружениях, со своим HOME/config/копией проекта; общий рабочий стол для скриншотов не используется. Детали — в `references/visual-testing.md`. - Визуальные агенты работают в отдельных Xvfb/display-окружениях, со своим HOME/config/копией проекта; общий рабочий стол для скриншотов не используется. Детали — в `references/visual-testing.md`.
- Стоимость: 30–40 агентов ≈ 0.5–1.5M токенов. - Стоимость: 30–40 агентов ≈ 0.5–1.5M токенов.
- Для задачи, которую один агент делает за 15 минут, swarm не нужен. - Для задачи, которую один агент делает за 15 минут, swarm не нужен.
+24 -10
View File
@@ -1,6 +1,6 @@
--- ---
name: agent-swarm name: agent-swarm
description: Use for large tasks that split into 8+ independent work units (codebase-wide changes, audits, migrations, multi-source research, multi-section documents) to run dozens of coordinated subagents in waves under one lead, with file ownership, packed context, and independent verification. Not for single-file, sequential, or highly coupled work. description: Use for large tasks that split into 8+ independent work units across software, research, content, data, design or operations (codebase-wide changes, audits, migrations, multi-source research, multi-section documents, dataset work, visual redesigns) to run coordinated subagents in waves under one lead, with ownership, packed context, and independent verification. Not for single-file, sequential, or highly coupled work.
whenToUse: The task is broad, parallelizable, and has executable acceptance checks; one agent would take hours and separate agents can finish units without touching the same files. whenToUse: The task is broad, parallelizable, and has executable acceptance checks; one agent would take hours and separate agents can finish units without touching the same files.
--- ---
@@ -8,11 +8,23 @@ whenToUse: The task is broad, parallelizable, and has executable acceptance chec
Run a large task as waves of coordinated subagents. The lead plans and integrates; workers execute one work packet each; verifiers check independently. A swarm is only as fast as its briefs are clear and its write scopes are disjoint. Run a large task as waves of coordinated subagents. The lead plans and integrates; workers execute one work packet each; verifiers check independently. A swarm is only as fast as its briefs are clear and its write scopes are disjoint.
The protocol is **domain-neutral**: software, research, content, data, design and operations all use the same roles and evidence rules. Pick an adapter from `references/domains.md`; do not force a software pipeline onto non-code work. Tools are optional too: if `workflow` is unavailable, use `subagent` or direct sequential work with the same packets.
The skill is a **capability, not a mandatory process**. Apply the lightest mode that meets the risk:
| Mode | When | What it adds |
|---|---|---|
| Direct | one unit, fast feedback, low blast radius | none |
| Paired critic | medium task or risky design decision | independent review, same artifact |
| Swarm | 8+ independent units, breadth dominates | plan, ownership, parallel workers, verifier wave |
Do not force task cards, waves or `.swarm/` artifacts onto a small request. Conversely, do not skip independent verification on a large or risky one. The user keeps the choice of stack, scope and pace; the skill only adds coordination when breadth or risk justifies it.
## Fit check — before spawning anything ## Fit check — before spawning anything
Swarm only when all are true: Swarm only when all are true:
- The task splits into **8+ independent units** with disjoint write scopes. - The task splits into **8+ independent units** with disjoint write scopes.
- Each unit has an **executable acceptance check** (command, test, or verifiable criterion). - Each unit has a **re-runnable acceptance check**: a command, a named artifact, a source/citation check, a metric, or a rendered result. There is no universal evidence type; match it to the domain adapter.
- Wall-clock is dominated by **breadth**, not by one deep sequential chain. - Wall-clock is dominated by **breadth**, not by one deep sequential chain.
- You can state the interfaces between units **before** dispatch. - You can state the interfaces between units **before** dispatch.
@@ -28,22 +40,22 @@ Otherwise: one agent for small work; 2–5 `subagent` calls for a few long-lived
## Protocol ## Protocol
0. **Fit check & preflight** — go/no-go, budget (`max_agents`, `max_waves`), and **discover the real active-child cap** before sizing a wave (see Sizing). Record the cap, current active children, and planned batch size in `state.json`. 0. **Fit check & preflight** — go/no-go, budget (`max_agents`, `max_waves`), and **discover the available tools and real active-child cap** before sizing a wave. Record in `state.json`: tool availability (`workflow`, `subagent`, display/artifact command, build commands), slot cap, active children, planned batch size, and the chosen domain adapter.
1. **Recon** — 2–4 parallel agents return findings with paths and line numbers. Timebox them, merge into `.swarm/brief.md` and `.swarm/map.md`, then stop them; recon must not hold slots during the build wave. 1. **Recon** — 2–4 parallel agents return findings with paths and line numbers. Timebox them, merge into `.swarm/brief.md` and `.swarm/map.md`, then stop them; recon must not hold slots during the build wave.
2. **Plan gate** — write `.swarm/plan.json`, `plan.md`, `ownership.md`, `contracts.md`, and one `tasks/Txx.md` per unit. Every success criterion maps to a task and a check. No two tasks write the same path. Include a `LEAD`/`INTEGRATOR` task owning lead-owned shared files, screenshots, licenses and the final report. Freeze interfaces. **Do not dispatch until this gate passes.** 2. **Plan gate** — write `.swarm/plan.json`, `plan.md`, `ownership.md`, `contracts.md`, and one `tasks/Txx.md` per unit. Every success criterion maps to a task and a check. No two tasks write the same path. Include a `LEAD`/`INTEGRATOR` task owning lead-owned shared files, screenshots, licenses and the final report. Freeze interfaces. **Do not dispatch until this gate passes.**
3. **Build wave** — one `workflow` call per build wave, using the batched runner in `assets/wave.workflow.js`; its `concurrency` must fit the available slots (see Sizing). Retry `null`/`failed` once; if the runtime reports an active-child limit, halve the next batch and dispatch the remaining tasks — never relaunch the same oversubscribed fan-out. 3. **Build wave** — one `workflow` call per build wave when the tool exists, using the batched runner in `assets/wave.workflow.js`; its `concurrency` must fit the available slots (see Sizing). If `workflow`/`subagent` is unavailable, the lead executes the same packets sequentially. Retry `null`/`failed` once; if the runtime reports an active-child limit, halve the next batch and dispatch the remaining tasks — never relaunch the same oversubscribed fan-out.
4. **Audit** — run `scripts/audit-scope.mjs` from the skill base directory; revert or reassign out-of-scope changes. Run the build/test gate. 4. **Audit** — run `scripts/audit-scope.mjs` from the skill base directory; revert or reassign out-of-scope changes. Run the build/test gate.
5. **Verify wave** — **freeze source changes**, then run 4–6 fresh verifiers by risk cluster. Use `assets/verdict.schema.json` and `assets/verify.workflow.js`; the review file on disk is the source of truth, not the workflow return. Verifiers never fix. For GUI products, verify in **per-agent isolated displays**, never a shared desktop (see `references/visual-testing.md`). If you fix findings, re-run the affected verifier and mark the old review stale. 5. **Verify wave** — **freeze source changes**, then run 4–6 fresh verifiers by risk cluster (or 1–2 for a small domain task). Use `assets/verdict.schema.json` and, when available, `assets/verify.workflow.js`; the review file on disk is the source of truth, not the workflow return. Verifiers never fix. Match evidence to the domain adapter: rerun commands, read rendered artifacts, sample citations, recompute metrics. For GUI products, use per-agent isolated displays, never a shared desktop (see `references/visual-testing.md`). If you fix findings, re-run the affected verifier and mark the old review stale.
6. **Integrate** — one integrator for shared files and cross-cutting fixes; re-run the full acceptance suite; then a final verification pass on the integrated build. 6. **Integrate** — one integrator for shared files and cross-cutting fixes; re-run the full acceptance suite; then a final verification pass on the integrated build.
7. **Close** — freeze the build and run a final independent review against the original request (not the plan), then write `final-report.md`. 7. **Close** — freeze the build and run a final independent review against the original request (not the plan), then write `final-report.md`.
## Hard rules ## Hard rules
1. **One writer per path.** A path appears in at most one task's `write` list. Shared files (`package.json`, lockfiles, barrels, schemas, migrations, CI) belong to the integrator only. 1. **One writer per path.** A path appears in at most one task's `write` list. Shared files (`package.json`, lockfiles, barrels, schemas, migrations, CI) belong to the integrator only.
2. **Packet, not transcript.** Each worker reads `.swarm/brief.md`, its `tasks/Txx.md`, and `.swarm/contracts.md`. Never fork the lead's conversation for dozens of workers. 2. **Packet, not transcript.** Each worker reads `.swarm/brief.md`, its `tasks/Txx.md`, `.swarm/contracts.md`, and the domain adapter in `.swarm/profile.md` (if any). Never fork the lead's conversation for dozens of workers.
3. **Structured reports.** Workers return `{task_id, status, summary, files_changed, evidence, acceptance, issues, assumptions}` and write the same object to `.swarm/reports/Txx.json`. Verifiers write the full review to `.swarm/reviews/Vxx.md` and return the minimal `{task_id, verdict, summary, review_file}`. Prose is not a report. 3. **Structured reports.** Workers return `{task_id, status, summary, files_changed, evidence, acceptance, issues, assumptions}` and write the same object to `.swarm/reports/Txx.json`. Verifiers write the full review to `.swarm/reviews/Vxx.md` and return the minimal `{task_id, verdict, summary, review_file}`. Prose is not a report.
4. **No self-verification.** The worker's own checks are a smoke test; a different agent verifies the artifact. 4. **No self-verification.** The worker's own checks are a smoke test; a different agent verifies the artifact.
5. **No global side effects.** Workers do not run installs, repo-wide format/lint/codegen, migrations, dev servers, or any git write command. They do not edit other tasks' files or reports. The lead owns git and commits only after the final review. 5. **No global side effects.** Workers do not run installs, repo-wide format/lint/codegen, migrations, dev servers, deployments, external publishes, or any git write command without explicit scope. They do not edit other tasks' files/reports or touch live systems. The lead owns irreversible operations and only after the final review.
6. **Respect the runtime slot cap.** Active children include recon, verifiers, integrators and any other subagents. A spawn-limit error is a scheduling bug, not a worker failure: shrink the batch, keep completed results, and dispatch the remainder. 6. **Respect the runtime slot cap.** Active children include recon, verifiers, integrators and any other subagents. A spawn-limit error is a scheduling bug, not a worker failure: shrink the batch, keep completed results, and dispatch the remainder.
7. **Freeze during verification.** Once the verify wave starts, do not edit source/tests/docs except to fix a verified finding. After a fix, re-run the affected verifier; an old review is stale. 7. **Freeze during verification.** Once the verify wave starts, do not edit source/tests/docs except to fix a verified finding. After a fix, re-run the affected verifier; an old review is stale.
8. **Stop rules.** Two waves with no net progress → stop and re-plan. Verification failure rate > 30% → fix briefs/contracts, not agent count. Budget exhausted → report partial and list unverified areas. 8. **Stop rules.** Two waves with no net progress → stop and re-plan. Verification failure rate > 30% → fix briefs/contracts, not agent count. Budget exhausted → report partial and list unverified areas.
@@ -65,9 +77,10 @@ Otherwise: one agent for small work; 2–5 `subagent` calls for a few long-lived
``` ```
.swarm/ .swarm/
brief.md shared context: goal, stack, commands, conventions, hazards brief.md shared context: goal, domain, commands, conventions, hazards
map.md repository map from recon: paths, entry points, hazards map.md repository/source map from recon: paths, entry points, hazards
contracts.md frozen interfaces between tasks contracts.md frozen interfaces between tasks
profile.md domain adapter: artifacts, commands, evidence types (optional)
plan.json tasks, deps, write scopes, waves, status plan.json tasks, deps, write scopes, waves, status
plan.md human-readable plan + coverage matrix plan.md human-readable plan + coverage matrix
ownership.md path -> task map ownership.md path -> task map
@@ -93,7 +106,8 @@ For a `blocked` task: apply the smallest contract/shared-file change, update `co
- `references/playbook.md` — phase-by-phase runbook, gates, checklists, failure recovery. - `references/playbook.md` — phase-by-phase runbook, gates, checklists, failure recovery.
- `references/packets.md` — how to write briefs, task cards, and verifier cards; examples and common mistakes. - `references/packets.md` — how to write briefs, task cards, and verifier cards; examples and common mistakes.
- `references/orchestration.md` — `workflow` cookbook: script patterns, schema subset, retries, background runs, archetypes (code / research / content). - `references/orchestration.md` — `workflow` cookbook: script patterns, schema subset, retries, background runs, archetypes (code / research / content).
- `references/visual-testing.md` — isolated Xvfb/container visual tests, deterministic screenshots, verifier procedure. - `references/domains.md` — adapters for software, research, content, data, design and operations.
- `references/visual-testing.md` — isolated Xvfb/container visual tests, deterministic screenshots, verifier procedure (GUI adapter).
- `assets/` — copyable brief, task, and verifier templates; `report.schema.json`, `verdict.schema.json`; `wave.workflow.js` (batched workers), `verify.workflow.js` (frozen verification). - `assets/` — copyable brief, task, and verifier templates; `report.schema.json`, `verdict.schema.json`; `wave.workflow.js` (batched workers), `verify.workflow.js` (frozen verification).
- `scripts/audit-scope.mjs` — compares changed files to the ownership map. - `scripts/audit-scope.mjs` — compares changed files to the ownership map.
+19 -11
View File
@@ -4,26 +4,34 @@
{{One paragraph. What must exist when the swarm is done.}} {{One paragraph. What must exist when the swarm is done.}}
## Success criteria ## Success criteria
- [ ] {{Criterion}} — verified by {{check or command}} - [ ] {{Criterion}} — verified by {{check, command, artifact or citation}}
- [ ] {{Criterion}} — verified by {{check or command}} - [ ] {{Criterion}} — verified by {{check, command, artifact or citation}}
Scope is checked by the lead with the skill's `scripts/audit-scope.mjs`; workers do not run it. Scope is checked by the lead with the skill's `scripts/audit-scope.mjs`; workers do not run it.
## Non-goals ## Non-goals
- {{What must not change or be attempted.}} - {{What must not change or be attempted.}}
## Stack and commands ## Domain profile
- Domain: {{software / research / content / data / design / operations}}
- Primary artifacts: {{paths, sections, datasets, renders, services}}
- Evidence type: {{command / artifact / citation / metric / render}}
- Evidence commands or sources: {{commands, URLs, access notes}}
- Approval boundaries: {{what needs human confirmation}}
## Stack and commands (when applicable)
| Action | Command | | Action | Command |
|---|---| |---|---|
| build | `{{command}}` | | build | `{{command or n/a}}` |
| test | `{{command}}` | | test | `{{command or n/a}}` |
| lint | `{{command}}` | | lint | `{{command or n/a}}` |
| run | `{{command}}` | | run | `{{command or n/a}}` |
| evidence | `{{screenshot/citation/metric command}}` |
## Repository map ## Artifact / source map
| Path | Role | | Path, source or artifact | Role |
|---|---| |---|---|
| `{{path}}` | {{one line}} | | `{{path/url/artifact}}` | {{one line}} |
## Conventions and invariants ## Conventions and invariants
- {{Naming, error handling, test style, formatting.}} - {{Naming, error handling, test style, formatting.}}
@@ -37,7 +45,7 @@ Scope is checked by the lead with the skill's `scripts/audit-scope.mjs`; workers
See `.swarm/contracts.md`. Do not change an interface without returning `blocked`. See `.swarm/contracts.md`. Do not change an interface without returning `blocked`.
## Global forbidden actions ## Global forbidden actions
- No installs, repo-wide format/lint/codegen, migrations, dev servers, or git writes. - No installs, repo-wide format/lint/codegen, migrations, deployments, external publishes, dev servers, or git writes without explicit scope.
- No edits outside your task's write scope. - No edits outside your task's write scope.
- Do not edit `.swarm/brief.md`, `plan.*`, `contracts.md`, or another task's files or reports. - Do not edit `.swarm/brief.md`, `plan.*`, `contracts.md`, or another task's files or reports.
+7 -6
View File
@@ -11,11 +11,11 @@ Role: worker | Wave: {{n}} | Depends on: {{ids or —}} | Effort: {{S/M/L}}
## Inputs (read first) ## Inputs (read first)
- `.swarm/brief.md` - `.swarm/brief.md`
- `.swarm/contracts.md` §{{section}} - `.swarm/contracts.md` §{{section}}
- `{{path}}:{{start}}-{{end}}` - `{{artifact/source}}`: {{path:start-end, URL, dataset, design file}}
## Deliverables ## Deliverables
- `{{new or changed path}}` — {{what}} - `{{new or changed path/artifact}}` — {{what}}
- `{{test path}}` — {{what it covers}} - `{{test/evidence artifact}}` — {{what it proves}}
## Write scope (only these) ## Write scope (only these)
- `{{glob or exact path}}` - `{{glob or exact path}}`
@@ -29,9 +29,10 @@ Role: worker | Wave: {{n}} | Depends on: {{ids or —}} | Effort: {{S/M/L}}
## Constraints ## Constraints
- {{No new dependencies, style, performance, compatibility.}} - {{No new dependencies, style, performance, compatibility.}}
## Acceptance (run these) ## Acceptance (re-runnable)
1. `{{command}}` → {{expected result}} 1. `{{command or artifact path}}` → {{expected result/state}}
2. `{{command}}` → {{expected result}} 2. `{{citation check / metric / render at sizes}}` → {{expected result}}
3. Every criterion must have evidence a fresh verifier can reproduce.
## Report ## Report
`.swarm/reports/{{ID}}.json` per `.swarm/report.schema.json`; status `done|partial|blocked|failed`. `.swarm/reports/{{ID}}.json` per `.swarm/report.schema.json`; status `done|partial|blocked|failed`.
+8 -4
View File
@@ -4,13 +4,17 @@ You did not write this work. Do not fix it. Do not trust worker summaries.
## Inputs ## Inputs
- Task cards: {{paths}} - Task cards: {{paths}}
- Changed files or diff: {{paths or command}} - Changed files/artifacts or diff: {{paths or command}}
- Acceptance checks: {{commands}} - Acceptance checks: {{commands, artifact paths, citations, metrics}}
## For each criterion ## For each criterion
| Criterion | Command | Observed | Pass/Fail | | Criterion | Evidence (command/artifact/citation/metric) | Observed | Pass/Fail |
|---|---|---|---| |---|---|---|---|
| {{criterion}} | `{{command}}` | {{observed}} | {{pass/fail}} | | {{criterion}} | {{command, path, URL or check}} | {{observed}} | {{pass/fail}} |
For research/content, cite the exact source and date. For data, record input hash, row count and
metric. For design, record the rendered artifact and sizes. For software, record the command and
output. Evidence must be reproducible by a fresh verifier.
## Also check ## Also check
- Scope: every changed file is owned by the task. - Scope: every changed file is owned by the task.
+69
View File
@@ -0,0 +1,69 @@
# Domain adapters
The swarm protocol is domain-neutral. A domain adapter says what "work", "ownership", "evidence"
and "done" mean for this kind of task. Pick one, combine several, or write a project-specific
adapter in `.swarm/profile.md`. Do not treat these as mandatory pipelines.
## Software / code
- Units: module, feature, crate, service, migration, test cluster.
- Ownership: source + test paths; shared manifests/lockfiles/barrels/schemas are integrator-only.
- Acceptance: build/test/lint commands, typecheck, generated-code compile, runtime smoke.
- Verifier: reruns commands, reads the diff, checks edge cases and API compatibility; no self-review.
- Evidence: command + observed result, test names, compiler output, benchmark numbers.
## Research / analysis
- Units: one question, source cluster, claim set, or section.
- Ownership: one notes/report file per unit; no shared notes file.
- Acceptance: every factual claim has a source URL; dates are explicit; counter-evidence is considered.
- Verifier: samples claims against sources, checks citation resolvability and recency, looks for
unsupported synthesis.
- Evidence: source URL, quote/paraphrase, access date, confidence, open questions.
## Content / documents / translation
- Units: one section, chapter, page, or locale.
- Ownership: separate section files; the editor/integrator owns the assembled document and style.
- Acceptance: section brief, word/character budget, terminology/glossary, citations, style guide,
rendered artifact (PDF/HTML/DOCX) where applicable.
- Verifier: reads the rendered artifact, checks structure/voice/term consistency, samples facts.
- Evidence: rendered path, word count, diff, terminology check, citation check.
## Data / analytics
- Units: one dataset, metric, query, notebook, or chart.
- Ownership: input data read-only; one output table/notebook/report per unit; shared schemas need an
integrator.
- Acceptance: reproducible script with pinned inputs; output schema; row counts; metric definitions;
checksums or input hashes.
- Verifier: reruns the pipeline on a sample or full dataset; recomputes key numbers; checks nulls,
duplicates, units and time zones.
- Evidence: command, input hash, output rows, metric values, notebook/report path.
## Design / UX / visual
- Units: screen, component, flow, illustration, design token set.
- Ownership: one source/design file per unit; shared tokens/components/integrator.
- Acceptance: rendered artifact at required sizes/states; accessibility (contrast, focus, keyboard,
labels); interaction states; visual regression.
- Verifier: renders the artifact in an isolated display; checks default/minimum/empty/error states;
never accepts a shared-desktop screenshot.
- Evidence: screenshot path, dimensions, command, contrast/focus notes.
- See `visual-testing.md` for isolation and deterministic capture; it is optional for non-visual work.
## Operations / infrastructure
- Units: one service, deployment, migration, runbook, or config change.
- Ownership: infra files and runbooks; live environments are not "write scopes".
- Acceptance: dry-run/plan output, diff, rollback procedure, monitoring/health check, no production
writes without explicit human approval.
- Verifier: reviews the plan/diff, runs read-only checks, confirms rollback and blast radius.
- Evidence: dry-run output, diff, health check, rollback command, approval record.
## How to adapt without inventing a pipeline
1. Write `.swarm/profile.md` with: domain, artifacts, commands, evidence types, approval boundaries.
2. In `.swarm/brief.md`, replace command-only success criteria with "evidence type + check".
3. In each task card, name the artifact and the verifier action, not the steps.
4. In verification, use the matching adapter above; independent evidence is the invariant.
+26
View File
@@ -144,6 +144,20 @@ The verifier writes the review file first and returns only `{task_id, verdict, s
Use `run_in_background: true` when a wave may exceed ~10 minutes or you want live progress in the job list. The call returns a job id; `job_output` with `wait: true` blocks until settlement. If a wave hangs, `job_kill` cancels the run and disposes children. A background run's result arrives once, at settlement. Use `run_in_background: true` when a wave may exceed ~10 minutes or you want live progress in the job list. The call returns a job id; `job_output` with `wait: true` blocks until settlement. If a wave hangs, `job_kill` cancels the run and disposes children. A background run's result arrives once, at settlement.
## Tool availability
The protocol does not require the `workflow` tool. At preflight check what exists:
- `workflow` + sufficient slots → batched runner (`wave.workflow.js`).
- `subagent` only → lead dispatches 2–5 long-lived packets directly, or runs sequentially with
structured reports.
- Neither → the lead executes the packets itself and still uses independent review/evidence; the
skill becomes a planning/verification checklist, not a parallel runtime.
The same brief, task cards, ownership map and report schema apply in all three modes. Do not
fabricate a workflow if the tool is unavailable, and do not force a full swarm for a task that a
single agent can finish.
## Archetypes ## Archetypes
### Code ### Code
@@ -152,6 +166,18 @@ Use `run_in_background: true` when a wave may exceed ~10 minutes or you want liv
- Acceptance: targeted test command, typecheck, lint on changed files. - Acceptance: targeted test command, typecheck, lint on changed files.
- Verify: a fresh agent runs the tests and reads the diff; no self-review. - Verify: a fresh agent runs the tests and reads the diff; no self-review.
### Data / analysis
- Units: dataset, metric, query, notebook or chart per agent.
- Ownership: inputs read-only; one output table/report per unit.
- Acceptance: reproducible script, input hash, row counts, metric definitions.
- Verify: rerun on a sample or full data; recompute key numbers.
### Design / UX
- Units: screen/component/flow/token set per agent.
- Ownership: source design files; shared tokens are integrator-only.
- Acceptance: rendered artifact at required sizes/states, accessibility checks.
- Verify: isolated display, screenshot path, keyboard/focus/contrast notes.
### Research ### Research
- Units: one question or one source cluster per agent; output files under `research/`. - Units: one question or one source cluster per agent; output files under `research/`.
- Ownership: one file per agent; no shared notes file. - Ownership: one file per agent; no shared notes file.
+9 -9
View File
@@ -4,7 +4,7 @@ A packet is everything one agent needs and nothing else. The lead writes packets
## The context ladder ## The context ladder
1. `.swarm/brief.md` — shared by all tasks: goal, success criteria, stack, commands, conventions, hazards, forbidden actions. 1. `.swarm/brief.md` — shared by all tasks: goal, success criteria, domain/evidence, commands or sources, conventions, hazards, forbidden actions.
2. `.swarm/tasks/Txx.md` — one task: objective, inputs, deliverables, write scope, contract, acceptance, stop conditions. 2. `.swarm/tasks/Txx.md` — one task: objective, inputs, deliverables, write scope, contract, acceptance, stop conditions.
3. `.swarm/contracts.md` — frozen interfaces; read the relevant section only. 3. `.swarm/contracts.md` — frozen interfaces; read the relevant section only.
4. Pointers — `path:line` ranges, not pasted code. 4. Pointers — `path:line` ranges, not pasted code.
@@ -16,7 +16,7 @@ If a worker needs the lead's conversation, the packet is incomplete. If a packet
Copy `assets/brief.md.tmpl`. Rules: Copy `assets/brief.md.tmpl`. Rules:
- Goal is one paragraph; success criteria are checkable. - Goal is one paragraph; success criteria are checkable.
- List the exact build/test/lint commands. Workers should not guess. - List the exact commands or evidence sources for the domain. Workers should not guess.
- Map only the paths a worker may need; link the rest. - Map only the paths a worker may need; link the rest.
- Hazards: generated files, migrations, flaky tests, shared ports, secrets. Name what not to touch. - Hazards: generated files, migrations, flaky tests, shared ports, secrets. Name what not to touch.
- Global forbidden actions are identical in every packet; keep them in the brief to save prompt space. - Global forbidden actions are identical in every packet; keep them in the brief to save prompt space.
@@ -26,11 +26,11 @@ Copy `assets/brief.md.tmpl`. Rules:
Copy `assets/task.md.tmpl`. Rules: Copy `assets/task.md.tmpl`. Rules:
- Objective: what must exist when done, in 1–3 sentences. - Objective: what must exist when done, in 1–3 sentences.
- Inputs: brief, contract section, and exact code ranges. - Inputs: brief, contract section, and exact file/source ranges.
- Deliverables: paths, including tests. - Deliverables: paths, including tests.
- Write scope: globs. Everything else is read-only. - Write scope: globs. Everything else is read-only.
- Contract: exact signature or output shape. If it is not written, it is not frozen. - Contract: exact signature or output shape. If it is not written, it is not frozen.
- Acceptance: 1–3 commands a verifier can re-run. "Code is clean" is not a check. - Acceptance: 1–3 checks a verifier can re-run independently: commands, artifacts, citations, metrics or renders. "Works well" is not a check.
- GUI: acceptance includes a deterministic screenshot command, fixed window sizes and an isolated display; see `references/visual-testing.md`. - GUI: acceptance includes a deterministic screenshot command, fixed window sizes and an isolated display; see `references/visual-testing.md`.
- Stop conditions: time/attempt limit (25 min for S/M, 45–60 for L) plus "ask, do not guess" for load-bearing unknowns. - Stop conditions: time/attempt limit (25 min for S/M, 45–60 for L) plus "ask, do not guess" for load-bearing unknowns.
- Never include another task's internal details; workers do not need the whole plan. - Never include another task's internal details; workers do not need the whole plan.
@@ -40,8 +40,8 @@ Copy `assets/task.md.tmpl`. Rules:
Copy `assets/verifier.md.tmpl`. Rules: Copy `assets/verifier.md.tmpl`. Rules:
- State plainly: you did not write this; do not fix it. - State plainly: you did not write this; do not fix it.
- State that the tree is frozen: no source/test/docs/manifest edits during verification. - State that the tree is frozen: no source/test/docs/manifest edits during verification.
- Give criteria, changed paths, and commands; withhold the worker's rationale. - Give criteria, changed paths/artifacts, and evidence checks; withhold the worker's rationale.
- Require a table: criterion, command, observed, pass/fail. - Require a table: criterion, evidence, observed, pass/fail.
- Ask for scope, contract, and test-quality checks. - Ask for scope, contract, and test-quality checks.
- Require the full review file **first**, then a minimal `{task_id, verdict, summary, review_file}` return (`assets/verdict.schema.json`). The review file is the source of truth; a schema miss must not erase the verification work. - Require the full review file **first**, then a minimal `{task_id, verdict, summary, review_file}` return (`assets/verdict.schema.json`). The review file is the source of truth; a schema miss must not erase the verification work.
- GUI: require an isolated Xvfb/display, screenshots at default and minimum sizes, and the exact commands used; shared-desktop screenshots are not evidence. - GUI: require an isolated Xvfb/display, screenshots at default and minimum sizes, and the exact commands used; shared-desktop screenshots are not evidence.
@@ -51,8 +51,8 @@ Copy `assets/verifier.md.tmpl`. Rules:
Copy `assets/report.schema.json` to `.swarm/report.schema.json` and `assets/verdict.schema.json` to `.swarm/verdict.schema.json` during bootstrap; workers/verifiers read those copies. Field discipline: Copy `assets/report.schema.json` to `.swarm/report.schema.json` and `assets/verdict.schema.json` to `.swarm/verdict.schema.json` during bootstrap; workers/verifiers read those copies. Field discipline:
- `status`: `done` (acceptance met), `partial` (some criteria met, listed), `blocked` (needs a lead decision), `failed` (attempted, cannot proceed). - `status`: `done` (acceptance met), `partial` (some criteria met, listed), `blocked` (needs a lead decision), `failed` (attempted, cannot proceed).
- `verdict` (verifiers only): `pass`, `pass_with_risks`, or `fail`; the detailed findings belong in the review file, not a required workflow array. - `verdict` (verifiers only): `pass`, `pass_with_risks`, or `fail`; the detailed findings belong in the review file, not a required workflow array.
- `files_changed`: exact deliverable/code paths, no globs. Coordination artifacts under `.swarm/` are implicit and may be omitted. - `files_changed`: exact deliverable paths/artifacts, no globs. Coordination artifacts under `.swarm/` are implicit and may be omitted.
- `evidence`: commands and observed results, one line each. - `evidence`: commands, artifact paths, citations, metrics or renders with observed results, one line each.
- `acceptance`: per check, `pass|fail|not_run` plus evidence. - `acceptance`: per check, `pass|fail|not_run` plus evidence.
- `assumptions`: load-bearing assumptions the lead must confirm. - `assumptions`: load-bearing assumptions the lead must confirm.
- `blocked_question`: one precise question, only when `status=blocked`. - `blocked_question`: one precise question, only when `status=blocked`.
@@ -64,7 +64,7 @@ Keep `summary` under ~300 characters. The lead reads summaries first and opens a
| Mistake | Fix | | Mistake | Fix |
|---|---| |---|---|
| Pasting the whole conversation into every prompt | Write a brief; point to files | | Pasting the whole conversation into every prompt | Write a brief; point to files |
| Vague acceptance ("works well") | A command and an expected result | | Vague acceptance ("works well") | A re-runnable check and an expected result |
| No non-goals | List what not to touch | | No non-goals | List what not to touch |
| Two tasks own one file | Serialize or merge | | Two tasks own one file | Serialize or merge |
| Task needs 2+ hours | Split by deliverable, not by file count | | Task needs 2+ hours | Split by deliverable, not by file count |
+9 -8
View File
@@ -1,10 +1,11 @@
# Swarm playbook # Swarm playbook
Detailed runbook for `agent-swarm`. Read this after the fit check passes. Keep `.swarm/state.json` current; it is the resume point if the session restarts. Detailed runbook for `agent-swarm`. Read this after the fit check passes. The runbook is domain-neutral; choose an adapter from `domains.md` and put its details in `.swarm/profile.md`. Keep `.swarm/state.json` current; it is the resume point if the session restarts.
## 0. Fit check and budget ## 0. Fit check and budget
Answer these before spawning: Answer these before spawning:
- **Mode.** Is this really a swarm, or does a direct run / paired critic cover the risk with less overhead?
- **Units.** Can you list 8+ deliverables that different agents can finish without waiting for each other? - **Units.** Can you list 8+ deliverables that different agents can finish without waiting for each other?
- **Writes.** Can every unit get a disjoint write scope? Name the shared files now. - **Writes.** Can every unit get a disjoint write scope? Name the shared files now.
- **Checks.** Does every unit have a command or criterion a verifier can re-run? - **Checks.** Does every unit have a command or criterion a verifier can re-run?
@@ -12,13 +13,13 @@ Answer these before spawning:
- **Breadth.** Is the time dominated by many independent pieces, not one deep chain? - **Breadth.** Is the time dominated by many independent pieces, not one deep chain?
Budget: Budget:
- `agents ≈ units + ceil(units / 5) verifiers + 1–2 integrators + 2–4 recon`; add retries and re-verifications explicitly. - `agents ≈ units + ceil(units / 5) verifiers + 1–2 integrators + 2–4 recon`; add retries and re-verifications explicitly. Set `max_agents` only after checking available tools and slot cap.
- Tokens ≈ `agents × 20k` (10–40k per agent depending on code reads). - Tokens ≈ `agents × 20k` (10–40k per agent depending on code reads).
- Waves ≈ `ceil(units / batch_size)` + verify + integrate, where `batch_size` comes from the **real** active-child cap, not from a documented default. - Waves ≈ `ceil(units / batch_size)` + verify + integrate, where `batch_size` comes from the **real** active-child cap, not from a documented default.
- Stop at `max_agents` or `max_waves`, whichever comes first. Record both, plus `slot_cap`, `active_at_dispatch`, `batch_size`, retries and re-verifications in `state.json`. - Stop at `max_agents` or `max_waves`, whichever comes first. Record both, plus `slot_cap`, `active_at_dispatch`, `batch_size`, retries and re-verifications in `state.json`.
Go: a 40-file migration with per-module tests, a 30-source research report, a 20-section document with a style guide. Go: a 40-file migration with per-module tests, a 30-source research report, a 20-section document with a style guide, a multi-dataset analysis, a multi-screen visual redesign, a multi-service runbook.
No-go: one failing test, one architectural decision, a refactor where every file imports the same core module. No-go: one failing test, one architectural decision, a detail pass where every unit touches the same artifact.
## 1. Recon (2–4 agents) ## 1. Recon (2–4 agents)
@@ -44,13 +45,13 @@ cp <skill>/assets/verdict.schema.json .swarm/verdict.schema.json
node <skill>/scripts/audit-scope.mjs --init node <skill>/scripts/audit-scope.mjs --init
``` ```
Write the plan before any worker starts. Write the plan before any worker starts. Keep the plan proportionate: a small domain task may need only a brief and a verifier, not a full `.swarm` tree.
**Decomposition.** One task = one deliverable, one writer, one acceptance check, at most one page. Budget **5–25 minutes for S/M** and **40–60 minutes for L**; the old blanket 25-minute rule underestimates large UI/refactor files. If a task is expected to produce a single source file over ~1,500 lines, split it by module or accept that it will be a long, integration-heavy task. If it needs two writers, split it; if it needs the whole repo, it is not a task. **Decomposition.** One task = one deliverable, one writer, one acceptance check, at most one page. The deliverable may be a module, a research question, a document section, a dataset, a design artifact, or a runbook. Budget **5–25 minutes for S/M** and **40–60 minutes for L**; if a task is expected to produce a single source file over ~1,500 lines (or a very large document/dataset), split it or accept an integration-heavy task. If it needs two writers, split it; if it needs the whole repo, it is not a task.
**Ownership.** Every path in exactly one `write` list. Add an explicit `LEAD` task whose `write` list contains lead/integrator-owned shared files, screenshots, licenses and the final report; without it, audit-scope reports the lead's own integration edits as unowned. Shared files are integrator-only: `package.json`, lockfiles, `tsconfig`, CI config, barrel/index files, schemas, migrations, i18n catalogs, snapshots, generated code. If two tasks must touch one file, serialize them with `depends_on` or merge them. **Ownership.** Every artifact/path in exactly one `write` list: files, sections, datasets, source notes, design files. Add an explicit `LEAD` task whose list contains lead/integrator-owned shared artifacts, screenshots, licenses and the final report; without it, audit-scope reports the lead's own integration edits as unowned. Shared files are integrator-only: manifests, lockfiles, indexes/barrels, schemas, shared style/token files, migrations, i18n catalogs, snapshots, generated code. If two tasks must touch one artifact, serialize them with `depends_on` or merge them.
**Contracts.** Freeze what crosses a boundary: function signatures, types, file names, CLI flags, error behavior, output format. Put them in `.swarm/contracts.md`; workers may not change them without returning `blocked`. **Contracts.** Freeze what crosses a boundary within the chosen domain: function signatures/types/file names/CLI behavior for software; source/date/citation format for research; section structure/terminology/render target for content; schema/units/definitions for data; breakpoints/states/tokens for design; approval/rollback boundaries for operations. The invariant is the same: a verifier can check the contract independently. Put it in `.swarm/contracts.md`; workers may not change it without returning `blocked`.
**Coverage matrix.** Each success criterion → task(s) → check. A criterion with no task is a hole; a task with no criterion is scope creep. **Coverage matrix.** Each success criterion → task(s) → check. A criterion with no task is a hole; a task with no criterion is scope creep.
+8 -3
View File
@@ -5,6 +5,11 @@ modals, dialogs that do not close, wrong DPI, a viewport that renders a blank ba
screenshot that captures a different agent's window. Treat visual verification as a separate test screenshot that captures a different agent's window. Treat visual verification as a separate test
tier with its own infrastructure. tier with its own infrastructure.
The commands below use Linux Xvfb + ImageMagick as one concrete provider. On macOS/Windows use a
container or the platform's virtual-display tooling; the invariant is **isolation and deterministic
capture**, not Xvfb itself. If the app can capture its own framebuffer, that is preferred on every
platform.
## Rule zero: never share one desktop ## Rule zero: never share one desktop
Do not run several visual agents against the same X11/Wayland session. They steal focus, overlap Do not run several visual agents against the same X11/Wayland session. They steal focus, overlap
@@ -17,7 +22,7 @@ Each visual agent gets:
- its own display (`DISPLAY=:N` / Wayland socket), - its own display (`DISPLAY=:N` / Wayland socket),
- its own `HOME`, `XDG_CONFIG_HOME`, `XDG_RUNTIME_DIR`, `TMPDIR`, - its own `HOME`, `XDG_CONFIG_HOME`, `XDG_RUNTIME_DIR`, `TMPDIR`,
- its own project copy/worktree and artifact directory, - its own project copy/worktree and artifact directory,
- its own `CARGO_TARGET_DIR` (or a read-only prebuilt cache + writable per-agent target), - its own build target/cache directory (or a read-only prebuilt cache + writable per-agent target),
- its own service port (BRP, dev server, websocket), - its own service port (BRP, dev server, websocket),
- a cleanup trap that kills the app, the X server and any helper processes. - a cleanup trap that kills the app, the X server and any helper processes.
@@ -66,7 +71,7 @@ export VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/lvp_icd.x86_64.json
# Start the app *after* the X socket exists. A small WM helps focus/IME. # Start the app *after* the X socket exists. A small WM helps focus/IME.
sleep 0.5 sleep 0.5
# openbox & # optional # openbox & # optional
timeout 120s cargo run -p app -- --screenshot-mode "$ART/app.png" & timeout 120s <run command> --screenshot-mode "$ART/app.png" &
APP_PID=$! APP_PID=$!
# Prefer an in-app deterministic screenshot. Fallback: capture the root window. # Prefer an in-app deterministic screenshot. Fallback: capture the root window.
@@ -84,7 +89,7 @@ Containers are useful for reproducibility and cleanup, not as a default for ever
- Build one pinned image with Rust, Xvfb, Mesa/lavapipe, ImageMagick, xdotool and a minimal WM. - Build one pinned image with Rust, Xvfb, Mesa/lavapipe, ImageMagick, xdotool and a minimal WM.
- Run one container per visual agent: `--rm --network=none --userns=keep-id`, no host `$HOME`, a - Run one container per visual agent: `--rm --network=none --userns=keep-id`, no host `$HOME`, a
read-only repo mount plus a writable worktree/artifact mount. read-only repo mount plus a writable worktree/artifact mount.
- Keep cargo registry/cache in a named read-only volume; use a per-container target dir. - Keep package-manager/build caches in a named read-only volume; use a per-container target dir.
- GPU: `--device /dev/dri` for Intel/AMD; NVIDIA needs the container toolkit/CDI. Prefer software - GPU: `--device /dev/dri` for Intel/AMD; NVIDIA needs the container toolkit/CDI. Prefer software
rendering for UI tests and reserve GPU containers for one final Tier 3 run. rendering for UI tests and reserve GPU containers for one final Tier 3 run.
- Limit visual containers to 2–4 concurrently; llvmpipe uses CPU aggressively. - Limit visual containers to 2–4 concurrently; llvmpipe uses CPU aggressively.