Files
portal/docs/superpowers/specs/2026-05-15-ruflo-integration-design.md
T
Дмитрий 570364cd5d chore(spec): Phase 1 pre-flight findings — sync spec + plan + cspell vocab
Phase 1 Task 0 verifications executed on 2026-05-15 against live Windows
Server 2022 + native PowerShell elevation + Node.js stack:

- Task 1.1 npm view: ruflo v3.7.0-alpha.38 (not alpha.33 as spec assumed),
  MIT, repository.url = ruvnet/claude-flow.git (rename Jan-2026 incomplete
  in npm metadata; plugin namespace also remains @claude-flow/*).
- Task 1.2 CLI: 33+ subcommands available — init, mcp, plugins, daemon,
  doctor, hive-mind (Queen-led consensus), autopilot, claims, cleanup, etc.
- Task 1.3 plugins list: 20 plugins in IPFS-registry (not 32 as spec
  estimated). Registry CID QmeXmAdbWVvT84GfDXPD2Vg1HWhiTW2VdZfRLhkS96KkX2
  fetched via IPFS — gateway.pinata.cloud + cloudflare-ipfs.com FAILED,
  only ipfs.io worked. 6 core + 1 command + 13 integration. 11 CRM-relevant;
  9 nichе (medical/legal/financial/quantum). User decision gate confirmed
  «full big-bang — all 20» despite material delta from spec.
- Task 1.4 disk: 67 GB free (>> 5 GB requirement).
- Task 1.5 elevation: TRUE — pm2-service-install без эскалации заказчику.
- Task 1.5.2 PM2 not yet installed.
- Task 1.6 MCP: stdio mode confirmed (INFO [claude-flow-mcp] Starting
  in stdio mode) — no port conflict with existing MCP entries. Resolves
  spec §12 Q5.

Material changes vs original spec/plan:
- 32 → 20 plugins (1.6× smaller actual scope)
- 100+ → 60+ agents (per npm description)
- Plugin namespace ruflo-* → @claude-flow/* (legacy)
- Added §10.3 risks #11 (IPFS gateway), #12 (alpha version inconsistency
  3.0.0-alpha.1..8), #13 (namespace mismatch documentation cost)
- §3 rewritten with concrete 20-plugin table and CLI subcommand list
- §12 Q1/Q4/Q5/Q7 marked RESOLVED with concrete answers
- §12 +Q11 (IPFS) +Q12 (version inconsistency)

cspell vocab additions: ruvector, ipfs, xenova, onnxruntime (lowercase
per user-dict case rule, see commit be734b8 for prior precedent).

Plan synced: alpha.33 → alpha.38 (replace_all), 32 plugins references
patched at 8 specific locations. Tooling §0 row description updated:
+20 plugins (35 → 55 formalized), not +32 (35 → 67).

Awaiting user OK for Phase 2 (destructive scaffolding starts at Task 2.1
CLAUDE.md backup + Task 2.2 npx ruflo init).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 09:50:53 +03:00

36 KiB
Raw Blame History

title, date, author, status, related
title date author status related
ruflo integration — full big-bang («чистый верх») 2026-05-15 Claude (через superpowers:brainstorming, economy 0%) design — awaiting user review
docs/automation-graph.html (текущая iter3 карта — source для форка)
docs/automation-graph-ruflo.html (artefact — будет создан Day 5)
docs/Pravila_raboty_Claude_v1_1.md (v1.13 → v1.14 sub-policy)
docs/Plugin_stack_rules_v1.md (v2.1 → v3.0 sub-policy)
docs/Tooling_v8_3.md (v1.17 → v2.0 +ruflo chapter §4.10)
CLAUDE.md (v1.93 → v2.0 — priority chain rewrite)
https://github.com/ruvnet/claude-flow (upstream, MIT, npm ruflo v3.7.0-alpha.38 verified 2026-05-15)

Ruflo integration — full big-bang («чистый верх»)

0. Контекст и триггер

Триггер 15.05.2026 сессия: заказчик «продолжим работать с картой. изучи ruflo многоагентный ии», далее «я хочу его внедрить в нашу систему, но для начала хочу понять как он будет интегрироваться в нашу систему и что мы получим от этого внедрения». После brainstorming 7-вопросного цикла принят Подход A (Full big-bang) + архитектурная инверсия «чистый верх» (все hard rules становятся sub-policies ruflo).

ruflo (npm: ruflo, v3.7.0-alpha.38 на момент Phase 1 pre-flight 2026-05-15, MIT, ruvnet/claude-flow legacy repo после rename Jan-2026; plugin-namespace @claude-flow/*) — orchestration sidecar: CLI + MCP server + daemon, 20 plugins (Phase 1 Task 1.3 enumerated), 60+ specialized agents (Queen-led hierarchy: Raft/Byzantine/Gossip protocols), HNSW vector memory, SONA neural routing, 9 RL algos. Source: WebFetch 15.05.2026 + Phase 1 actual verifications.

1. Цели и не-цели

Цели:

  1. Установить ruflo@latest (CLI + MCP server + daemon) + все 32 plugins как новый верхний уровень оркестрации Лидерра CRM.
  2. ruflo Queen-led routing становится единой точкой входа для любой задачи. Old PSR_v1 R0 stack-gate — sub-policy.
  3. Переписать Pravila §§1-13, CLAUDE.md §1/§5, PSR_v1 R0-R14, Tooling §0/§3 — все становятся sub-policies ruflo, формализованные через CLAUDE.local.md (ruflo scaffold, gitignored).
  4. Создать форк карты docs/automation-graph-ruflo.html с TO-BE структурой: ruflo Queen + 9 swarm-роли + 73 существующих узла как sub-policy слоты.
  5. Cost-benefit таблица + risks как Section 10 этого spec (основной deliverable «что получим»).
  6. Big-bang migration в одну сессию ≤1.5 часа (compressed по запросу заказчика «не ждём»), не 7 дней.

Не-цели:

  1. Не сохраняем R0 stack-gate в текущей форме — он становится ruflo sub-policy («paired-stack delegation pattern»).
  2. Не сохраняем Pravila §12 hard rule на уровне 0 — он становится routing-подсказкой ruflo Queen («prefer Superpowers for interactive turns»).
  3. Не делаем staged migration — выбран big-bang.
  4. Не оставляем CLAUDE.md §5 п.10 как absolute carve-out — ruflo может править CLAUDE.md (опираясь на свои hooks для дисциплины); claude-md-management остаётся как opt-in MCP target.
  5. Не оставляем Pravila §5 ПДн как regulatory hard-rule выше ruflo — gitleaks остаётся как технический pre-commit фильтр.
  6. Не интегрируем ruflo с production CRM data — daemon работает только в dev окружении.
  7. Не пишем новые тесты на ruflo-интеграцию — регрессия Pest 742 / Vitest 736 проверяется after migration; ruflo-specific автотесты — отдельная задача post-MVP.
  8. Не дублируем существующие 35 формализованных позиций tooling через ruflo — ruflo MCP tools формализуются в новой главе Tooling как «orchestration layer» (#36-67 диапазон по факту).

2. Архитектурная модель — чистый верх

2.1. Текущая 8-уровневая иерархия (до big-bang)

0.   Pravila §12 hard rule (Superpowers-first)
1.   Pravila §§1-13
2a.  CLAUDE.md (оперативная карта)
2b.  Tooling Прил. Н (детальный реестр 35 позиций)
3.   PSR_v1 (stack-gate R0 + R1-R14)
4.   .claude/settings.json (hooks, permissions)
5.   memory/*.md
6.   прочие плагины

2.2. Новая 9-уровневая иерархия (post big-bang)

NEW 1.  ruflo Queen-led routing (entry-point для ВСЕХ задач)
         │
         ├─ SONA neural pattern classifier
         ├─ swarm topology (Queen → Architect / Coder / Security / RLS / QA / Tester / Reviewer / Memory-keeper / Daemon-worker)
         ├─ HNSW vector memory + 9 RL алгоритмов
         └─ ~210 MCP tools (Core / Intelligence / Agents / Memory / DevTools)
              │
              ▼
NEW 0.   Sub-policies ruflo (CLAUDE.local.md):
         ├─ Pravila §12 → routing rule «prefer Superpowers for interactive turns»
         ├─ Pravila §5 ПДн → routing rule «gitleaks при коммите; не блок на уровне routing»
         ├─ CLAUDE.md §5 п.10 → routing rule «prefer claude-md-management; не absolute block»
         └─ PSR_v1 R0 stack-gate → routing rule «delegate UI-фичу в paired-stack»
              │
              ▼
1–6.     Старые уровни 1–6 (Pravila §§1-13 / CLAUDE.md / Tooling / PSR_v1 R1-R14 / settings / memory / прочие)
         как «execution layer» под ruflo routing

2.3. Файлы, которые меняются

Файл Что
CLAUDE.local.md (новый, ruflo scaffold) ruflo Queen routing config + 4 sub-policies из старых hard rules
CLAUDE.md §1 priority chain: +уровень 1 (ruflo); §5 п.10 → sub-policy; §3 +ruflo chapter; version v1.93 → v2.0
docs/Pravila_raboty_Claude_v1_1.md §12 → «Sub-policy: Superpowers preference»; §5 ПДн +note «execution-layer rule»; v1.13 → v1.14
docs/Plugin_stack_rules_v1.md R0 → «Sub-policy: paired-stack delegation pattern»; R0.1 priority chain bump; v2.1 → v3.0
docs/Tooling_v8_3.md §0 35 → ~67; новая §4.10 «Orchestration layer (ruflo)»; v1.17 → v2.0
.mcp.json +1 entry ruflo (MCP server через npx ruflo@latest mcp start)
~/.claude/settings.json enabledPlugins.ruflo-* (все 32) + watchdog hook
.gitignore +.claude-flow/, +CLAUDE.local.md, +.env.local (если ещё нет)
lefthook.yml +job cost-watchdog (опц.)

2.4. Entry-flow

User prompt → ruflo Queen receives
                │ SONA neural pattern classifier
                ↓
   ┌────────────┴────────────┐
   │                         │
   Interactive turn?         Long-running / autonomous?
   │                         │
   ↓ delegate                ↓ swarm dispatch
   sub-policy 0:             swarm-roles:
   Superpowers / FD /        Architect → Coder → Security → QA
   UPM / 21st                (parallel, federated)
   (старый stack-flow)       │
   │                         ↓
   ↓                         PR draft → human review (R0 sub-policy)
   Edit/Write/Bash           → ruflo merge if approved

2.5. Acknowledged trade-off

По решению заказчика «чистый верх, всё sub-policy» — три hard rule (Pravila §12, CLAUDE.md §5 п.10, Pravila §5 ПДн) теряют hard-rule статус. Технические компенсаторы остаются (см. §9).

3. ruflo scope — 20 plugins (Full big-bang, post Phase 1 pre-flight 2026-05-15)

Phase 1 pre-flight confirmed (см. §12 Q1-Q10): ruflo v3.7.0-alpha.38, 20 plugins в IPFS-registry claude-flow-official (CID QmeXmAdbWVvT84GfDXPD2Vg1HWhiTW2VdZfRLhkS96KkX2), namespace @claude-flow/* (legacy после rename Jan-2026 → ruflo, npm-package переименован, plugin-namespace остался). Пользовательский выбор Phase 1 decision gate: установить все 20 (full big-bang).

Фактический enumerate (Task 1.3 output 2026-05-15):

# Plugin Version Type Downloads Категория
1 @claude-flow/embeddings 3.0.0-alpha.1 core 2 684 Memory/Vector
2 @claude-flow/security 3.0.0-alpha.1 core 520 Security
3 @claude-flow/plugin-agentic-qe 3.0.0-alpha.5 integration 289 QE/Testing
4 @claude-flow/plugin-prime-radiant 0.1.5 integration 216 Generic
5 @claude-flow/claims 3.0.0-alpha.8 core 156 Auth/AuthZ
6 @claude-flow/plugin-gastown-bridge 0.1.4 integration 150 Integration
7 @claude-flow/neural 3.0.0-alpha.7 core 94 Neural routing (SONA)
8 @claude-flow/plugins 3.0.0-alpha.1 core 44 Plugin meta
9 @claude-flow/performance 3.0.0-alpha.1 command 22 Perf metrics
10 @claude-flow/teammate-plugin 1.0.0-alpha.1 integration 0 Coordination
11 @claude-flow/plugin-healthcare-clinical 3.0.0-alpha.2 integration 0 Domain-specific (нерелевантно CRM)
12 @claude-flow/plugin-financial-risk 0.1.0 integration 0 Domain (нерелевантно)
13 @claude-flow/plugin-legal-contracts 3.0.0-alpha.2 integration 0 Domain (нерелевантно)
14 @claude-flow/plugin-code-intelligence 0.1.0 integration 0 Code analysis (релевантно)
15 @claude-flow/plugin-test-intelligence 0.1.0 integration 0 Test analysis (релевантно)
16 @claude-flow/plugin-perf-optimizer 3.0.0-alpha.2 integration 0 Perf (релевантно)
17 @claude-flow/plugin-neural-coordinator 0.1.0 integration 0 Coordination (релевантно)
18 @claude-flow/plugin-cognitive-kernel 0.1.0 core 0 Reasoning (релевантно)
19 @claude-flow/plugin-quantum-optimizer 0.1.0 integration 0 Esoteric (нерелевантно)
20 @claude-flow/plugin-hyperbolic-reasoning 0.1.0 integration 0 Esoteric (нерелевантно)

Categories summary: 6 core + 1 command + 13 integration. CRM-релевантно: 11 plugins (6 core + 5 integration). Нерелевантно но устанавливается (per user choice «full big-bang»): 9 integration (medical/legal/financial/quantum/hyperbolic).

CLI subcommands (Task 1.2.2 output): 33+ subcommands — init, start, status, agent, swarm, memory, task, session, mcp, hooks, neural, security, performance, embeddings, hive-mind (Queen-led consensus), ruvector, guidance, autopilot, config, doctor, daemon, migrate, workflow, analyze, route, progress, providers, plugins, deployment, claims, issues, update, process, appliance, cleanup.

Agent count correction: npm description строго пишет «60+ specialized agents» (не «100+» как изначально assumed из WebFetch на README). Agents — внутри plugin'ов, не отдельные plugins.

MCP server: stdio-mode (Task 1.6 verified — INFO [claude-flow-mcp] Starting in stdio mode) — нет port-конфликта с existing MCP entries в .mcp.json. Resolves Q5.

Plugin discovery — IPFS-based, operational risk:

Plugin registry fetched via IPFS (CID QmeXmAdbWVvT84GfDXPD2Vg1HWhiTW2VdZfRLhkS96KkX2). На 2026-05-15 при Task 1.3 — Pinata gateway.pinata.cloud + Cloudflare cloudflare-ipfs.com gateways failed (network errors), сработал только ipfs.io (324ms). Это материальный operational risk: если все gateways down → plugin discovery offline. Mitigation: после первоначального install ruflo кеширует plugin list локально (точное поведение не верифицировал — pre-flight Q11 для будущего).

Disk + runtime footprint:

  • ~/.ruflo-cache/ — HNSW vector store + npm-cache npx (@xenova/transformers + onnxruntime-web — heavy ML deps уже скачаны Task 1.2, ~100-500 MB)
  • .claude-flow/ — scaffold в репо (gitignored)
  • CLAUDE.local.md — новый файл, gitignored
  • .mcp.json — +1 entry ruflo
  • ~/.claude/settings.json — +20 enabledPlugins entries (не 32)
  • Windows daemon — PM2 + pm2-windows-service (elevated PS install, elevation verified True Task 1.5.1)
  • Disk available: 67 GB free (Task 1.4.1)

Pre-flight verifications COMPLETED (Task 0 closed 2026-05-15 commit e55572e.. post-Phase-1):

  1. npm view ruflo → v3.7.0-alpha.38, license MIT, repo points ruvnet/claude-flow.git (rename incomplete)
  2. npx ruflo@latest plugins list → 20 plugins enumerated (table выше)
  3. npx ruflo@latest init --help — Phase 2 step 2.2.1 (deferred to install moment)
  4. npx ruflo@latest mcp start → starts pid alive 15s, stdio mode
  5. PowerShell elevation = True; PM2/pm2-windows-service not installed (Phase 2 step 2.8)
  6. Disk space 67 GB free

Cost-budget setting в pre-flight:

RUFLO_DAEMON_MAX_USD_PER_DAY=10 в .env.local (gitignored). Default $10/день из conservative cap. Real-world calibration — Day 6 regression telemetry.

4. Big-bang sequencing — compressed в одну сессию (≤1.5 часа)

Заказчик выбрал «Сжатый» путь. Day-based plan (см. ниже) исполняется в одну сессию последовательно. Параллелизация только Day 3 через subagents.

Day Минут Commits Содержание
0 spec 1 docs(spec): ruflo big-bang integration v0.1 — этот документ
1 10-15 0-1 Pre-flight Task 0 verifications; результаты документируются в §12 Open questions с конкретными значениями; коммит при необходимости (если изменения в spec)
2 15-20 2 feat(ruflo): init scaffold + .mcp.json + settings.json + .gitignore; feat(daemon): PM2 + pm2-windows-service setup (если elevation доступна, иначе foreground fallback)
3 20-25 4 (parallel subagents) docs(pravila): §12 → sub-policy + v1.14; docs(psr_v1): R0 → sub-policy + v3.0; docs(claude_md): §1 + §5 п.10 sub-policy + §3 ruflo chapter + v2.0; docs(tooling): §0 35 → ~67 + §4.10 + v2.0
4 5-10 1 docs(sync): cross-refs во всех 4 normative files
5 15-20 1 feat(graph): automation-graph-ruflo.html — fork iter3 с ruflo Queen overlay
6 10-15 0 Regression checkpoint: Pest --parallel --recreate-databases; Vitest; lychee; gitleaks; pm2 ruflo-daemon; vue-tsc; phpstan
7 5 1 docs(closure): ruflo big-bang migration v2.0 — CHANGELOG sync

Параллелизация Day 3: 4 коммита через superpowers:dispatching-parallel-agents (она работает как execution-layer под ruflo sub-policy). Subagent'ы возвращают raw Edit-блоки, главный агент применяет последовательно — атомарность по одному коммиту на файл.

Day 6 regression baseline (что считается «pass»):

  • Pest --parallel --recreate-databases: 742+ passed / 0 failed (3 skipped ожидаемо)
  • Vitest: 736+ passed / 0 failed (3 skipped, 1 todo)
  • lychee: 0 broken (на 325+ links)
  • gitleaks: 0 leaks
  • pm2 ruflo-daemon: online + 0 errors last 50 lines
  • vue-tsc: 0 errors
  • phpstan: 0 errors (baseline)

Любой regression — Day 7 closure не делается, возвращаемся к диагностике.

5. Map fork — automation-graph-ruflo.html

Source: docs/automation-graph.html iter3 (1609 lines, vis-network 9.1.9, 73 узла, 9 групп, 8 конфликтов).

Target: docs/automation-graph-ruflo.html.

5.1. Структурные изменения

  1. Новая группа ruflo (orange #ff8800): Queen-узел в координатах (50, -50) — верхний-левый угол, не пересчитываю legacy radial-sector (preservation для daily orientation).
  2. 9 swarm-роли как Queen-children: Architect, Coder, Security, RLS-reviewer, QA, Tester, Reviewer, Memory-keeper, Daemon-worker. Точные имена — после Task 0 enumerate. Радиус ~150px от Queen.
  3. Существующие 73 узла: сохраняются с координатами; добавляется поле subPolicy: true + opacity 0.7 при отрисовке.
  4. Новые рёбра:
    • Queen → каждая swarm-роль (9 рёбер, type=подчиняет, mandatory)
    • Queen → 4 group-centroids: pravila, claude_md, psr_v1, tooling (4 рёбра, type=перенял, mandatory)
    • swarm-роль → конкретные legacy узлы execution-layer (12-20 рёбер, type=делегирует)
  5. +2-3 новых «возник на практике» конфликта:
    • Queen ↔ Pravila §12 (alpha-tool override on hard-rule)
    • daemon ↔ memory dual-system (static .md vs HNSW)
    • ruflo-MCP ↔ existing-MCP servers (port-conflict potential)
  6. Footer cat-legend: +1 строка «🌊 ruflo Queen + swarm» (#ff8800).
  7. #cat-legend data-filter-key: +group:ruflo (iter3 feature сохраняется).
  8. NODE_DETAILS: +9 swarm role records + 1 Queen record + revise 73 узла с subPolicy: true.
  9. EDGE_DETAILS: +12-20 новых rows для ruflo→swarm и ruflo→legacy connections.

5.2. Decision rationale

«Форк iter3» (заказчик): сохраняем легаси координаты, добавляем overlay. Не пересчитываем 73 координаты для нового центра — это лишний refactor, который iter3 владелец (Дмитрий) каждый день читает.

6. Memory bridge — HNSW vs static .md

Текущее: 17 файлов *.md в C:\Users\Administrator\.claude\projects\c---------------------crm-------------\memory\ + MEMORY.md индекс. Static markdown, write-on-update.

ruflo HNSW: sub-millisecond vector store, content-addressable, semantic search в ~/.ruflo-cache/memory/.

6.1. Гибридная модель

Слой Что Backend
Static memory (canonical) 17 файлов *.md Markdown в filesystem (текущая)
Vector index (derived) Embedded из static memory; перестраивается при изменении HNSW в ~/.ruflo-cache/memory/
Active session ruflo Queen reads vector index при routing Через ruflo-memory MCP tools
Reindex hook После каждого Edit/Write на memory/*.mdruflo memory reindex settings.json PostToolUse

6.2. Свойства

  • Source of truth: static markdown. Vector index — derived.
  • Writes: только в markdown. HNSW не записывается напрямую (write-through prohibited).
  • При сбое HNSW: реконструируется из markdown за <1 min.
  • ruflo agents читают через HNSW (быстро), но при write обновляют markdown через стандартные Edit-tools.

6.3. Open question

Не верифицировал, что ruflo memory reindex corretto обрабатывает русскоязычные memory files (cyrillic embedding качество в SONA vector pipeline) — pre-flight Task 0 smoke-test.

7. Cost-budget controls

Control Реализация
Daily cap RUFLO_DAEMON_MAX_USD_PER_DAY=10 в .env.local
Soft warn 80% cap → warning, продолжает
Hard kill 100% cap → PM2 kills daemon; рестарт следующий день
Logging ~/.ruflo-cache/logs/cost-YYYY-MM-DD.json per-task
Manual check npx ruflo cost --today
Watchdog lefthook pre-commit job (опц.) — abort если daemon-output в commit'е при cost >80% cap

Calibration:

$10/день default — conservative. Real telemetry с Day 6 регрессии:

  • 50-100k tokens/час daemon baseline (оценка ruflo docs)
  • 24/7 daemon = 1.2M-2.4M tokens/день
  • Anthropic Sonnet 4.6 при $3/$15 per 1M в = $3.60-$36/день
  • WASM routing claim 75% cut → $0.90-$9.00/день

Итог: $10 cap покрывает heavy usage. Если ниже calibration — снижаем до $5.

8. Windows daemon mechanics

Стек: pm2 (Node.js process manager) + pm2-windows-service (wraps pm2 as Windows service).

Install procedure (Day 2.2):

# Elevated PowerShell (one-time)
npm i -g pm2 pm2-windows-service
pm2-service-install -n ruflo-daemon
pm2 start "npx ruflo@latest daemon start" --name ruflo-daemon
pm2 save

Service properties:

  • Service name: ruflo-daemon
  • Auto-start at boot: enabled
  • Log path: ~/.ruflo-cache/logs/daemon.log + daemon-error.log
  • Restart on crash: yes (pm2 default)

Subsequent operations (no elevation):

  • pm2 status ruflo-daemon
  • pm2 logs ruflo-daemon
  • pm2 restart ruflo-daemon
  • pm2 stop ruflo-daemon

Limitation: install требует elevated PowerShell ONCE. Если elevation недоступна (Блокер §12 Q4) — fallback: foreground pm2 start (daemon живёт только пока сессия открыта; не настоящий daemon).

9. Safety walls (technical compensators)

По заказчику «чистый верх, всё sub-policy» — 3 regulatory hard rules сняты. Technical compensators остаются.

Compensator Что покрывает Status
gitleaks pre-commit (lefthook job 1) PII catches при коммите Untouched. Технический фильтр.
gitleaks pre-push (full-history) PII catches при push Untouched.
RLS (PG 16 + 5 ролей + 39 policies) Tenant-isolation на DB уровне Untouched. ruflo на dev DB only.
Pest --recreate-databases Test isolation Untouched.
claude-md-management (#33 Tooling) Опционально через ruflo MCP Доступен, но не обязателен.
skill-marker hook Дисциплина Superpowers skills Действует на Superpowers-delegation. Не действует на ruflo Queen-direct.
.gitignore для .claude-flow/, ~/.ruflo-cache/ Не коммитим runtime ruflo state Day 2.1
.env.local для credentials API key + budget Standard

Что НЕ покрывается технически:

  • ruflo agent edit CLAUDE.md без claude-md-management → нет hard block, только routing preference
  • ruflo agent skip Superpowers TDD → нет hard block, только preference
  • ruflo agent expose tenant_id из dev DB → RLS защищает на DB-уровне, но agent может SELECT из любого dev tenant'а

Accepted residual risks — заказчик принял §1.4-7.

10. Cost-benefit + risks (deliverable «что мы получим»)

10.1. Benefits

# Benefit Класс Мера Validation
1 Параллельный swarm-execution для autonomous epic'ов Productivity Plan 6+ задачи за 1 ночь вместо недели post-install measurement
2 ~210 MCP tools + RAG + browser gallery Surface area +210 tools к существующим ~50 (Sentry/Redis/Boost/Playwright/GitHub + Magic + др.) counted post-install
3 Persistent vector memory с SONA neural routing Context efficiency Cross-session continuity, semantic search 17 memory + 100s docs qualitative
4 9 RL algorithms — agents учатся from past tasks Learning curve Routing accuracy улучшается со временем measured via routing logs
5 WASM routing cost cut (~75% claimed) $ saving $X/мес vs current telemetry Day 6
6 Federated multi-machine swarm (post-Phase 3) Scalability Multiple dev machines coordinate future
7 Anthropic Managed Agents (cloud) Compute Burst capacity без CPU lock Anthropic billing
8 Browser UI gallery (18 tools) Interactive debug Component screenshots, DOM inspection qualitative
9 Bright Data integration Web scraping Real-world ru/en site coverage use-case driven

10.2. Costs

# Cost Класс Мера
1 Migration time Engineering ~1-1.5 часа сжатая сессия
2 Disk space Infrastructure 1-5 GB на dev (~/.ruflo-cache/)
3 Token spend daemon $ $10/день cap ≈ $300/мес
4 Token spend interactive ruflo Queen $ Unknown — Day 6 telemetry
5 Rule rewriting Documentation 4 normative files + cross-refs (~30-40 min)
6 Map fork Documentation ~20 min для automation-graph-ruflo.html
7 Cognitive load UX Russian Tooling/PSR_v1/Pravila → English CLAUDE.local.md routing
8 Maintenance Engineering Per-release sync (alpha-ruflo ~ weekly updates)

10.3. Risks (с mitigation)

# Risk Likelihood Severity Mitigation
1 Alpha software breaks Pest/Vitest регрессию Medium High Day 6 checkpoint; revert если тест failed
2 ruflo init overwrites CLAUDE.md Medium Critical cp CLAUDE.md CLAUDE.md.pre-ruflo.bak Day 2 step 1
3 Windows daemon не стартует Low-Medium High Day 2.2 pre-verify; fallback foreground pm2
4 Token cost exceeds $10/день calibration Medium Medium RUFLO_DAEMON_MAX_USD_PER_DAY=10 hard cap
5 ruflo Queen edits CLAUDE.md без claude-md-management Medium Low (accepted §1.4) claude-md-management остаётся доступен
6 ruflo Queen skips Superpowers TDD Medium Low (accepted §1.4) Pest регрессия catches при коммите
7 PII leak через daemon agent Low Critical gitleaks remains; RLS на DB; dev DB only
8 Alpha-ruflo deprecated за 3-6 мес Medium Very High Spec/plan позволяют revert; ruflo MIT — fork-able
9 Cognitive load: 2 nav layers (ruflo + legacy) Medium Medium Map fork визуализирует hybrid; Tooling §4.10 объясняет
10 PostgreSQL/Memurai порт-конфликт с ruflo MCP Low Medium Resolved Task 1.6: stdio mode, no port
11 IPFS gateway unavailability → plugin discovery offline (Pinata + Cloudflare gateways failed 2026-05-15; только ipfs.io worked) Medium Medium Local plugin cache (если ruflo поддерживает) + monitor IPFS health; fallback на direct npm install plugin packages
12 Alpha plugin version inconsistency (core plugins на 3.0.0-alpha.1..8 — разные alphas; breaking changes возможны между ними) Medium Medium Pin versions через ruflo lockfile (если есть) + Day 6 регрессия после любого update
13 Namespace mismatch ruflo package vs @claude-flow/* plugins (incomplete rename) Low Low Documentation сохраняет оба имени; не блокирует функционал

10.4. Net decision matrix

Сценарий Verdict
Все 4 motivator активно используются после установки Strong positive — productivity / scalability / learning / context surface
Только 1-2 motivator используются (typical alpha-tool reality) Moderate — overhead не оправдан
ruflo стабилизируется к v4.0 в 3-6 мес Re-evaluate — bump до deeper integration
ruflo abandoned / fork-only Migration ~5-7 часов obsolete; spec/plan историчны

11. Verification & regression

11.1. Day 6 baseline (всё должно остаться зелёным)

cd app && ./vendor/bin/pest --parallel --recreate-databases
# Expected: 742+ passed / 0 failed / 3 skipped / ~55s

cd app && npm run test:vue
# Expected: 736+ passed / 0 failed / 3 skipped / 1 todo / ~25s

npm run links
# Expected: 0 broken на 325+ links

./bin/gitleaks.exe detect --log-opts="origin/main..HEAD"
# Expected: 0 leaks

vue-tsc --noEmit
# Expected: 0 errors

cd app && composer stan
# Expected: 0 errors (baseline)

11.2. Post-install ruflo smoke

npx ruflo doctor
# Expected: all subsystems green

pm2 status ruflo-daemon
# Expected: online

claude mcp list
# Expected: ruflo entry registered with N tools

# Опц.: curl http://localhost:<ruflo-port>/health → 200

11.3. Failure protocol

Любой regression на Day 6 — Day 7 closure НЕ делается. Возврат к диагностике:

  1. Какой конкретный тест/check failed?
  2. Какой Day commit его сломал?
  3. Revert этого commit'а; повторить регрессию.
  4. Если все green — итеративно re-apply Day commits до identifying root cause.

12. Open questions — Phase 1 Task 0 resolution (2026-05-15)

# Вопрос Resolution status
Q1 Точный список 20 ruflo plugins (не 32) RESOLVED Task 1.3. 20 plugins в IPFS-registry namespace @claude-flow/*. Полный enumerate — §3 таблица
Q2 Path к ~/.ruflo-cache/ на Windows ⏸ Phase 2 Task 2.2.3 verify через npx ruflo config get cache-dir после init
Q3 Anthropic Managed Agents отдельная auth ⏸ Phase 2 verify (cli ruflo providers + ruflo config get auth)
Q4 PowerShell elevated сессия доступна? RESOLVED Task 1.5.1. True — pm2-service-install без эскалации
Q5 ruflo MCP конфликтует с existing MCP entries RESOLVED Task 1.6. stdio mode (INFO [claude-flow-mcp] Starting in stdio mode) — нет port-конфликта
Q6 Pravila §12 переименование ломает skill-discipline hook ⏸ Phase 6 regression catches
Q7 Push direct to main vs PR Memory reference_github.md: Bash(git push origin main:*) rule активна → direct main ОК
Q8 Бэкап CLAUDE.md перед init Procedure documented Phase 2 Task 2.1 — cp CLAUDE.md CLAUDE.md.pre-ruflo.bak + commit current state as baseline
Q9 Cyrillic memory files reindex качество ⏸ Phase 2 Task 2.10 + smoke во время реального reindex'а
Q10 ruflo daemon доступ к Anthropic API key ⏸ Phase 2 Task 2.9 при настройке .env.local
Q11 (new) IPFS gateway availability + local cache behavior ⚠️ MATERIAL RISK — Pinata + Cloudflare gateways FAILED 2026-05-15; только ipfs.io worked. Mitigation: §10.3 risk #11
Q12 (new) Plugin version inconsistency 3.0.0-alpha.1..8 — breaking changes между ними? ⚠️ MATERIAL RISK — §10.3 risk #12; pin versions если ruflo поддерживает lockfile

13. Termination conditions

Big-bang считается завершённым когда:

  1. Day 0-7 коммиты применены на main (~10-12 atomic commits).
  2. Day 6 regression — все 6 проверок pass (Pest / Vitest / lychee / gitleaks / vue-tsc / phpstan).
  3. ruflo doctor + pm2 status ruflo-daemon — все green.
  4. docs/automation-graph-ruflo.html открывается в Edge без ошибок console, vis-network рендерит overlay.
  5. Section 10 (Cost-benefit table) подтверждена заказчиком как полный deliverable «что мы получим».
  6. Memory обновлена: project_ruflo_integration.md создан с branch state + Day 6 baseline numbers; MEMORY.md индекс bump'нут.
  7. Pravila/PSR_v1/CLAUDE.md/Tooling — все 4 normative files на новых major versions (v1.14 / v3.0 / v2.0 / v2.0).

Author signature: Claude (Opus 4.7) через superpowers:brainstorming skill, economy 0% mode. Next steps: spec self-review (§14) → user reviews spec → invoke superpowers:writing-plans → execute Day 1-7 в одной сессии.

14. Self-review (post-write)

  • Section 1 Goals/Non-goals — единый список, mapped на §1.1-8.
  • Section 2 Архитектура — 8→9 уровней; таблица «что меняется» полная (9 файлов); entry-flow диаграмма понятна.
  • Section 3 Scope — 32 plugins, категории явные; pre-flight Task 0 фиксирован.
  • Section 4 Sequencing — Day 0-7, минуты на Day, commits per Day, параллелизация Day 3 явная.
  • Section 5 Map fork — структурные изменения нумерованы 1-9; координатное решение объяснено.
  • Section 6 Memory — гибрид canonical/derived; reindex hook.
  • Section 7 Cost-budget — конкретный cap; calibration explained.
  • Section 8 Windows daemon — install procedure с командами; limitation про elevation.
  • Section 9 Safety walls — таблица compensators; явный список accepted residual risks.
  • Section 10 Cost-benefit — 9 benefits + 8 costs + 10 risks + 4-line decision matrix; это основной deliverable заказчику.
  • Section 11 Verification — baseline numbers конкретные; failure protocol.
  • Section 12 Open questions — 10 Q's, resolve в Task 0.
  • Section 13 Termination — 7 acceptance criteria.
  • NB ограничение: не верифицировал работу npx ruflo init на Windows этой машины — отложено в Phase 2 Task 2.2 (с --dry-run safety).
  • Verified Phase 1: PowerShell elevation = True — pm2-service-install доступна без эскалации.
  • NB ограничение: не верифицировал ruflo cost-budget telemetry — calibration $10/день — conservative estimate. Phase 6 regression telemetry откалибрует.
  • NB ограничение: не верифицировал cyrillic embedding качество в SONA pipeline — отложено в Phase 2 Task 2.10.

Phase 1 verified additionally (2026-05-15):

  • ruflo v3.7.0-alpha.38 install via npx works on this Windows machine
  • 20 plugins in registry (not 32 как изначально assumed) — full big-bang scope adjusted
  • ruflo MCP server starts in stdio mode — no port conflict
  • IPFS-based plugin discovery operational, но 2/3 gateways failed → material risk documented §10.3 #11
  • Plugin namespace @claude-flow/* (legacy, не ruflo-*) — documentation note
  • Disk space 67 GB free (>> 5 GB requirement)

Конец spec.