1use crate::error::{CliError, Result};
4use colored::Colorize;
5use dialoguer::{theme::ColorfulTheme, Confirm, Select};
6use std::fs;
7use std::path::{Path, PathBuf};
8
9pub struct InitCommand {
10 pub name: String,
11 #[allow(dead_code)] pub private: bool,
13 pub interactive: bool,
14}
15
16#[derive(Debug, Clone)]
17enum ProjectType {
18 WebApp,
19 ApiBackend,
20 CliTool,
21 Library,
22}
23
24impl ProjectType {
25 fn as_str(&self) -> &str {
26 match self {
27 ProjectType::WebApp => "Web App (React/Next.js/SvelteKit)",
28 ProjectType::ApiBackend => "API Backend (Rust/Node.js/Python)",
29 ProjectType::CliTool => "CLI Tool (Rust/Go)",
30 ProjectType::Library => "Library/SDK (Rust/TypeScript)",
31 }
32 }
33}
34
35impl InitCommand {
36 pub fn with_interactive(name: String, private: bool, interactive: bool) -> Self {
37 Self {
38 name,
39 private,
40 interactive,
41 }
42 }
43
44 pub async fn execute(&self) -> Result<()> {
45 if self.interactive {
46 self.execute_interactive().await
47 } else {
48 self.execute_simple().await
49 }
50 }
51
52 async fn execute_interactive(&self) -> Result<()> {
53 println!();
54 println!("{}", "🎯 Welcome to Miyabi!".cyan().bold());
55 println!();
56
57 let project_types = [
59 ProjectType::WebApp,
60 ProjectType::ApiBackend,
61 ProjectType::CliTool,
62 ProjectType::Library,
63 ];
64
65 let project_type_selection = Select::with_theme(&ColorfulTheme::default())
66 .with_prompt("What are you building?")
67 .items(
68 project_types
69 .iter()
70 .map(|t| t.as_str())
71 .collect::<Vec<_>>(),
72 )
73 .default(0)
74 .interact()
75 .map_err(|e| CliError::InvalidProjectName(e.to_string()))?;
76
77 let project_type = &project_types[project_type_selection];
78
79 println!();
80 println!(
81 " {} {}",
82 "✨".green(),
83 format!("Great choice! Building: {}", project_type.as_str()).bold()
84 );
85 println!();
86
87 let connect_github = Confirm::with_theme(&ColorfulTheme::default())
89 .with_prompt("Connect to GitHub?")
90 .default(true)
91 .interact()
92 .map_err(|e| CliError::InvalidProjectName(e.to_string()))?;
93
94 println!();
95 if connect_github {
96 println!(" {} Will set up GitHub integration", "🔗".green());
97 } else {
98 println!(" {} Skipping GitHub (you can set it up later)", "⏭️".yellow());
99 }
100 println!();
101
102 println!("{}", "🤖 Setting up AI Agents...".cyan().bold());
104 println!(" {} CoordinatorAgent (Task planning)", "✅".green());
105 println!(" {} CodeGenAgent (Code generation)", "✅".green());
106 println!(" {} ReviewAgent (Quality checks)", "✅".green());
107 println!();
108
109 self.execute_simple().await?;
110
111 println!();
113 println!("{}", "🎉 You're all set!".green().bold());
114 println!();
115 println!("Your first AI-powered task:");
116 println!(" {}", "miyabi work-on \"Setup project structure\"".yellow());
117 println!();
118 println!("Or try the traditional way:");
119 println!(" {}", "miyabi agent run coordinator --issue 1".cyan());
120
121 Ok(())
122 }
123
124 async fn execute_simple(&self) -> Result<()> {
125 if !self.interactive {
126 println!("{}", "🚀 Initializing new Miyabi project...".cyan().bold());
127 }
128
129 self.validate_project_name()?;
131
132 let project_dir = self.create_project_directory()?;
134
135 self.init_git_repository(&project_dir)?;
137
138 self.create_project_structure(&project_dir)?;
140
141 self.create_config_files(&project_dir)?;
143
144 println!();
145 println!("{}", "✅ Project initialized successfully!".green().bold());
146 println!();
147 println!("{}", "📚 Next steps:".cyan().bold());
148 println!();
149 println!(" {} Enter project directory:", "1.".yellow().bold());
150 println!(" cd {}", self.name);
151 println!();
152 println!(" {} Set up GitHub token:", "2.".yellow().bold());
153 println!(" Visit: https://github.com/settings/tokens/new");
154 println!(" Scopes: repo, workflow");
155 println!(" export GITHUB_TOKEN=ghp_xxx");
156 println!();
157 println!(" {} Check installation:", "3.".yellow().bold());
158 println!(" miyabi status");
159 println!();
160 println!(" {} Create your first issue on GitHub, then:", "4.".yellow().bold());
161 println!(" miyabi agent run coordinator --issue 1");
162 println!();
163 println!("{}", "📖 Documentation:".cyan().bold());
164 println!(" • Quick Start: .claude/QUICK_START.md");
165 println!(" • Full Guide: CLAUDE.md");
166 println!(" • Agent Specs: .claude/agents/README.md");
167 println!();
168 println!("{}", "🔗 Resources:".cyan().bold());
169 println!(" • crates.io: https://crates.io/crates/miyabi-cli");
170 println!(" • GitHub: https://github.com/ShunsukeHayashi/Miyabi");
171 println!(" • Docs: https://docs.rs/miyabi-agents");
172
173 Ok(())
174 }
175
176 fn validate_project_name(&self) -> Result<()> {
177 if self.name.is_empty() {
179 return Err(CliError::InvalidProjectName(
180 "Project name cannot be empty".to_string(),
181 ));
182 }
183
184 if !self
186 .name
187 .chars()
188 .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
189 {
190 return Err(CliError::InvalidProjectName(
191 "Project name can only contain alphanumeric characters, hyphens, and underscores"
192 .to_string(),
193 ));
194 }
195
196 Ok(())
197 }
198
199 fn create_project_directory(&self) -> Result<PathBuf> {
200 let project_dir = PathBuf::from(&self.name);
201
202 if project_dir.exists() {
204 return Err(CliError::ProjectExists(self.name.clone()));
205 }
206
207 fs::create_dir(&project_dir)?;
209 println!(" Created directory: {}", project_dir.display());
210
211 Ok(project_dir)
212 }
213
214 fn init_git_repository(&self, project_dir: &Path) -> Result<()> {
215 use std::process::Command;
216
217 let output = Command::new("git")
219 .args(["init"])
220 .current_dir(project_dir)
221 .output()?;
222
223 if !output.status.success() {
224 return Err(CliError::Io(std::io::Error::other(
225 "Failed to initialize git repository",
226 )));
227 }
228
229 println!(" Initialized git repository");
230 Ok(())
231 }
232
233 fn create_project_structure(&self, project_dir: &Path) -> Result<()> {
234 let dirs = vec![
236 ".github/workflows",
237 ".claude/agents/specs/coding",
238 ".claude/agents/specs/business",
239 ".claude/agents/prompts/coding",
240 ".claude/agents/prompts/business",
241 ".claude/commands",
242 ".claude/prompts",
243 ".claude/templates",
244 "docs",
245 "scripts",
246 "logs",
247 "reports",
248 ];
249
250 for dir in dirs {
251 let dir_path = project_dir.join(dir);
252 fs::create_dir_all(&dir_path)?;
253 }
254
255 self.create_claude_md(project_dir)?;
257
258 self.create_claude_files(project_dir)?;
260
261 println!(" Created project structure");
262 Ok(())
263 }
264
265 fn create_claude_md(&self, project_dir: &Path) -> Result<()> {
266 let claude_md = format!(
267 r#"# Claude Code プロジェクト設定
268
269このファイルは、Claude Codeが自動的に参照するプロジェクトコンテキストファイルです。
270
271## プロジェクト概要
272
273**{}** - Miyabi自律型開発プロジェクト
274
275## アーキテクチャ
276
277### コアコンポーネント
278
2791. **Agent System** - 自律実行Agent(Miyabi Framework)
2802. **GitHub OS Integration** - GitHubをOSとして活用
2813. **Label System** - 53ラベル体系による状態管理
282
283### ディレクトリ構造
284
285```
286{}/
287├── .claude/ # Claude Code設定
288│ ├── agents/ # Agent仕様・プロンプト
289│ ├── commands/ # カスタムコマンド
290│ └── prompts/ # 実行プロンプト
291├── .github/ # GitHub設定
292│ └── workflows/ # GitHub Actions
293├── docs/ # ドキュメント
294├── scripts/ # 自動化スクリプト
295├── logs/ # ログファイル
296└── reports/ # レポート出力
297```
298
299## 開発ガイドライン
300
301### コミット規約
302- Conventional Commits準拠
303- `feat:`, `fix:`, `chore:`, `docs:`, etc.
304
305### セキュリティ
306- トークンは環境変数
307- `.miyabi.yml`は`.gitignore`に追加済み
308
309## 環境変数
310
311```bash
312GITHUB_TOKEN=ghp_xxx # GitHubアクセストークン
313ANTHROPIC_API_KEY=sk-xxx # Anthropic APIキー(Agent実行時)
314```
315
316## 実行例
317
318```bash
319# ステータス確認
320miyabi status
321
322# Agent実行
323miyabi agent coordinator --issue 1
324
325# テスト実行
326cargo test --all
327
328# Linter実行
329cargo clippy --all-targets
330```
331
332---
333
334**このファイルはClaude Codeが自動参照します。プロジェクトのコンテキストとして常に最新に保ってください。**
335"#,
336 self.name, self.name
337 );
338
339 fs::write(project_dir.join("CLAUDE.md"), claude_md)?;
340 Ok(())
341 }
342
343 fn create_claude_files(&self, project_dir: &Path) -> Result<()> {
344 let claude_readme = r#"# .claude Directory
346
347Claude Code設定ディレクトリ - プロジェクト固有の設定とプロンプト
348
349## 構造
350
351- `agents/` - Agent仕様とプロンプト
352 - `specs/coding/` - コーディング系Agent仕様
353 - `specs/business/` - ビジネス系Agent仕様
354 - `prompts/coding/` - 実行プロンプト
355- `commands/` - カスタムスラッシュコマンド
356- `prompts/` - 汎用プロンプト
357- `templates/` - テンプレートファイル
358
359## カスタムコマンド
360
361`.claude/commands/` 配下に `*.md` ファイルを作成することで、
362カスタムスラッシュコマンドを定義できます。
363
364例: `.claude/commands/test.md` → `/test` コマンド
365
366## Agent仕様
367
368Agent仕様ファイル(`.claude/agents/specs/`)で、各Agentの役割・権限・エスカレーション条件を定義します。
369"#;
370 fs::write(project_dir.join(".claude/README.md"), claude_readme)?;
371
372 let quick_start = format!(
374 r#"# {} - Quick Start Guide
375
376## 🚀 3分で始めるMiyabi
377
378### 1. 環境変数設定
379
380```bash
381export GITHUB_TOKEN=ghp_xxx
382export ANTHROPIC_API_KEY=sk-xxx
383```
384
385### 2. ステータス確認
386
387```bash
388miyabi status
389```
390
391### 3. Issue作成
392
393GitHubでIssueを作成し、以下のラベルを付与:
394- `type:feature` または `type:bug`
395- `priority:P1-High`
396
397### 4. Agent実行
398
399```bash
400miyabi agent coordinator --issue 1
401```
402
403## 📚 詳細ドキュメント
404
405- [CLAUDE.md](../CLAUDE.md) - プロジェクトコンテキスト
406- [.claude/README.md](./README.md) - .claudeディレクトリ説明
407
408---
409
410**Miyabi** - Beauty in Autonomous Development 🌸
411"#,
412 self.name
413 );
414 fs::write(project_dir.join(".claude/QUICK_START.md"), quick_start)?;
415
416 let agents_readme = r#"# Miyabi Agents
418
419このディレクトリには、Miyabiプロジェクトで使用するAgent仕様とプロンプトを配置します。
420
421## 📁 ディレクトリ構造
422
423```
424agents/
425├── specs/ # Agent仕様定義
426│ ├── coding/ # コーディング系Agent(7種類)
427│ └── business/ # ビジネス系Agent(14種類)
428└── prompts/ # 実行プロンプト
429 ├── coding/ # コーディング系Agentプロンプト
430 └── business/ # ビジネス系Agentプロンプト
431```
432
433## 🤖 Coding Agents(7種類)
434
4351. **CoordinatorAgent** - タスク統括・DAG分解
4362. **CodeGenAgent** - AI駆動コード生成
4373. **ReviewAgent** - コード品質レビュー
4384. **IssueAgent** - Issue分析・ラベリング
4395. **PRAgent** - Pull Request自動作成
4406. **DeploymentAgent** - CI/CDデプロイ自動化
4417. **RefresherAgent** - Issue状態監視・更新
442
443## 💼 Business Agents(14種類)
444
445### 戦略・企画系(6種類)
446- AIEntrepreneurAgent, ProductConceptAgent, ProductDesignAgent
447- FunnelDesignAgent, PersonaAgent, SelfAnalysisAgent
448
449### マーケティング系(5種類)
450- MarketResearchAgent, MarketingAgent, ContentCreationAgent
451- SNSStrategyAgent, YouTubeAgent
452
453### 営業・顧客管理系(3種類)
454- SalesAgent, CRMAgent, AnalyticsAgent
455
456## 📝 Agent仕様の書き方
457
458詳細は各ディレクトリのREADME.mdを参照してください:
459- [specs/coding/README.md](specs/coding/README.md)
460- [specs/business/README.md](specs/business/README.md)
461
462## 🚀 Agent実行方法
463
464```bash
465# CoordinatorAgentでIssue処理
466miyabi agent run coordinator --issue 123
467
468# 複数Issue並列処理
469miyabi agent run coordinator --issues 123,124,125 --concurrency 3
470```
471
472## 🔗 参考リンク
473
474- [Miyabi Agent SDK](https://docs.rs/miyabi-agents)
475- [CLAUDE.md](../../CLAUDE.md) - プロジェクトコンテキスト
476"#;
477 fs::write(project_dir.join(".claude/agents/README.md"), agents_readme)?;
478
479 let coding_specs_readme = r#"# Coding Agent 仕様
481
482このディレクトリには、コーディング系Agent(7種類)の仕様を配置します。
483
484## Agent仕様ファイルのフォーマット
485
486各Agentの仕様は以下の構造で記述します:
487
488```markdown
489# [Agent名] 仕様
490
491## 概要
492Agentの役割と責任範囲
493
494## 入力
495- 受け取るTask/Issueの形式
496- 必須パラメータ
497
498## 処理フロー
4991. ステップ1
5002. ステップ2
5013. ...
502
503## 出力
504- 生成する成果物
505- 更新するIssue/PR
506
507## エスカレーション条件
508- 上位Agentへのエスカレーション基準
509- エラーハンドリング
510
511## 実行例
512\`\`\`bash
513miyabi agent run [agent-type] --issue 123
514\`\`\`
515```
516
517## 📋 テンプレート
518
519新しいAgent仕様を作成する場合、以下のテンプレートを使用してください:
520
521```bash
522cp example-agent-spec.md my-custom-agent.md
523```
524
525## 🔗 参考
526
527既存のAgent仕様は以下を参照:
528- Miyabiプロジェクトの `.claude/agents/specs/coding/` ディレクトリ
529- [Agent Operations Manual](https://github.com/ShunsukeHayashi/Miyabi/blob/main/docs/AGENT_OPERATIONS_MANUAL.md)
530"#;
531 fs::write(
532 project_dir.join(".claude/agents/specs/coding/README.md"),
533 coding_specs_readme,
534 )?;
535
536 let business_specs_readme = r#"# Business Agent 仕様
538
539このディレクトリには、ビジネス系Agent(14種類)の仕様を配置します。
540
541## Agent仕様ファイルのフォーマット
542
543各Agentの仕様は以下の構造で記述します:
544
545```markdown
546# [Agent名] 仕様
547
548## 概要
549Agentの役割とビジネス目標
550
551## 入力
552- ユーザー要求(市場情報、目標KPI等)
553- 必須パラメータ
554
555## 実行フェーズ
5561. Phase 1: データ収集
5572. Phase 2: 分析
5583. Phase 3: 戦略立案
5594. ...
560
561## 出力
562- 生成するビジネスドキュメント
563- レポート形式
564
565## 品質基準
566- 検証項目
567- スコアリング基準(100点満点)
568
569## 実行例
570\`\`\`bash
571miyabi agent run ai-entrepreneur --output business-plan.md
572\`\`\`
573```
574
575## 📊 Business Agent一覧
576
577### 戦略・企画系
578- **AIEntrepreneurAgent** - 包括的ビジネスプラン作成
579- **ProductConceptAgent** - 製品コンセプト設計
580- **ProductDesignAgent** - サービス詳細設計
581- **FunnelDesignAgent** - 導線設計
582- **PersonaAgent** - ターゲット顧客ペルソナ
583- **SelfAnalysisAgent** - 自己分析
584
585### マーケティング系
586- **MarketResearchAgent** - 市場調査
587- **MarketingAgent** - マーケティング戦略
588- **ContentCreationAgent** - コンテンツ制作
589- **SNSStrategyAgent** - SNS戦略
590- **YouTubeAgent** - YouTube運用最適化
591
592### 営業・顧客管理系
593- **SalesAgent** - セールスプロセス最適化
594- **CRMAgent** - 顧客関係管理
595- **AnalyticsAgent** - データ分析・PDCA
596
597## 🔗 参考
598
599- [SaaS Business Model Guide](https://github.com/ShunsukeHayashi/Miyabi/blob/main/docs/SAAS_BUSINESS_MODEL.md)
600- [Business Agents User Guide](https://github.com/ShunsukeHayashi/Miyabi/blob/main/docs/BUSINESS_AGENTS_USER_GUIDE.md)
601"#;
602 fs::write(
603 project_dir.join(".claude/agents/specs/business/README.md"),
604 business_specs_readme,
605 )?;
606
607 let example_prompt = r#"# Example Agent Prompt
609
610このファイルは、Agentプロンプトのサンプルです。
611
612## プロンプト構造
613
614```markdown
615# [Task名]
616
617## Context
618プロジェクトのコンテキスト情報
619
620## Objective
621このAgentが達成すべき目標
622
623## Inputs
624- Issue URL: https://github.com/user/repo/issues/123
625- Task ID: TASK-456
626- Dependencies: TASK-123, TASK-124
627
628## Instructions
6291. ステップ1を実行
6302. ステップ2を実行
6313. ...
632
633## Output Format
634期待される出力形式(JSON, Markdown, Code等)
635
636## Success Criteria
637- 基準1
638- 基準2
639```
640
641## 使用方法
642
643Worktree内でClaude Codeセッションを起動する際、このプロンプトが自動的に読み込まれます。
644
645```bash
646cd .worktrees/issue-123
647# Claude Codeがこのプロンプトを参照して実行
648```
649
650## カスタマイズ
651
652プロジェクト固有のプロンプトを作成する場合:
653
6541. このファイルをコピー
6552. 内容をカスタマイズ
6563. `.claude/agents/prompts/coding/` に配置
657
658## 🔗 参考
659
660実際のプロンプト例は、Miyabiプロジェクトの `.claude/agents/prompts/coding/` を参照してください。
661"#;
662 fs::write(
663 project_dir.join(".claude/agents/prompts/coding/example-prompt.md"),
664 example_prompt,
665 )?;
666
667 let codegen_example = r#"# CodeGenAgent Specification
669
670## 概要
671CodeGenAgentは、AI駆動のコード生成を担当するSpecialist Agentです。
672Claude Sonnet 4を使用して、型安全で高品質なRustコードを生成します。
673
674## 入力
675- **Task**: CoordinatorAgentから受け取ったTask
676 - Task ID
677 - 依存関係(Dependencies)
678 - 生成すべきコードの仕様
679- **Issue Context**: 元のIssue情報
680
681## 処理フロー
682
683### 1. 要件分析
684- Taskの内容を解析
685- 必要なモジュール・トレイト・構造体を特定
686- 既存コードとの整合性確認
687
688### 2. コード生成
689```rust
690// 例: 新しいAgent構造体の生成
691pub struct NewAgent {
692 config: AgentConfig,
693}
694
695#[async_trait]
696impl BaseAgent for NewAgent {
697 async fn execute(&self, task: Task) -> Result<AgentResult> {
698 // Implementation
699 Ok(AgentResult::success(data))
700 }
701}
702```
703
704### 3. テスト生成
705```rust
706#[cfg(test)]
707mod tests {
708 use super::*;
709
710 #[tokio::test]
711 async fn test_new_agent() {
712 let agent = NewAgent::new(config);
713 let result = agent.execute(task).await.unwrap();
714 assert_eq!(result.status, ResultStatus::Success);
715 }
716}
717```
718
719### 4. ドキュメント生成
720- Rustdocコメント(`///`)の追加
721- 使用例の記述
722- パラメータ・戻り値の説明
723
724## 出力
725- **生成コード**: Rust source files
726- **テスト**: `#[cfg(test)]` mod
727- **ドキュメント**: Rustdoc comments
728- **Commit**: Conventional Commits形式
729
730## エスカレーション条件
731- 既存コードとの大規模なコンフリクト
732- セキュリティ上の懸念(unsafe使用等)
733- 外部依存の追加が必要
734
735## 品質基準
736- ✅ Clippy警告0件
737- ✅ テストカバレッジ80%以上
738- ✅ すべてのpublic APIにRustdoc
739- ✅ エラーハンドリング完備
740
741## 実行例
742```bash
743miyabi agent run codegen --issue 123
744```
745
746または簡易コマンド:
747```bash
748miyabi work-on 123
749```
750
751---
752
753**このファイルはClaude Codeが参照する実際のAgent仕様です。**
754**プロジェクト固有の要件に合わせてカスタマイズしてください。**
755"#;
756 fs::write(
757 project_dir.join(".claude/agents/specs/coding/codegen-agent-example.md"),
758 codegen_example,
759 )?;
760
761 let issue_workflow_example = format!(
763 r#"# Issue Creation Workflow Example
764
765このファイルは、{}プロジェクトでの標準的なIssue作成フローです。
766
767## ステップ1: Issue作成
768
769### GitHub Web UIで作成
7701. リポジトリの"Issues"タブをクリック
7712. "New issue"をクリック
7723. Issueテンプレートを使用(推奨)
773
774### GitHub CLIで作成(推奨)
775```bash
776gh issue create \
777 --title "✨ Add user authentication" \
778 --body "$(cat <<'EOF'
779## 概要
780ユーザー認証機能を追加する
781
782## 要件
783- [ ] JWT トークン認証
784- [ ] ログイン/ログアウトエンドポイント
785- [ ] トークンリフレッシュ機能
786
787## 期待される成果
788- 認証付きAPIエンドポイント
789- テストカバレッジ90%以上
790- セキュリティ監査パス
791EOF
792)" \
793 --label "type:feature,priority:P1-High,state:pending"
794```
795
796## ステップ2: Agent実行
797
798### 方法1: 新しいwork-onコマンド(推奨)
799```bash
800# Issue番号で実行
801miyabi work-on 1
802
803# または作業説明で実行(Issue作成を提案)
804miyabi work-on "Add user authentication"
805```
806
807### 方法2: 従来のagentコマンド
808```bash
809miyabi agent run coordinator --issue 1
810```
811
812### 方法3: 並列実行
813```bash
814miyabi parallel --issues 1,2,3 --concurrency 2
815```
816
817## ステップ3: 進捗確認
818
819```bash
820# プロジェクトステータス確認
821miyabi status
822
823# Issue状態確認
824gh issue view 1
825
826# Worktree確認
827git worktree list
828
829# ログ確認
830tail -f logs/miyabi-$(date +%Y%m%d).log
831```
832
833## ステップ4: レビュー
834
835Agentが自動的に:
8361. コード生成
8372. テスト作成
8383. Linter実行
8394. PR作成
840
841あなたがすべきこと:
8421. PRレビュー
8432. 追加修正(必要なら)
8443. マージ
845
846## 実際の例
847
848### 成功例: Issue #42 "Setup CI/CD pipeline"
849
850```bash
851$ miyabi work-on 42
852
853🚀 Let's work on it!
854 📋 Issue #42
855
856🤖 CoordinatorAgent starting...
857 ✅ Analyzed issue
858 ✅ Created 3 tasks
859 ✅ Assigned CodeGenAgent, ReviewAgent, DeploymentAgent
860
861⏱️ Estimated time: 15 minutes
862🌳 Created worktree: .worktrees/issue-42
863
864[15 minutes later]
865
866✅ All tasks completed!
867📊 Quality score: 95/100
868🔗 PR created: #43
869```
870
871## トラブルシューティング
872
873### Agentがスタックした場合
874```bash
875# ログ確認
876grep -i "error" logs/miyabi-*.log
877
878# Worktreeクリーンアップ
879git worktree prune
880
881# 再実行
882miyabi work-on 42
883```
884
885### より詳しいヘルプ
886```bash
887# トラブルシューティングガイド
888cat docs/TROUBLESHOOTING.md
889
890# Agent仕様確認
891cat .claude/agents/README.md
892```
893
894---
895
896**{}プロジェクトの標準ワークフロー**
897**Miyabi - Beauty in Autonomous Development 🌸**
898"#,
899 self.name, self.name
900 );
901 fs::write(
902 project_dir.join(".claude/agents/issue-workflow-example.md"),
903 issue_workflow_example,
904 )?;
905
906 Ok(())
907 }
908
909 fn create_config_files(&self, project_dir: &Path) -> Result<()> {
910 let miyabi_config = format!(
912 r#"# Miyabi Configuration
913project_name: {}
914version: "0.1.0"
915
916# GitHub settings (use environment variables for sensitive data)
917# github_token: ${{{{ GITHUB_TOKEN }}}}
918
919# Agent settings
920agents:
921 enabled: true
922 use_worktree: true
923 worktree_base_path: ".worktrees"
924
925# Logging
926logging:
927 level: info
928 directory: "./logs"
929
930# Reporting
931reporting:
932 directory: "./reports"
933"#,
934 self.name
935 );
936
937 fs::write(project_dir.join(".miyabi.yml"), miyabi_config)?;
938
939 let gitignore = r#"# Miyabi
941.miyabi.yml
942.worktrees/
943logs/
944reports/
945*.log
946
947# Environment
948.env
949.env.local
950
951# Dependencies
952node_modules/
953target/
954
955# IDE
956.vscode/
957.idea/
958*.swp
959*.swo
960"#;
961
962 fs::write(project_dir.join(".gitignore"), gitignore)?;
963
964 let readme = format!(
966 r#"# {}
967
968Miyabi autonomous development project.
969
970## Setup
971
9721. Set GitHub token:
973 ```bash
974 export GITHUB_TOKEN=ghp_xxx
975 ```
976
9772. Check status:
978 ```bash
979 miyabi status
980 ```
981
9823. Run agent:
983 ```bash
984 miyabi agent coordinator --issue 1
985 ```
986
987## Documentation
988
989- See `docs/` directory for detailed documentation
990- See `.claude/agents/specs/` for agent specifications
991"#,
992 self.name
993 );
994
995 fs::write(project_dir.join("README.md"), readme)?;
996
997 let getting_started = format!(
999 r#"# Getting Started with {}
1000
1001Miyabiプロジェクトへようこそ!このガイドでは、ゼロからMiyabiを使い始めるまでの手順を詳しく解説します。
1002
1003## 📋 前提条件
1004
1005### 必須
1006
1007- **Rust**: 1.75.0以上
1008 ```bash
1009 rustc --version # 確認
1010 ```
1011
1012- **Git**: バージョン管理用
1013 ```bash
1014 git --version
1015 ```
1016
1017- **GitHubアカウント**: Issue/PR管理用
1018
1019### 推奨
1020
1021- **GitHub CLI (`gh`)**: GitHub操作を簡単に
1022 ```bash
1023 brew install gh # macOS
1024 gh --version
1025 ```
1026
1027## 🚀 セットアップ手順
1028
1029### Step 1: 環境変数の設定
1030
1031#### 1.1 GitHub Personal Access Token取得
1032
10331. https://github.com/settings/tokens/new にアクセス
10342. Token名を入力(例: "Miyabi Local Dev")
10353. 以下のスコープを選択:
1036 - ✅ `repo` (Full control of private repositories)
1037 - ✅ `workflow` (Update GitHub Action workflows)
10384. "Generate token"をクリック
10395. トークンをコピー(**一度しか表示されません!**)
1040
1041#### 1.2 環境変数をシェルプロファイルに追加
1042
1043**Bash (.bashrc / .bash_profile):**
1044```bash
1045echo 'export GITHUB_TOKEN=ghp_xxxxx' >> ~/.bashrc
1046echo 'export ANTHROPIC_API_KEY=sk-ant-xxxxx' >> ~/.bashrc
1047source ~/.bashrc
1048```
1049
1050**Zsh (.zshrc):**
1051```bash
1052echo 'export GITHUB_TOKEN=ghp_xxxxx' >> ~/.zshrc
1053echo 'export ANTHROPIC_API_KEY=sk-ant-xxxxx' >> ~/.zshrc
1054source ~/.zshrc
1055```
1056
1057#### 1.3 環境変数確認
1058```bash
1059echo $GITHUB_TOKEN
1060echo $ANTHROPIC_API_KEY
1061```
1062
1063### Step 2: GitHubリポジトリ作成
1064
1065#### 2.1 GitHub CLI使用(推奨)
1066```bash
1067cd {}
1068gh repo create {} --private --source=. --remote=origin
1069```
1070
1071#### 2.2 手動作成
10721. https://github.com/new にアクセス
10732. Repository nameに `{}` を入力
10743. "Private"を選択
10754. "Create repository"をクリック
10765. ローカルリポジトリと接続:
1077 ```bash
1078 git remote add origin https://github.com/YOUR_USERNAME/{}.git
1079 git branch -M main
1080 git add .
1081 git commit -m "feat: initial commit 🚀"
1082 git push -u origin main
1083 ```
1084
1085### Step 3: Label体系のセットアップ
1086
1087Miyabiは53ラベル体系で自動化を制御します。
1088
1089#### 3.1 自動セットアップ(将来実装予定)
1090```bash
1091miyabi setup labels
1092```
1093
1094#### 3.2 手動セットアップ
1095GitHubリポジトリの設定から、以下のラベルを作成:
1096
1097**STATE(8個)**:
1098- `📥 state:pending` (Gray)
1099- `🔍 state:analyzing` (Blue)
1100- `🏗️ state:implementing` (Yellow)
1101- `👀 state:reviewing` (Orange)
1102- `✅ state:done` (Green)
1103- `❌ state:blocked` (Red)
1104- `⏸️ state:on-hold` (Purple)
1105- `🔄 state:reopened` (Pink)
1106
1107(残り45ラベルは`.github/labels.yml`を参照)
1108
1109### Step 4: 最初のIssue作成
1110
1111#### 4.1 GitHub Web UIで作成
11121. リポジトリの"Issues"タブをクリック
11132. "New issue"をクリック
11143. Title: "✨ Setup project configuration"
11154. Body:
1116 ```markdown
1117 ## 概要
1118 プロジェクトの初期設定を行う
1119
1120 ## タスク
1121 - [ ] .miyabi.yml の設定確認
1122 - [ ] GitHub Actionsの設定
1123 - [ ] 開発環境の準備
1124
1125 ## 期待される成果
1126 - プロジェクトが動作可能な状態
1127 ```
11285. Labels:
1129 - `✨ type:feature`
1130 - `⚠️ priority:P1-High`
1131 - `📥 state:pending`
11326. "Submit new issue"をクリック
1133
1134#### 4.2 GitHub CLIで作成
1135```bash
1136gh issue create --title "✨ Setup project configuration" \
1137 --body "初期設定タスク" \
1138 --label "type:feature,priority:P1-High,state:pending"
1139```
1140
1141### Step 5: Agent実行
1142
1143#### 5.1 ステータス確認
1144```bash
1145miyabi status
1146```
1147
1148出力例:
1149```
1150📊 Project Status
1151
1152Miyabi Installation:
1153 ✅ Miyabi is installed
1154 ✓ .claude/agents
1155 ✓ .github/workflows
1156
1157Environment:
1158 ✅ GITHUB_TOKEN is set
1159 ✅ DEVICE_IDENTIFIER: YourMac.local
1160
1161Git Repository:
1162 ✅ Git repository detected
1163 Branch: main
1164 Remotes: origin
1165```
1166
1167#### 5.2 CoordinatorAgent実行
1168```bash
1169miyabi agent run coordinator --issue 1
1170```
1171
1172Agentは以下を実行します:
11731. Issue分析
11742. Task分解(DAG構築)
11753. Worktree作成
11764. Specialist Agent割り当て
11775. 並列実行
11786. 結果統合
1179
1180## 🎯 よくある使い方
1181
1182### Issue処理の基本フロー
1183```bash
1184# 1. Issue作成(GitHub UI または gh CLI)
1185gh issue create --title "新機能実装" --label "type:feature"
1186
1187# 2. Agent実行
1188miyabi agent run coordinator --issue 2
1189
1190# 3. ステータス確認
1191miyabi status
1192
1193# 4. ログ確認
1194cat logs/miyabi-*.log
1195```
1196
1197### 複数Issue並列処理
1198```bash
1199miyabi agent run coordinator --issues 1,2,3 --concurrency 2
1200```
1201
1202### Worktree確認
1203```bash
1204git worktree list
1205```
1206
1207## 📚 次に読むべきドキュメント
1208
12091. **CLAUDE.md** - プロジェクトコンテキスト(Claude Codeが自動参照)
12102. **.claude/QUICK_START.md** - 3分で始めるクイックガイド
12113. **.claude/agents/README.md** - Agent一覧と使い方
12124. **docs/TROUBLESHOOTING.md** - トラブルシューティング
1213
1214## 🆘 困ったときは
1215
1216### エラーが出た場合
12171. `docs/TROUBLESHOOTING.md` を確認
12182. `miyabi status` で環境確認
12193. GitHub Issuesで質問: https://github.com/ShunsukeHayashi/Miyabi/issues
1220
1221### ログ確認
1222```bash
1223# 最新のログファイル
1224tail -f logs/miyabi-$(date +%Y%m%d).log
1225
1226# エラーログのみ抽出
1227grep -i error logs/miyabi-*.log
1228```
1229
1230## 🎉 次のステップ
1231
1232おめでとうございます!Miyabiのセットアップが完了しました。
1233
1234次は:
12351. **独自のAgent仕様作成**: `.claude/agents/specs/coding/` にカスタムAgent追加
12362. **Label体系のカスタマイズ**: プロジェクトに合わせたLabel追加
12373. **GitHub Actionsの設定**: `.github/workflows/` でCI/CD自動化
12384. **Worktree並列実行**: 複数Issueの同時処理
1239
1240---
1241
1242**Miyabi** - Beauty in Autonomous Development 🌸
1243"#,
1244 self.name, self.name, self.name, self.name, self.name
1245 );
1246 fs::write(project_dir.join("docs/GETTING_STARTED.md"), getting_started)?;
1247
1248 let troubleshooting = r#"# Troubleshooting Guide
1250
1251Miyabi使用中に発生する可能性のある問題と解決策をまとめています。
1252
1253## 🔧 環境関連
1254
1255### GITHUB_TOKENが設定されていない
1256
1257**症状**:
1258```
1259Error: GITHUB_TOKEN not set
1260```
1261
1262**解決策**:
12631. トークンを取得: https://github.com/settings/tokens/new
12642. 環境変数を設定:
1265 ```bash
1266 export GITHUB_TOKEN=ghp_xxxxx
1267 ```
12683. シェルプロファイルに追加(永続化):
1269 ```bash
1270 echo 'export GITHUB_TOKEN=ghp_xxxxx' >> ~/.zshrc
1271 source ~/.zshrc
1272 ```
1273
1274### ANTHROPIC_API_KEYが設定されていない
1275
1276**症状**:
1277```
1278Error: ANTHROPIC_API_KEY not set
1279```
1280
1281**解決策**:
12821. Anthropic Consoleでキー取得: https://console.anthropic.com/
12832. 環境変数を設定:
1284 ```bash
1285 export ANTHROPIC_API_KEY=sk-ant-xxxxx
1286 ```
1287
1288## 🐛 Git関連
1289
1290### Git repositoryが見つからない
1291
1292**症状**:
1293```
1294Error: Not a git repository
1295```
1296
1297**解決策**:
1298```bash
1299cd your-project
1300git init
1301```
1302
1303### Worktreeが残ったまま
1304
1305**症状**:
1306```
1307Error: Worktree already exists: .worktrees/issue-123
1308```
1309
1310**解決策**:
1311```bash
1312# Worktree一覧確認
1313git worktree list
1314
1315# 不要なWorktreeを削除
1316git worktree remove .worktrees/issue-123
1317
1318# すべてのstale Worktreeをクリーンアップ
1319git worktree prune
1320```
1321
1322### マージコンフリクト
1323
1324**症状**:
1325```
1326CONFLICT (content): Merge conflict in src/main.rs
1327```
1328
1329**解決策**:
1330```bash
1331# コンフリクトファイルを確認
1332git status
1333
1334# 手動でコンフリクトを解決
1335# エディタでファイルを開き、<<<<<<<, =======, >>>>>>> マーカーを削除
1336
1337# 解決後
1338git add src/main.rs
1339git commit -m "fix: resolve merge conflict"
1340```
1341
1342## 🤖 Agent関連
1343
1344### Agent実行が失敗する
1345
1346**症状**:
1347```
1348Error: Agent execution failed
1349```
1350
1351**解決策**:
13521. ログファイル確認:
1353 ```bash
1354 tail -f logs/miyabi-$(date +%Y%m%d).log
1355 ```
13562. Issue番号が正しいか確認:
1357 ```bash
1358 gh issue list
1359 ```
13603. Labelが正しく設定されているか確認
1361
1362### Issue番号が見つからない
1363
1364**症状**:
1365```
1366Error: Issue #123 not found
1367```
1368
1369**解決策**:
1370```bash
1371# Issue一覧確認
1372gh issue list --limit 50
1373
1374# 正しい番号で再実行
1375miyabi agent run coordinator --issue 正しい番号
1376```
1377
1378## 📦 インストール関連
1379
1380### `miyabi` コマンドが見つからない
1381
1382**症状**:
1383```
1384command not found: miyabi
1385```
1386
1387**解決策**:
1388```bash
1389# crates.ioから再インストール
1390cargo install miyabi-cli --force
1391
1392# パス確認
1393which miyabi
1394
1395# Cargo binディレクトリがPATHに含まれているか確認
1396echo $PATH | grep -o "$HOME/.cargo/bin"
1397
1398# なければ追加
1399echo 'export PATH="$HOME/.cargo/bin:$PATH"' >> ~/.zshrc
1400source ~/.zshrc
1401```
1402
1403### コンパイルエラー
1404
1405**症状**:
1406```
1407error: failed to compile miyabi-cli
1408```
1409
1410**解決策**:
1411```bash
1412# Rustを最新版にアップデート
1413rustup update stable
1414
1415# Cargoキャッシュをクリア
1416rm -rf ~/.cargo/registry
1417rm -rf ~/.cargo/git
1418
1419# 再インストール
1420cargo install miyabi-cli
1421```
1422
1423## 🌐 GitHub関連
1424
1425### API Rate Limit
1426
1427**症状**:
1428```
1429Error: API rate limit exceeded
1430```
1431
1432**解決策**:
14331. GitHubにログイン状態か確認:
1434 ```bash
1435 gh auth status
1436 ```
14372. Personal Access Tokenのスコープ確認
14383. しばらく待つ(Rate limitは1時間でリセット)
1439
1440### Permission denied
1441
1442**症状**:
1443```
1444Error: Resource not accessible by personal access token
1445```
1446
1447**解決策**:
14481. トークンのスコープを確認: `repo`, `workflow` が必要
14492. 新しいトークンを生成
14503. 環境変数を更新
1451
1452## 🔍 デバッグ方法
1453
1454### 詳細ログを有効化
1455
1456`.miyabi.yml` でログレベルを変更:
1457```yaml
1458logging:
1459 level: debug # info → debug
1460 directory: "./logs"
1461```
1462
1463### ログファイルの確認
1464
1465```bash
1466# 最新のログ
1467tail -100 logs/miyabi-$(date +%Y%m%d).log
1468
1469# エラーのみ抽出
1470grep -i "error\|fail" logs/miyabi-*.log
1471
1472# 特定のAgentのログ
1473grep -i "CoordinatorAgent" logs/miyabi-*.log
1474```
1475
1476### miyabi status の活用
1477
1478```bash
1479miyabi status
1480
1481# 出力例:
1482# Miyabi Installation: ✅ or ❌
1483# Environment: GITHUB_TOKEN, ANTHROPIC_API_KEY の状態
1484# Git Repository: ブランチ、コミット状態
1485# Worktrees: アクティブなWorktree数
1486```
1487
1488## 🆘 それでも解決しない場合
1489
1490### サポートを受ける
1491
14921. **GitHub Issues**: https://github.com/ShunsukeHayashi/Miyabi/issues
1493 - 詳細なエラーメッセージを含めてください
1494 - `miyabi status` の出力を添付
1495 - ログファイルの関連部分を添付
1496
14972. **Discord Community**: (準備中)
1498
14993. **ドキュメント**:
1500 - [GETTING_STARTED.md](GETTING_STARTED.md)
1501 - [CLAUDE.md](../CLAUDE.md)
1502 - [GitHub Discussions](https://github.com/ShunsukeHayashi/Miyabi/discussions)
1503
1504### 報告に含めるべき情報
1505
1506```bash
1507# システム情報
1508uname -a
1509
1510# Rustバージョン
1511rustc --version
1512cargo --version
1513
1514# miyabiバージョン
1515miyabi --version
1516
1517# プロジェクト状態
1518miyabi status
1519
1520# 直近のログ
1521tail -50 logs/miyabi-$(date +%Y%m%d).log
1522```
1523
1524---
1525
1526**Miyabi** - Beauty in Autonomous Development 🌸
1527"#;
1528 fs::write(project_dir.join("docs/TROUBLESHOOTING.md"), troubleshooting)?;
1529
1530 println!(" Created configuration files");
1531 Ok(())
1532 }
1533}
1534
1535#[cfg(test)]
1536mod tests {
1537 use super::*;
1538
1539 #[test]
1540 fn test_validate_project_name() {
1541 let valid_cmd = InitCommand::new("my-project".to_string(), false);
1542 assert!(valid_cmd.validate_project_name().is_ok());
1543
1544 let valid_cmd = InitCommand::new("my_project_123".to_string(), false);
1545 assert!(valid_cmd.validate_project_name().is_ok());
1546
1547 let invalid_cmd = InitCommand::new("".to_string(), false);
1548 assert!(invalid_cmd.validate_project_name().is_err());
1549
1550 let invalid_cmd = InitCommand::new("my project".to_string(), false);
1551 assert!(invalid_cmd.validate_project_name().is_err());
1552
1553 let invalid_cmd = InitCommand::new("my@project".to_string(), false);
1554 assert!(invalid_cmd.validate_project_name().is_err());
1555 }
1556}