@evolve.labs/devflow 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/.claude/commands/agents/architect.md +1162 -0
  2. package/.claude/commands/agents/architect.meta.yaml +124 -0
  3. package/.claude/commands/agents/builder.md +1432 -0
  4. package/.claude/commands/agents/builder.meta.yaml +117 -0
  5. package/.claude/commands/agents/chronicler.md +633 -0
  6. package/.claude/commands/agents/chronicler.meta.yaml +217 -0
  7. package/.claude/commands/agents/guardian.md +456 -0
  8. package/.claude/commands/agents/guardian.meta.yaml +127 -0
  9. package/.claude/commands/agents/strategist.md +483 -0
  10. package/.claude/commands/agents/strategist.meta.yaml +158 -0
  11. package/.claude/commands/agents/system-designer.md +1137 -0
  12. package/.claude/commands/agents/system-designer.meta.yaml +156 -0
  13. package/.claude/commands/devflow-help.md +93 -0
  14. package/.claude/commands/devflow-status.md +60 -0
  15. package/.claude/commands/quick/create-adr.md +82 -0
  16. package/.claude/commands/quick/new-feature.md +57 -0
  17. package/.claude/commands/quick/security-check.md +54 -0
  18. package/.claude/commands/quick/system-design.md +58 -0
  19. package/.claude_project +52 -0
  20. package/.devflow/agents/architect.meta.yaml +122 -0
  21. package/.devflow/agents/builder.meta.yaml +116 -0
  22. package/.devflow/agents/chronicler.meta.yaml +222 -0
  23. package/.devflow/agents/guardian.meta.yaml +127 -0
  24. package/.devflow/agents/strategist.meta.yaml +158 -0
  25. package/.devflow/agents/system-designer.meta.yaml +265 -0
  26. package/.devflow/project.yaml +242 -0
  27. package/.gitignore-template +84 -0
  28. package/LICENSE +21 -0
  29. package/README.md +249 -0
  30. package/bin/devflow.js +54 -0
  31. package/lib/autopilot.js +235 -0
  32. package/lib/autopilotConstants.js +213 -0
  33. package/lib/constants.js +95 -0
  34. package/lib/init.js +200 -0
  35. package/lib/update.js +181 -0
  36. package/lib/utils.js +157 -0
  37. package/lib/web.js +119 -0
  38. package/package.json +57 -0
  39. package/web/CHANGELOG.md +192 -0
  40. package/web/README.md +156 -0
  41. package/web/app/api/autopilot/execute/route.ts +102 -0
  42. package/web/app/api/autopilot/terminal-execute/route.ts +124 -0
  43. package/web/app/api/files/route.ts +280 -0
  44. package/web/app/api/files/tree/route.ts +160 -0
  45. package/web/app/api/git/route.ts +201 -0
  46. package/web/app/api/health/route.ts +94 -0
  47. package/web/app/api/project/open/route.ts +134 -0
  48. package/web/app/api/search/route.ts +247 -0
  49. package/web/app/api/specs/route.ts +405 -0
  50. package/web/app/api/terminal/route.ts +222 -0
  51. package/web/app/globals.css +160 -0
  52. package/web/app/ide/layout.tsx +43 -0
  53. package/web/app/ide/page.tsx +216 -0
  54. package/web/app/layout.tsx +34 -0
  55. package/web/app/page.tsx +303 -0
  56. package/web/components/agents/AgentIcons.tsx +281 -0
  57. package/web/components/autopilot/AutopilotConfigModal.tsx +245 -0
  58. package/web/components/autopilot/AutopilotPanel.tsx +299 -0
  59. package/web/components/dashboard/DashboardPanel.tsx +393 -0
  60. package/web/components/editor/Breadcrumbs.tsx +134 -0
  61. package/web/components/editor/EditorPanel.tsx +120 -0
  62. package/web/components/editor/EditorTabs.tsx +229 -0
  63. package/web/components/editor/MarkdownPreview.tsx +154 -0
  64. package/web/components/editor/MermaidDiagram.tsx +113 -0
  65. package/web/components/editor/MonacoEditor.tsx +177 -0
  66. package/web/components/editor/TabContextMenu.tsx +207 -0
  67. package/web/components/git/GitPanel.tsx +534 -0
  68. package/web/components/layout/Shell.tsx +15 -0
  69. package/web/components/layout/StatusBar.tsx +100 -0
  70. package/web/components/modals/CommandPalette.tsx +393 -0
  71. package/web/components/modals/GlobalSearch.tsx +348 -0
  72. package/web/components/modals/QuickOpen.tsx +241 -0
  73. package/web/components/modals/RecentFiles.tsx +208 -0
  74. package/web/components/projects/ProjectSelector.tsx +147 -0
  75. package/web/components/settings/SettingItem.tsx +150 -0
  76. package/web/components/settings/SettingsPanel.tsx +323 -0
  77. package/web/components/specs/SpecsPanel.tsx +1091 -0
  78. package/web/components/terminal/TerminalPanel.tsx +683 -0
  79. package/web/components/ui/ContextMenu.tsx +182 -0
  80. package/web/components/ui/LoadingSpinner.tsx +66 -0
  81. package/web/components/ui/ResizeHandle.tsx +110 -0
  82. package/web/components/ui/Skeleton.tsx +108 -0
  83. package/web/components/ui/SkipLinks.tsx +37 -0
  84. package/web/components/ui/Toaster.tsx +57 -0
  85. package/web/hooks/useFocusTrap.ts +141 -0
  86. package/web/hooks/useKeyboardShortcuts.ts +169 -0
  87. package/web/hooks/useListNavigation.ts +237 -0
  88. package/web/lib/autopilotConstants.ts +213 -0
  89. package/web/lib/constants/agents.ts +67 -0
  90. package/web/lib/git.ts +339 -0
  91. package/web/lib/ptyManager.ts +191 -0
  92. package/web/lib/specsParser.ts +299 -0
  93. package/web/lib/stores/autopilotStore.ts +288 -0
  94. package/web/lib/stores/fileStore.ts +550 -0
  95. package/web/lib/stores/gitStore.ts +386 -0
  96. package/web/lib/stores/projectStore.ts +196 -0
  97. package/web/lib/stores/settingsStore.ts +126 -0
  98. package/web/lib/stores/specsStore.ts +297 -0
  99. package/web/lib/stores/uiStore.ts +175 -0
  100. package/web/lib/types/index.ts +177 -0
  101. package/web/lib/utils.ts +98 -0
  102. package/web/next.config.js +50 -0
  103. package/web/package.json +54 -0
  104. package/web/postcss.config.js +6 -0
  105. package/web/tailwind.config.ts +68 -0
  106. package/web/tsconfig.json +41 -0
@@ -0,0 +1,84 @@
1
+ # DevFlow .gitignore
2
+
3
+ # Node modules (se usar JavaScript/TypeScript)
4
+ node_modules/
5
+ npm-debug.log*
6
+ yarn-debug.log*
7
+ yarn-error.log*
8
+
9
+ # Environment variables
10
+ .env
11
+ .env.local
12
+ .env.*.local
13
+
14
+ # Local settings (não distribuir)
15
+ *.local.json
16
+ settings.local.json
17
+
18
+ # IDE específicos
19
+ .vscode/*
20
+ !.vscode/settings.json
21
+ !.vscode/tasks.json
22
+ !.vscode/launch.json
23
+ !.vscode/extensions.json
24
+ .idea/
25
+ *.swp
26
+ *.swo
27
+ *~
28
+
29
+ # OS específicos
30
+ .DS_Store
31
+ Thumbs.db
32
+
33
+ # Build outputs
34
+ dist/
35
+ build/
36
+ *.tsbuildinfo
37
+
38
+ # Logs
39
+ logs/
40
+ *.log
41
+
42
+ # Temporary files
43
+ tmp/
44
+ temp/
45
+ *.tmp
46
+
47
+ # Python (se usar)
48
+ __pycache__/
49
+ *.py[cod]
50
+ *$py.class
51
+ .Python
52
+ venv/
53
+ env/
54
+
55
+ # Arquivos grandes ou sensíveis
56
+ *.zip
57
+ *.tar.gz
58
+ *.rar
59
+
60
+ # Mantenha estas pastas (não ignore)
61
+ # Importante: queremos versionar a documentação!
62
+ !.devflow/
63
+ !docs/
64
+ !planning/
65
+ !architecture/
66
+ !CHANGELOG.md
67
+
68
+ # Snapshots podem ser grandes, você decide se quer versionar
69
+ # Descomente a linha abaixo se NÃO quiser versionar snapshots:
70
+ # docs/snapshots/*.json
71
+
72
+ # DevFlow Development (não incluir no release)
73
+ build-release.sh # Script de build fica apenas no dev
74
+
75
+ # Web IDE build artifacts (users run npm install themselves)
76
+ web/.next/
77
+ web/node_modules/
78
+ web/CHANGELOG.md
79
+ web/README.md
80
+
81
+ # Releases geradas (versionadas separadamente)
82
+ # Mantenha release/ versionado para distribuição
83
+ !release/
84
+ web/.devflow/
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Evolve Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,249 @@
1
+ # DevFlow v0.7.0 - Sistema Multi-Agentes + Web IDE
2
+
3
+ Sistema de multi-agentes especializados para desenvolvimento de software, com **6 agentes** e **Web IDE** integrada.
4
+
5
+ [![Version](https://img.shields.io/badge/version-0.7.0-blue.svg)](docs/CHANGELOG.md)
6
+ [![npm](https://img.shields.io/npm/v/devflow-agents.svg)](https://www.npmjs.com/package/devflow-agents)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
8
+
9
+ ## Screenshots
10
+
11
+ ![DevFlow Hero](docs/images/hero.png)
12
+
13
+ ![Dashboard](docs/images/dashboard.png)
14
+
15
+ ![Editor](docs/images/editor.png)
16
+
17
+ ![Terminal](docs/images/terminal.png)
18
+
19
+ ![Specs Panel](docs/images/specs.png)
20
+
21
+ ---
22
+
23
+ ## 🆕 Novidades v0.7.0
24
+
25
+ ### System Designer Agent (6th agent)
26
+ - System Design Documents (SDDs) com back-of-the-envelope calculations
27
+ - RFCs, capacity planning, trade-off analysis
28
+ - SLA/SLO/SLI definitions e reliability patterns
29
+
30
+ ### npm Package
31
+ - `npx devflow-agents init` para instalacao rapida
32
+ - `devflow update` para atualizacoes
33
+ - Flag `--web` para incluir Web IDE
34
+
35
+ ### Web IDE (Opcional)
36
+ Interface visual completa para gerenciar seu projeto DevFlow:
37
+
38
+ - **Terminal Integrado** - Interface principal via xterm.js + node-pty
39
+ - **Dashboard** - Metricas do projeto, health check, status dos agentes
40
+ - **Specs Panel** - Visualize requirements, design decisions e tasks
41
+ - **File Explorer** - Navegue pelo codigo com preview de markdown/mermaid
42
+ - **Editor Monaco** - Editor profissional com syntax highlighting
43
+ - **Settings** - Configure tema, fonte, terminal
44
+
45
+ ---
46
+
47
+ ## 🚀 Instalacao
48
+
49
+ ### Via npm (Recomendado)
50
+
51
+ ```bash
52
+ # Instala DevFlow no seu projeto (sem instalar nada globalmente)
53
+ npx devflow-agents init
54
+
55
+ # Ou instale globalmente para usar em multiplos projetos
56
+ npm install -g devflow-agents
57
+ devflow init /caminho/para/seu-projeto
58
+
59
+ # Opcoes de instalacao
60
+ devflow init # Agentes + estrutura de docs (padrao)
61
+ devflow init --agents-only # Apenas agentes (minimo)
62
+ devflow init --full # Tudo incluindo .gitignore
63
+ devflow init --web # Inclui Web IDE (opcional)
64
+ devflow init --full --web # Tudo + Web IDE
65
+
66
+ # Atualizar instalacao existente
67
+ devflow update
68
+ ```
69
+
70
+ ### Via bash script (Alternativa)
71
+
72
+ ```bash
73
+ git clone https://github.com/evolve-labs-cloud/devflow.git
74
+ cd devflow
75
+ ./install.sh /caminho/para/seu-projeto
76
+ ```
77
+
78
+ ### Requisitos
79
+
80
+ - **Claude Code CLI** (`npm i -g @anthropic-ai/claude-code`)
81
+ - **Node.js 18+** (para o CLI npm)
82
+ - **Git** (recomendado)
83
+
84
+ ### Dependências por Sistema
85
+
86
+ #### Debian/Ubuntu
87
+ ```bash
88
+ sudo apt-get update
89
+ sudo apt-get install -y build-essential python3 git
90
+ curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
91
+ sudo apt-get install -y nodejs
92
+ npm install -g @anthropic-ai/claude-code
93
+ ```
94
+
95
+ #### Fedora
96
+ ```bash
97
+ sudo dnf groupinstall -y "Development Tools"
98
+ sudo dnf install -y python3 git nodejs npm
99
+ npm install -g @anthropic-ai/claude-code
100
+ ```
101
+
102
+ #### RHEL/CentOS/Rocky
103
+ ```bash
104
+ sudo dnf groupinstall -y "Development Tools"
105
+ sudo dnf install -y python3 git
106
+ curl -fsSL https://rpm.nodesource.com/setup_20.x | sudo bash -
107
+ sudo dnf install -y nodejs
108
+ npm install -g @anthropic-ai/claude-code
109
+ ```
110
+
111
+ #### macOS
112
+ ```bash
113
+ xcode-select --install
114
+ brew install node
115
+ npm install -g @anthropic-ai/claude-code
116
+ ```
117
+
118
+ #### Windows (WSL)
119
+ ```powershell
120
+ # PowerShell como Admin
121
+ wsl --install
122
+ ```
123
+ Depois siga as instruções de Debian/Ubuntu no terminal WSL.
124
+
125
+ ### Web IDE (Opcional)
126
+ ```bash
127
+ cd devflow/web
128
+ npm install
129
+ npm run dev
130
+ # Acesse http://localhost:3000
131
+ ```
132
+
133
+ ---
134
+
135
+ ## 🤖 Os 6 Agentes
136
+
137
+ | # | Agente | Funcao | Uso |
138
+ |---|--------|--------|-----|
139
+ | 1 | **/agents:strategist** | Planejamento & Produto | Requisitos, PRDs, user stories |
140
+ | 2 | **/agents:architect** | Design & Arquitetura | Decisoes tecnicas, ADRs, APIs |
141
+ | 3 | **/agents:system-designer** | System Design & Escala | SDDs, RFCs, capacity planning, SLOs |
142
+ | 4 | **/agents:builder** | Implementacao | Codigo, reviews, refactoring |
143
+ | 5 | **/agents:guardian** | Qualidade & Seguranca | Testes, security, performance |
144
+ | 6 | **/agents:chronicler** | Documentacao & Memoria | CHANGELOG, snapshots, stories |
145
+
146
+ ### Fluxo de Trabalho
147
+
148
+ ```
149
+ strategist → architect → system-designer → builder → guardian → chronicler
150
+ ```
151
+
152
+ Cada agente tem **hard stops** — limites rigidos que impedem de fazer trabalho de outros agentes.
153
+
154
+ ---
155
+
156
+ ## 🖥️ Web IDE Features
157
+
158
+ ### Dashboard
159
+ - Métricas do projeto (specs, decisões, tasks)
160
+ - Health check (Claude CLI, .devflow, git)
161
+ - Status em tempo real
162
+
163
+ ### Specs Panel
164
+ - **Requirements** - User stories com acceptance criteria
165
+ - **Design** - Architecture Decision Records (ADRs)
166
+ - **Tasks** - Tarefas de implementação
167
+
168
+ ### Editor
169
+ - Monaco Editor (VS Code engine)
170
+ - Syntax highlighting para 50+ linguagens
171
+ - Preview de Markdown com Mermaid diagrams
172
+ - Múltiplas tabs com indicador de dirty state
173
+
174
+ ### Terminal
175
+ - Terminal integrado via xterm.js + node-pty
176
+ - WebGL rendering para displays de alta resolução
177
+ - Histórico de comandos
178
+ - Resize responsivo
179
+
180
+ ---
181
+
182
+ ## 📁 Estrutura do Projeto
183
+
184
+ ```
185
+ devflow/
186
+ ├── .claude/ # Comandos e agentes
187
+ │ └── commands/ # Skills dos 6 agentes
188
+ │ └── agents/ # Definições dos agentes
189
+
190
+ ├── .devflow/ # Configuração do projeto
191
+ │ ├── snapshots/ # Histórico do projeto
192
+ │ └── project.yaml # Estado do projeto
193
+
194
+ ├── docs/ # Documentação
195
+ │ ├── decisions/ # ADRs
196
+ │ ├── planning/ # Stories e specs
197
+ │ └── images/ # Screenshots
198
+
199
+ └── web/ # Web IDE
200
+ ├── app/ # Next.js pages
201
+ ├── components/ # React components
202
+ └── lib/ # Utilities
203
+ ```
204
+
205
+ ---
206
+
207
+ ## 📊 Versões
208
+
209
+ | Versão | Features |
210
+ |--------|----------|
211
+ | v0.1.0 | Multi-agent system, Documentation automation |
212
+ | v0.2.0 | Structured metadata, Knowledge graph |
213
+ | v0.3.0 | Hard stops, Mandatory delegation |
214
+ | v0.4.0 | Web IDE completa |
215
+ | v0.5.0 | Terminal como interface principal, WSL support |
216
+ | v0.6.0 | Permission mode configuration |
217
+ | **v0.7.0** | **System Designer agent (6th), npm package, token optimization** |
218
+
219
+ ---
220
+
221
+ ## 📚 Documentação
222
+
223
+ - **[Quick Start](docs/QUICKSTART.md)** - Comece em 5 minutos
224
+ - **[Instalação](docs/INSTALLATION.md)** - Guia detalhado
225
+ - **[Arquitetura](docs/ARCHITECTURE.md)** - Como funciona
226
+ - **[Changelog](docs/CHANGELOG.md)** - Histórico de mudanças
227
+
228
+ ---
229
+
230
+ ## 🛠️ Tech Stack (Web IDE)
231
+
232
+ - **Next.js 15** - Framework React
233
+ - **TypeScript** - Type safety
234
+ - **Tailwind CSS** - Styling
235
+ - **Monaco Editor** - Code editing
236
+ - **xterm.js** - Terminal emulator
237
+ - **node-pty** - PTY para terminal real
238
+ - **Zustand** - State management
239
+ - **Lucide Icons** - Iconografia
240
+
241
+ ---
242
+
243
+ ## 📜 Licença
244
+
245
+ MIT License - veja [LICENSE](LICENSE) para detalhes.
246
+
247
+ ---
248
+
249
+ **DevFlow v0.7.0** - Desenvolvido por [Evolve Labs](https://evolvelabs.cloud)
package/bin/devflow.js ADDED
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env node
2
+
3
+ const { Command } = require('commander');
4
+ const { VERSION } = require('../lib/constants');
5
+ const { initCommand } = require('../lib/init');
6
+ const { updateCommand } = require('../lib/update');
7
+ const { webCommand } = require('../lib/web');
8
+ const { autopilotCommand } = require('../lib/autopilot');
9
+
10
+ const program = new Command();
11
+
12
+ program
13
+ .name('devflow')
14
+ .description('DevFlow - Multi-agent system for software development with Claude Code')
15
+ .version(VERSION, '-v, --version');
16
+
17
+ program
18
+ .command('init')
19
+ .description('Initialize DevFlow in a project directory')
20
+ .argument('[path]', 'target project directory', '.')
21
+ .option('--agents-only', 'install only agents (minimal setup)')
22
+ .option('--full', 'full installation including .gitignore')
23
+ .option('--web', 'include Web IDE source files')
24
+ .option('-f, --force', 'overwrite existing installation without asking')
25
+ .option('--skip-deps', 'skip dependency checking')
26
+ .action(initCommand);
27
+
28
+ program
29
+ .command('update')
30
+ .description('Update an existing DevFlow installation')
31
+ .argument('[path]', 'target project directory', '.')
32
+ .option('-f, --force', 'update without confirmation')
33
+ .action(updateCommand);
34
+
35
+ program
36
+ .command('web')
37
+ .description('Start the DevFlow Web Dashboard')
38
+ .option('-p, --port <port>', 'port number', '3000')
39
+ .option('--project <path>', 'initial project path (defaults to current directory)')
40
+ .option('--dev', 'run in development mode')
41
+ .option('--no-open', 'do not open browser automatically')
42
+ .action(webCommand);
43
+
44
+ program
45
+ .command('autopilot')
46
+ .description('Run autopilot agents on a spec file')
47
+ .argument('<spec-file>', 'path to the spec markdown file')
48
+ .option('--phases <list>', 'comma-separated agent IDs to run', 'strategist,architect,system-designer,builder,guardian,chronicler')
49
+ .option('--project <path>', 'project directory (default: current directory)')
50
+ .option('--no-update', 'do not auto-update tasks in spec file')
51
+ .option('--verbose', 'show detailed output')
52
+ .action(autopilotCommand);
53
+
54
+ program.parse();
@@ -0,0 +1,235 @@
1
+ const { spawn } = require('node:child_process');
2
+ const path = require('node:path');
3
+ const fs = require('node:fs');
4
+ const {
5
+ VALID_AGENTS,
6
+ DEFAULT_PHASES,
7
+ AGENT_TIMEOUTS,
8
+ TASK_TRACKING_AGENTS,
9
+ loadAgentDefinitionSync,
10
+ buildPrompt,
11
+ autoUpdateSpecTasks,
12
+ } = require('./autopilotConstants');
13
+
14
+ // ANSI color helpers
15
+ const c = {
16
+ reset: '\x1b[0m',
17
+ bold: '\x1b[1m',
18
+ dim: '\x1b[2m',
19
+ red: '\x1b[31m',
20
+ green: '\x1b[32m',
21
+ yellow: '\x1b[33m',
22
+ blue: '\x1b[34m',
23
+ magenta: '\x1b[35m',
24
+ cyan: '\x1b[36m',
25
+ white: '\x1b[37m',
26
+ gray: '\x1b[90m',
27
+ };
28
+
29
+ const AGENT_COLORS = {
30
+ strategist: c.blue,
31
+ architect: c.magenta,
32
+ 'system-designer': c.cyan,
33
+ builder: c.yellow,
34
+ guardian: c.green,
35
+ chronicler: c.red,
36
+ };
37
+
38
+ /**
39
+ * Execute a single agent phase via claude --print with streaming output.
40
+ * Returns the captured output.
41
+ */
42
+ function executePhase(agent, fullPrompt, projectPath, timeoutSec) {
43
+ return new Promise((resolve, reject) => {
44
+ let output = '';
45
+ const timeoutMs = timeoutSec * 1000;
46
+
47
+ const child = spawn('claude', ['--print'], {
48
+ cwd: projectPath,
49
+ env: { ...process.env },
50
+ stdio: ['pipe', 'pipe', 'pipe'],
51
+ });
52
+
53
+ // Write the prompt to stdin
54
+ child.stdin.write(fullPrompt);
55
+ child.stdin.end();
56
+
57
+ // Stream stdout in real-time
58
+ child.stdout.on('data', (data) => {
59
+ const text = data.toString();
60
+ output += text;
61
+ process.stdout.write(text);
62
+ });
63
+
64
+ // Stream stderr
65
+ child.stderr.on('data', (data) => {
66
+ process.stderr.write(c.dim + data.toString() + c.reset);
67
+ });
68
+
69
+ // Timeout
70
+ const timer = setTimeout(() => {
71
+ child.kill('SIGTERM');
72
+ reject(new Error(`Timeout: ${agent} exceeded ${timeoutSec}s`));
73
+ }, timeoutMs);
74
+
75
+ child.on('close', (code) => {
76
+ clearTimeout(timer);
77
+ if (code === 0) {
78
+ resolve(output.trim());
79
+ } else {
80
+ reject(new Error(`Agent ${agent} exited with code ${code}`));
81
+ }
82
+ });
83
+
84
+ child.on('error', (err) => {
85
+ clearTimeout(timer);
86
+ if (err.code === 'ENOENT') {
87
+ reject(new Error('Claude CLI not found. Install with: npm i -g @anthropic-ai/claude-code'));
88
+ } else {
89
+ reject(err);
90
+ }
91
+ });
92
+ });
93
+ }
94
+
95
+ /**
96
+ * Format duration in seconds to human-readable string.
97
+ */
98
+ function formatDuration(ms) {
99
+ const secs = Math.floor(ms / 1000);
100
+ if (secs < 60) return `${secs}s`;
101
+ const mins = Math.floor(secs / 60);
102
+ const remainSecs = secs % 60;
103
+ return `${mins}m ${remainSecs}s`;
104
+ }
105
+
106
+ /**
107
+ * devflow autopilot <spec-file> - Run autopilot agents on a spec file
108
+ */
109
+ async function autopilotCommand(specFile, options) {
110
+ // 1. Validate spec file
111
+ const resolvedSpec = path.resolve(specFile);
112
+ if (!fs.existsSync(resolvedSpec)) {
113
+ console.error(`${c.red}Error: Spec file not found: ${resolvedSpec}${c.reset}`);
114
+ process.exit(1);
115
+ }
116
+
117
+ // 2. Read spec content
118
+ const specContent = fs.readFileSync(resolvedSpec, 'utf-8');
119
+ if (!specContent.trim()) {
120
+ console.error(`${c.red}Error: Spec file is empty${c.reset}`);
121
+ process.exit(1);
122
+ }
123
+
124
+ // 3. Determine project path
125
+ const projectPath = path.resolve(options.project || process.cwd());
126
+ if (!fs.existsSync(projectPath)) {
127
+ console.error(`${c.red}Error: Project path not found: ${projectPath}${c.reset}`);
128
+ process.exit(1);
129
+ }
130
+
131
+ // 4. Parse phases
132
+ const phasesStr = options.phases || VALID_AGENTS.join(',');
133
+ const selectedPhases = phasesStr.split(',').map(p => p.trim()).filter(Boolean);
134
+
135
+ // Validate phase names
136
+ for (const phase of selectedPhases) {
137
+ if (!VALID_AGENTS.includes(phase)) {
138
+ console.error(`${c.red}Error: Unknown agent: ${phase}${c.reset}`);
139
+ console.error(`Valid agents: ${VALID_AGENTS.join(', ')}`);
140
+ process.exit(1);
141
+ }
142
+ }
143
+
144
+ // 5. Print header
145
+ const specName = path.basename(resolvedSpec);
146
+ console.log(`\n${c.bold}${c.magenta} DevFlow Autopilot${c.reset}`);
147
+ console.log(`${c.gray}${'─'.repeat(50)}${c.reset}`);
148
+ console.log(`${c.gray} Spec:${c.reset} ${specName}`);
149
+ console.log(`${c.gray} Project:${c.reset} ${path.basename(projectPath)}`);
150
+ console.log(`${c.gray} Phases:${c.reset} ${selectedPhases.length} agents`);
151
+ console.log(`${c.gray}${'─'.repeat(50)}${c.reset}\n`);
152
+
153
+ // 6. Execute phases
154
+ const results = [];
155
+ let previousOutputs = [];
156
+ const totalStart = Date.now();
157
+ let hasFailure = false;
158
+
159
+ for (let i = 0; i < selectedPhases.length; i++) {
160
+ const agentId = selectedPhases[i];
161
+ const phaseInfo = DEFAULT_PHASES.find(p => p.id === agentId);
162
+ const phaseName = phaseInfo ? phaseInfo.name : agentId;
163
+ const color = AGENT_COLORS[agentId] || c.white;
164
+
165
+ console.log(`${c.bold}${color}═══ Phase ${i + 1}/${selectedPhases.length}: ${phaseName} (@${agentId}) ═══${c.reset}\n`);
166
+
167
+ // Load the full agent definition from the project
168
+ const agentDef = loadAgentDefinitionSync(projectPath, agentId);
169
+ if (!agentDef && options.verbose) {
170
+ console.log(`${c.dim} (agent definition not found at ${projectPath}/.claude/commands/agents/${agentId}.md)${c.reset}`);
171
+ }
172
+
173
+ const fullPrompt = buildPrompt(agentId, specContent, previousOutputs, agentDef);
174
+ const timeout = AGENT_TIMEOUTS[agentId] || 600;
175
+ const phaseStart = Date.now();
176
+
177
+ try {
178
+ const output = await executePhase(agentId, fullPrompt, projectPath, timeout);
179
+ const duration = Date.now() - phaseStart;
180
+
181
+ previousOutputs.push(output);
182
+
183
+ // Auto-update tasks
184
+ let tasksCompleted = [];
185
+ if (options.update !== false && TASK_TRACKING_AGENTS.includes(agentId) && output.length > 0) {
186
+ tasksCompleted = await autoUpdateSpecTasks(resolvedSpec, output);
187
+ }
188
+
189
+ results.push({ agent: agentId, name: phaseName, status: 'completed', duration, tasksCompleted });
190
+
191
+ console.log(`\n${c.green}✓ ${phaseName} completed in ${formatDuration(duration)}${c.reset}`);
192
+ if (tasksCompleted.length > 0) {
193
+ console.log(`${c.green} Tasks auto-completed:${c.reset}`);
194
+ for (const task of tasksCompleted) {
195
+ console.log(`${c.green} ✓ ${task}${c.reset}`);
196
+ }
197
+ }
198
+ console.log('');
199
+
200
+ } catch (error) {
201
+ const duration = Date.now() - phaseStart;
202
+ const errorMessage = error.message || 'Unknown error';
203
+
204
+ results.push({ agent: agentId, name: phaseName, status: 'failed', duration, error: errorMessage });
205
+
206
+ console.error(`\n${c.red}✗ ${phaseName} failed after ${formatDuration(duration)}${c.reset}`);
207
+ console.error(`${c.red} Error: ${errorMessage}${c.reset}\n`);
208
+
209
+ hasFailure = true;
210
+ break; // Stop on failure
211
+ }
212
+ }
213
+
214
+ // 7. Print summary
215
+ const totalDuration = Date.now() - totalStart;
216
+ const completedCount = results.filter(r => r.status === 'completed').length;
217
+ const totalTasks = results.reduce((acc, r) => acc + (r.tasksCompleted?.length || 0), 0);
218
+
219
+ console.log(`${c.gray}${'═'.repeat(50)}${c.reset}`);
220
+ console.log(`${c.bold} Summary${c.reset}`);
221
+ console.log(`${c.gray}${'─'.repeat(50)}${c.reset}`);
222
+ console.log(` ${c.gray}Status:${c.reset} ${hasFailure ? `${c.red}Failed${c.reset}` : `${c.green}Completed${c.reset}`}`);
223
+ console.log(` ${c.gray}Phases:${c.reset} ${completedCount}/${selectedPhases.length} completed`);
224
+ console.log(` ${c.gray}Duration:${c.reset} ${formatDuration(totalDuration)}`);
225
+ if (totalTasks > 0) {
226
+ console.log(` ${c.gray}Tasks:${c.reset} ${totalTasks} auto-completed`);
227
+ }
228
+ console.log(`${c.gray}${'═'.repeat(50)}${c.reset}\n`);
229
+
230
+ if (hasFailure) {
231
+ process.exit(1);
232
+ }
233
+ }
234
+
235
+ module.exports = { autopilotCommand };