Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3b43035a36 | |||
| 84b49a7ff5 | |||
| 9963ea7ef7 |
@@ -1,52 +1,52 @@
|
||||
# Pull Request
|
||||
|
||||
## 概要
|
||||
## Summary
|
||||
|
||||
<!-- このPRの目的を簡潔に説明 -->
|
||||
<!-- Briefly describe the purpose of this PR -->
|
||||
|
||||
## 変更内容
|
||||
## Changes
|
||||
|
||||
<!-- 主な変更点をリストアップ -->
|
||||
<!-- List the main changes -->
|
||||
-
|
||||
|
||||
## 関連Issue
|
||||
## Related Issue
|
||||
|
||||
<!-- 関連するIssue番号があれば記載 -->
|
||||
<!-- Reference related issue numbers if applicable -->
|
||||
Closes #
|
||||
|
||||
## チェックリスト
|
||||
## Checklist
|
||||
|
||||
### Git Workflow
|
||||
- [ ] 外部貢献の場合: Fork → topic branch → upstream PR の流れに従った
|
||||
- [ ] コラボレーターの場合: topic branch使用(main直コミットしていない)
|
||||
- [ ] `git rebase upstream/main` 済み(コンフリクトなし)
|
||||
- [ ] コミットメッセージは Conventional Commits に準拠(`feat:`, `fix:`, `docs:` など)
|
||||
- [ ] External contributors: Followed Fork → topic branch → upstream PR flow
|
||||
- [ ] Collaborators: Used topic branch (no direct commits to main)
|
||||
- [ ] Rebased on upstream/main (`git rebase upstream/main`, no conflicts)
|
||||
- [ ] Commit messages follow Conventional Commits (`feat:`, `fix:`, `docs:`, etc.)
|
||||
|
||||
### Code Quality
|
||||
- [ ] 変更は1目的に限定(巨大PRでない、目安: ~200行差分以内)
|
||||
- [ ] 既存のコード規約・パターンに従っている
|
||||
- [ ] 新機能/修正には適切なテストを追加
|
||||
- [ ] Lint/Format/Typecheck すべてパス
|
||||
- [ ] CI/CD パイプライン成功(グリーン状態)
|
||||
- [ ] Changes are limited to a single purpose (not a mega-PR; aim for ~200 lines diff)
|
||||
- [ ] Follows existing code conventions and patterns
|
||||
- [ ] Added appropriate tests for new features/fixes
|
||||
- [ ] Lint/Format/Typecheck all pass
|
||||
- [ ] CI/CD pipeline succeeds (green status)
|
||||
|
||||
### Security
|
||||
- [ ] シークレット・認証情報をコミットしていない
|
||||
- [ ] `.gitignore` で必要なファイルを除外済み
|
||||
- [ ] 破壊的変更なし/ある場合は `!` 付きコミット + MIGRATION.md 記載
|
||||
- [ ] No secrets or credentials committed
|
||||
- [ ] Necessary files excluded via `.gitignore`
|
||||
- [ ] No breaking changes, or if so: `!` commit + MIGRATION.md documented
|
||||
|
||||
### Documentation
|
||||
- [ ] 必要に応じてドキュメントを更新(README, CLAUDE.md, docs/など)
|
||||
- [ ] 複雑なロジックにコメント追加
|
||||
- [ ] APIの変更がある場合は適切に文書化
|
||||
- [ ] Updated documentation as needed (README, CLAUDE.md, docs/, etc.)
|
||||
- [ ] Added comments for complex logic
|
||||
- [ ] API changes are properly documented
|
||||
|
||||
## テスト方法
|
||||
## How to Test
|
||||
|
||||
<!-- このPRの動作確認方法 -->
|
||||
<!-- Describe how to verify this PR works -->
|
||||
|
||||
## スクリーンショット(該当する場合)
|
||||
## Screenshots (if applicable)
|
||||
|
||||
<!-- UIの変更がある場合はスクリーンショットを添付 -->
|
||||
<!-- Attach screenshots for UI changes -->
|
||||
|
||||
## 備考
|
||||
## Notes
|
||||
|
||||
<!-- レビュワーに伝えたいこと、技術的な判断の背景など -->
|
||||
<!-- Anything you want reviewers to know, technical decisions, etc. -->
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
name: Pull Sync from Framework
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 */6 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
sync-and-isolate:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
steps:
|
||||
- name: Checkout Plugin Repository (Target)
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
path: plugin-repo
|
||||
|
||||
- name: Check for Framework updates
|
||||
id: check-updates
|
||||
run: |
|
||||
FRAMEWORK_HEAD=$(git ls-remote https://github.com/SuperClaude-Org/SuperClaude_Framework HEAD | cut -f1)
|
||||
echo "Current framework HEAD: $FRAMEWORK_HEAD"
|
||||
echo "framework-head=$FRAMEWORK_HEAD" >> $GITHUB_OUTPUT
|
||||
|
||||
LAST_SYNCED=""
|
||||
if [ -f "plugin-repo/docs/.framework-sync-commit" ]; then
|
||||
LAST_SYNCED=$(cat plugin-repo/docs/.framework-sync-commit)
|
||||
echo "Last synced commit: $LAST_SYNCED"
|
||||
else
|
||||
echo "No previous sync state - will run sync"
|
||||
fi
|
||||
|
||||
if [ "$FRAMEWORK_HEAD" = "$LAST_SYNCED" ] && [ "${{ github.event_name }}" != "workflow_dispatch" ]; then
|
||||
echo "✅ Framework is up to date - skipping sync"
|
||||
echo "has-updates=false" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "🔄 Framework has updates - proceeding with sync"
|
||||
echo "has-updates=true" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Checkout Framework Repository (Source)
|
||||
if: steps.check-updates.outputs.has-updates == 'true'
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: SuperClaude-Org/SuperClaude_Framework
|
||||
path: framework-src
|
||||
|
||||
- name: Set up Python
|
||||
if: steps.check-updates.outputs.has-updates == 'true'
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.10'
|
||||
|
||||
- name: Run Transformation & Sync Logic
|
||||
if: steps.check-updates.outputs.has-updates == 'true'
|
||||
run: |
|
||||
cd plugin-repo
|
||||
python3 scripts/sync_from_framework.py
|
||||
|
||||
- name: Verify protected files are unchanged
|
||||
if: steps.check-updates.outputs.has-updates == 'true'
|
||||
working-directory: plugin-repo
|
||||
run: |
|
||||
# Note: plugin.json removed from list as it is updated by the MCP merge script
|
||||
PROTECTED=(
|
||||
"README.md" "README-ja.md" "README-zh.md"
|
||||
"BACKUP_GUIDE.md" "MIGRATION_GUIDE.md" "SECURITY.md"
|
||||
"CLAUDE.md" "LICENSE" ".gitignore"
|
||||
".claude-plugin/marketplace.json"
|
||||
"core/" "modes/"
|
||||
)
|
||||
VIOLATIONS=()
|
||||
for path in "${PROTECTED[@]}"; do
|
||||
if git diff --name-only HEAD -- "$path" | grep -q .; then
|
||||
VIOLATIONS+=("$path")
|
||||
fi
|
||||
done
|
||||
if [ ${#VIOLATIONS[@]} -gt 0 ]; then
|
||||
echo "🚨 PROTECTION VIOLATION: sync modified Plugin-owned files:"
|
||||
for v in "${VIOLATIONS[@]}"; do echo " • $v"; done
|
||||
echo ""
|
||||
echo "Fix: check SYNC_MAPPINGS in scripts/sync_from_framework.py"
|
||||
exit 1
|
||||
fi
|
||||
echo "🔒 Protection check passed — no Plugin-owned files were modified"
|
||||
|
||||
- name: Save framework sync state
|
||||
if: steps.check-updates.outputs.has-updates == 'true'
|
||||
run: |
|
||||
echo "${{ steps.check-updates.outputs.framework-head }}" > plugin-repo/docs/.framework-sync-commit
|
||||
echo "✅ Saved framework commit: ${{ steps.check-updates.outputs.framework-head }}"
|
||||
|
||||
- name: Commit Changes to Sync Branch
|
||||
if: steps.check-updates.outputs.has-updates == 'true'
|
||||
id: commit-changes
|
||||
working-directory: plugin-repo
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
|
||||
SYNC_BRANCH="framework-sync/$(date +'%Y-%m-%d-%H%M')"
|
||||
git checkout -b "$SYNC_BRANCH"
|
||||
|
||||
git add commands/ agents/ .claude-plugin/plugin.json plugin.json
|
||||
|
||||
if [ -f "docs/.framework-sync-commit" ]; then
|
||||
git add -f docs/.framework-sync-commit
|
||||
fi
|
||||
|
||||
if ! git diff --cached --quiet; then
|
||||
git commit -m "chore: automated sync from framework [${{ steps.check-updates.outputs.framework-head }}]"
|
||||
git push origin "$SYNC_BRANCH"
|
||||
echo "has-changes=true" >> $GITHUB_OUTPUT
|
||||
echo "sync-branch=$SYNC_BRANCH" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "No changes detected."
|
||||
echo "has-changes=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Create Pull Request for Review
|
||||
if: steps.commit-changes.outputs.has-changes == 'true'
|
||||
working-directory: plugin-repo
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh pr create \
|
||||
--title "chore: framework sync ${{ steps.check-updates.outputs.framework-head }}" \
|
||||
--body "## Automated Framework Sync
|
||||
|
||||
Synced from upstream framework commit: \`${{ steps.check-updates.outputs.framework-head }}\`
|
||||
|
||||
**Review required before merge.** This PR was created automatically by the framework sync workflow. Please review the changes to ensure no unexpected modifications were introduced.
|
||||
|
||||
---
|
||||
*Auto-generated by pull-sync-framework workflow*" \
|
||||
--base main \
|
||||
--head "${{ steps.commit-changes.outputs.sync-branch }}"
|
||||
@@ -39,8 +39,8 @@ jobs:
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
SuperClaude多语言README质量检查器
|
||||
检查版本同步、链接有效性、结构一致性
|
||||
SuperClaude Multi-language README Quality Checker
|
||||
Checks version sync, link validity, and structural consistency
|
||||
"""
|
||||
|
||||
import os
|
||||
@@ -61,19 +61,19 @@ jobs:
|
||||
}
|
||||
|
||||
def check_structure_consistency(self):
|
||||
"""检查结构一致性"""
|
||||
print("🔍 检查结构一致性...")
|
||||
"""Check structural consistency"""
|
||||
print("🔍 Checking structural consistency...")
|
||||
|
||||
structures = {}
|
||||
for file in self.readme_files:
|
||||
if os.path.exists(file):
|
||||
with open(file, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
# 提取标题结构
|
||||
# Extract heading structure
|
||||
headers = re.findall(r'^#{1,6}\s+(.+)$', content, re.MULTILINE)
|
||||
structures[file] = len(headers)
|
||||
|
||||
# 比较结构差异
|
||||
# Compare structural differences
|
||||
line_counts = [structures.get(f, 0) for f in self.readme_files if f in structures]
|
||||
if line_counts:
|
||||
max_diff = max(line_counts) - min(line_counts)
|
||||
@@ -85,13 +85,13 @@ jobs:
|
||||
'status': 'PASS' if consistency_score >= 90 else 'WARN'
|
||||
}
|
||||
|
||||
print(f"✅ 结构一致性: {consistency_score}/100")
|
||||
print(f"✅ Structural consistency: {consistency_score}/100")
|
||||
for file, count in structures.items():
|
||||
print(f" {file}: {count} headers")
|
||||
|
||||
def check_link_validation(self):
|
||||
"""检查链接有效性"""
|
||||
print("🔗 检查链接有效性...")
|
||||
"""Check link validity"""
|
||||
print("🔗 Checking link validity...")
|
||||
|
||||
all_links = {}
|
||||
broken_links = []
|
||||
@@ -101,14 +101,14 @@ jobs:
|
||||
with open(file, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
|
||||
# 提取所有链接
|
||||
# Extract all links
|
||||
links = re.findall(r'\[([^\]]+)\]\(([^)]+)\)', content)
|
||||
all_links[file] = []
|
||||
|
||||
for text, url in links:
|
||||
link_info = {'text': text, 'url': url, 'status': 'unknown'}
|
||||
|
||||
# 检查本地文件链接
|
||||
# Check local file links
|
||||
if not url.startswith(('http://', 'https://', '#')):
|
||||
if os.path.exists(url):
|
||||
link_info['status'] = 'valid'
|
||||
@@ -116,10 +116,10 @@ jobs:
|
||||
link_info['status'] = 'broken'
|
||||
broken_links.append(f"{file}: {url}")
|
||||
|
||||
# HTTP链接检查(简化版)
|
||||
# HTTP link check (simplified)
|
||||
elif url.startswith(('http://', 'https://')):
|
||||
try:
|
||||
# 只检查几个关键链接,避免过多请求
|
||||
# Only check key links to avoid excessive requests
|
||||
if any(domain in url for domain in ['github.com', 'pypi.org', 'npmjs.com']):
|
||||
response = requests.head(url, timeout=10, allow_redirects=True)
|
||||
link_info['status'] = 'valid' if response.status_code < 400 else 'broken'
|
||||
@@ -132,7 +132,7 @@ jobs:
|
||||
|
||||
all_links[file].append(link_info)
|
||||
|
||||
# 计算链接健康度
|
||||
# Calculate link health score
|
||||
total_links = sum(len(links) for links in all_links.values())
|
||||
broken_count = len(broken_links)
|
||||
link_score = max(0, 100 - (broken_count * 10)) if total_links > 0 else 100
|
||||
@@ -141,37 +141,37 @@ jobs:
|
||||
'score': link_score,
|
||||
'total_links': total_links,
|
||||
'broken_links': broken_count,
|
||||
'broken_list': broken_links[:10], # 最多显示10个
|
||||
'broken_list': broken_links[:10], # Show max 10
|
||||
'status': 'PASS' if link_score >= 80 else 'FAIL'
|
||||
}
|
||||
|
||||
print(f"✅ 链接有效性: {link_score}/100")
|
||||
print(f" 总链接数: {total_links}")
|
||||
print(f" 损坏链接: {broken_count}")
|
||||
print(f"✅ Link validity: {link_score}/100")
|
||||
print(f" Total links: {total_links}")
|
||||
print(f" Broken links: {broken_count}")
|
||||
|
||||
def check_translation_sync(self):
|
||||
"""检查翻译同步性"""
|
||||
print("🌍 检查翻译同步性...")
|
||||
"""Check translation sync"""
|
||||
print("🌍 Checking translation sync...")
|
||||
|
||||
if not all(os.path.exists(f) for f in self.readme_files):
|
||||
print("⚠️ 缺少某些README文件")
|
||||
print("⚠️ Some README files are missing")
|
||||
self.results['translation_sync'] = {
|
||||
'score': 60,
|
||||
'status': 'WARN',
|
||||
'message': '缺少某些README文件'
|
||||
'message': 'Some README files are missing'
|
||||
}
|
||||
return
|
||||
|
||||
# 检查文件修改时间
|
||||
# Check file modification times
|
||||
mod_times = {}
|
||||
for file in self.readme_files:
|
||||
mod_times[file] = os.path.getmtime(file)
|
||||
|
||||
# 计算时间差异(秒)
|
||||
# Calculate time difference (seconds)
|
||||
times = list(mod_times.values())
|
||||
time_diff = max(times) - min(times)
|
||||
|
||||
# 根据时间差评分(7天内修改认为是同步的)
|
||||
# Score based on time diff (within 7 days = synced)
|
||||
sync_score = max(0, 100 - (time_diff / (7 * 24 * 3600) * 20))
|
||||
|
||||
self.results['translation_sync'] = {
|
||||
@@ -181,14 +181,14 @@ jobs:
|
||||
'mod_times': {f: f"{os.path.getmtime(f):.0f}" for f in self.readme_files}
|
||||
}
|
||||
|
||||
print(f"✅ 翻译同步性: {int(sync_score)}/100")
|
||||
print(f" 最大时间差: {round(time_diff / (24 * 3600), 1)} 天")
|
||||
print(f"✅ Translation sync: {int(sync_score)}/100")
|
||||
print(f" Max time difference: {round(time_diff / (24 * 3600), 1)} days")
|
||||
|
||||
def generate_report(self):
|
||||
"""生成质量报告"""
|
||||
print("\n📊 生成质量报告...")
|
||||
"""Generate quality report"""
|
||||
print("\n📊 Generating quality report...")
|
||||
|
||||
# 计算总分
|
||||
# Calculate overall score
|
||||
scores = [
|
||||
self.results['structure_consistency'].get('score', 0),
|
||||
self.results['link_validation'].get('score', 0),
|
||||
@@ -197,18 +197,18 @@ jobs:
|
||||
overall_score = sum(scores) // len(scores)
|
||||
self.results['overall_score'] = overall_score
|
||||
|
||||
# 生成GitHub Actions摘要
|
||||
# Generate GitHub Actions summary
|
||||
pipe = "|"
|
||||
table_header = f"{pipe} 检查项目 {pipe} 分数 {pipe} 状态 {pipe} 详情 {pipe}"
|
||||
table_header = f"{pipe} Check {pipe} Score {pipe} Status {pipe} Details {pipe}"
|
||||
table_separator = f"{pipe}----------|------|------|------|"
|
||||
table_row1 = f"{pipe} 📐 结构一致性 {pipe} {self.results['structure_consistency'].get('score', 0)}/100 {pipe} {self.results['structure_consistency'].get('status', 'N/A')} {pipe} {len(self.results['structure_consistency'].get('details', {}))} 个文件 {pipe}"
|
||||
table_row2 = f"{pipe} 🔗 链接有效性 {pipe} {self.results['link_validation'].get('score', 0)}/100 {pipe} {self.results['link_validation'].get('status', 'N/A')} {pipe} {self.results['link_validation'].get('broken_links', 0)} 个损坏链接 {pipe}"
|
||||
table_row3 = f"{pipe} 🌍 翻译同步性 {pipe} {self.results['translation_sync'].get('score', 0)}/100 {pipe} {self.results['translation_sync'].get('status', 'N/A')} {pipe} {self.results['translation_sync'].get('time_diff_days', 0)} 天差异 {pipe}"
|
||||
|
||||
table_row1 = f"{pipe} 📐 Structure {pipe} {self.results['structure_consistency'].get('score', 0)}/100 {pipe} {self.results['structure_consistency'].get('status', 'N/A')} {pipe} {len(self.results['structure_consistency'].get('details', {}))} files {pipe}"
|
||||
table_row2 = f"{pipe} 🔗 Links {pipe} {self.results['link_validation'].get('score', 0)}/100 {pipe} {self.results['link_validation'].get('status', 'N/A')} {pipe} {self.results['link_validation'].get('broken_links', 0)} broken {pipe}"
|
||||
table_row3 = f"{pipe} 🌍 Translation {pipe} {self.results['translation_sync'].get('score', 0)}/100 {pipe} {self.results['translation_sync'].get('status', 'N/A')} {pipe} {self.results['translation_sync'].get('time_diff_days', 0)} days diff {pipe}"
|
||||
|
||||
summary_parts = [
|
||||
"## 📊 README质量检查报告",
|
||||
"## 📊 README Quality Check Report",
|
||||
"",
|
||||
f"### 🏆 总体评分: {overall_score}/100",
|
||||
f"### 🏆 Overall Score: {overall_score}/100",
|
||||
"",
|
||||
table_header,
|
||||
table_separator,
|
||||
@@ -216,47 +216,47 @@ jobs:
|
||||
table_row2,
|
||||
table_row3,
|
||||
"",
|
||||
"### 📋 详细信息",
|
||||
"### 📋 Details",
|
||||
"",
|
||||
"**结构一致性详情:**"
|
||||
"**Structural consistency details:**"
|
||||
]
|
||||
summary = "\n".join(summary_parts)
|
||||
|
||||
|
||||
for file, count in self.results['structure_consistency'].get('details', {}).items():
|
||||
summary += f"\n- `{file}`: {count} 个标题"
|
||||
|
||||
summary += f"\n- `{file}`: {count} headings"
|
||||
|
||||
if self.results['link_validation'].get('broken_links'):
|
||||
summary += f"\n\n**损坏链接列表:**\n"
|
||||
summary += f"\n\n**Broken links:**\n"
|
||||
for link in self.results['link_validation']['broken_list']:
|
||||
summary += f"\n- ❌ {link}"
|
||||
|
||||
summary += f"\n\n### 🎯 建议\n"
|
||||
|
||||
|
||||
summary += f"\n\n### 🎯 Recommendations\n"
|
||||
|
||||
if overall_score >= 90:
|
||||
summary += "✅ 质量优秀!继续保持。"
|
||||
summary += "✅ Excellent quality! Keep it up."
|
||||
elif overall_score >= 70:
|
||||
summary += "⚠️ 质量良好,有改进空间。"
|
||||
summary += "⚠️ Good quality with room for improvement."
|
||||
else:
|
||||
summary += "🚨 需要改进!请检查上述问题。"
|
||||
|
||||
# 写入GitHub Actions摘要
|
||||
summary += "🚨 Needs improvement! Please review the issues above."
|
||||
|
||||
# Write GitHub Actions summary
|
||||
github_step_summary = os.environ.get('GITHUB_STEP_SUMMARY')
|
||||
if github_step_summary:
|
||||
with open(github_step_summary, 'w', encoding='utf-8') as f:
|
||||
f.write(summary)
|
||||
|
||||
# 保存详细结果
|
||||
# Save detailed results
|
||||
with open('readme-quality-report.json', 'w', encoding='utf-8') as f:
|
||||
json.dump(self.results, f, indent=2, ensure_ascii=False)
|
||||
|
||||
print("✅ 报告已生成")
|
||||
|
||||
# 根据分数决定退出码
|
||||
print("✅ Report generated")
|
||||
|
||||
# Determine exit code based on score
|
||||
return 0 if overall_score >= 70 else 1
|
||||
|
||||
def run_all_checks(self):
|
||||
"""运行所有检查"""
|
||||
print("🚀 开始README质量检查...\n")
|
||||
"""Run all checks"""
|
||||
print("🚀 Starting README quality check...\n")
|
||||
|
||||
self.check_structure_consistency()
|
||||
self.check_link_validation()
|
||||
@@ -264,7 +264,7 @@ jobs:
|
||||
|
||||
exit_code = self.generate_report()
|
||||
|
||||
print(f"\n🎯 检查完成!总分: {self.results['overall_score']}/100")
|
||||
print(f"\n🎯 Check complete! Score: {self.results['overall_score']}/100")
|
||||
return exit_code
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -297,11 +297,11 @@ jobs:
|
||||
const score = report.overall_score;
|
||||
const emoji = score >= 90 ? '🏆' : score >= 70 ? '✅' : '⚠️';
|
||||
|
||||
const comment = `${emoji} **README质量检查结果: ${score}/100**\n\n` +
|
||||
`📐 结构一致性: ${report.structure_consistency?.score || 0}/100\n` +
|
||||
`🔗 链接有效性: ${report.link_validation?.score || 0}/100\n` +
|
||||
`🌍 翻译同步性: ${report.translation_sync?.score || 0}/100\n\n` +
|
||||
`查看详细报告请点击 Actions 标签页。`;
|
||||
const comment = `${emoji} **README Quality Check: ${score}/100**\n\n` +
|
||||
`📐 Structural consistency: ${report.structure_consistency?.score || 0}/100\n` +
|
||||
`🔗 Link validity: ${report.link_validation?.score || 0}/100\n` +
|
||||
`🌍 Translation sync: ${report.translation_sync?.score || 0}/100\n\n` +
|
||||
`See the Actions tab for the detailed report.`;
|
||||
|
||||
github.rest.issues.createComment({
|
||||
issue_number: context.issue.number,
|
||||
|
||||
+3
-24
@@ -98,10 +98,12 @@ Pipfile.lock
|
||||
# Poetry
|
||||
poetry.lock
|
||||
|
||||
# Claude Code - only ignore user-specific files
|
||||
# Claude Code - only ignore user-specific files, keep settings.json and skills/
|
||||
.claude/history/
|
||||
.claude/cache/
|
||||
.claude/*.lock
|
||||
!.claude/settings.json
|
||||
!.claude/skills/
|
||||
|
||||
# SuperClaude specific
|
||||
.serena/
|
||||
@@ -110,7 +112,6 @@ poetry.lock
|
||||
*.bak
|
||||
|
||||
# Project specific
|
||||
Tests/
|
||||
temp/
|
||||
tmp/
|
||||
.cache/
|
||||
@@ -166,30 +167,8 @@ release-notes/
|
||||
changelog-temp/
|
||||
|
||||
# Build artifacts (additional)
|
||||
*.deb
|
||||
*.rpm
|
||||
*.dmg
|
||||
*.pkg
|
||||
*.msi
|
||||
*.exe
|
||||
|
||||
# IDE & Editor specific
|
||||
.vscode/settings.json
|
||||
.vscode/launch.json
|
||||
.idea/workspace.xml
|
||||
.idea/tasks.xml
|
||||
*.sublime-project
|
||||
*.sublime-workspace
|
||||
|
||||
# System & OS
|
||||
.DS_Store
|
||||
.DS_Store?
|
||||
._*
|
||||
.Spotlight-V100
|
||||
.Trashes
|
||||
ehthumbs.db
|
||||
Thumbs.db
|
||||
Desktop.ini
|
||||
$RECYCLE.BIN/
|
||||
|
||||
# Personal files
|
||||
|
||||
+56
-25
@@ -7,36 +7,67 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [4.2.0] - 2025-09-18
|
||||
## [4.3.0] - 2026-03-22
|
||||
### Added
|
||||
- **Deep Research System** - Complete implementation of autonomous web research capabilities
|
||||
- New `/sc:research` command for intelligent web research with DR Agent architecture
|
||||
- `deep-research-agent` - 15th specialized agent for research orchestration
|
||||
- `MODE_DeepResearch` - 7th behavioral mode for research workflows
|
||||
- Tavily MCP integration (7th MCP server) for real-time web search
|
||||
- Research configuration system (`RESEARCH_CONFIG.md`)
|
||||
- Comprehensive workflow examples (`deep_research_workflows.md`)
|
||||
- Three planning strategies: Planning-Only, Intent-to-Planning, Unified Intent-Planning
|
||||
- Multi-hop reasoning with genealogy tracking for complex queries
|
||||
- Case-based reasoning for learning from past research patterns
|
||||
- **Agent installation** - `superclaude install` now deploys 20 agent files to `~/.claude/agents/` (#531)
|
||||
- **SHA-256 integrity verification** - Downloaded docker-compose and mcp-config files are verified against expected hashes (#537)
|
||||
- **Comprehensive execution tests** - 62 new tests for ParallelExecutor, ReflectionEngine, SelfCorrectionEngine, and orchestrator (136 total)
|
||||
- **Claude Code integration guide** - New `docs/user-guide/claude-code-integration.md` mapping all SuperClaude features to Claude Code's native extension points with gap analysis
|
||||
- **Claude Code gap analysis** - Documented in KNOWLEDGE.md: skills migration (critical), hooks integration (high), plan mode (medium), settings profiles (medium)
|
||||
|
||||
### Fixed
|
||||
- **SECURITY: shell=True removal** - Replaced `shell=True` with user-controlled `$SHELL` in `_run_command()` with direct list-based `subprocess.run` (#536)
|
||||
- **ConfidenceChecker placeholders** - Replaced 4 stub methods with real implementations: codebase search, architecture doc checks, research reference validation, root cause specificity checks
|
||||
- **intelligent_execute() error capture** - Collect actual errors from failed tasks instead of hardcoded None; fixed critical variable shadowing bug where loop var overwrote task parameter
|
||||
- **MCP env var flag** - Fixed `--env` to `-e` matching Claude CLI's expected format (#517)
|
||||
- **ReflexionPattern mindbase** - Implemented HTTP API integration with graceful fallback when service unavailable
|
||||
- **.gitignore contradictions** - Removed duplicate entries, added explicit rules for `.claude/settings.json` and `.claude/skills/`
|
||||
- **FailureEntry.from_dict** - Fixed input dict mutation via shallow copy
|
||||
- **sys.path hack** - Removed unnecessary `sys.path.insert` from cli/main.py
|
||||
- **__version__.py mismatch** - Synced from 0.4.0 to match package version
|
||||
|
||||
### Changed
|
||||
- Updated agent count from 14 to 15 (added deep-research-agent)
|
||||
- Updated mode count from 6 to 7 (added MODE_DeepResearch)
|
||||
- Updated MCP server count from 6 to 7 (added Tavily)
|
||||
- Updated command count from 24 to 25 (added /sc:research)
|
||||
- Enhanced MCP component with remote server support for Tavily
|
||||
- Added `_install_remote_mcp_server` method to handle remote MCP configurations
|
||||
- **Japanese triggers → English** - Replaced Japanese trigger phrases and labels in pm-agent.md and pm.md with English equivalents (#534)
|
||||
- **Version consistency** - All version references across 15 files now synchronized
|
||||
- **Feature counts** - Corrected across all docs: Commands 21→30, Agents 14/16→20, Modes 6→7, MCP 6→8
|
||||
- **CLAUDE.md** - Complete project structure with agents, modes, commands, skills, hooks, MCP directories
|
||||
- **PLANNING.md, TASK.md, KNOWLEDGE.md** - Updated to reflect current architecture and Claude Code integration gaps
|
||||
|
||||
### Technical
|
||||
- Added Tavily to `server_docs_map` in `setup/components/mcp_docs.py`
|
||||
- Implemented remote MCP server handler in `setup/components/mcp.py`
|
||||
- Added `check_research_prerequisites()` function in `setup/utils/environment.py`
|
||||
- Created verification script `scripts/verify_research_integration.sh`
|
||||
## [4.2.0] - 2026-01-18
|
||||
### Added
|
||||
- **AIRIS MCP Gateway** - Optional unified MCP solution with 60+ tools (#509)
|
||||
- Single SSE endpoint at `localhost:9400`
|
||||
- 98% token reduction through HOT/COLD tool management
|
||||
- Requires Docker (optional - individual servers still supported)
|
||||
- **Airis Agent and MindBase MCP servers** - New individual server options (#497)
|
||||
- **Explicit command boundaries and handoff instructions** - All 30 commands now have clear scope definitions (#513)
|
||||
- **Complete command reference documentation** - Comprehensive docs for all slash commands (#512)
|
||||
|
||||
### Requirements
|
||||
- `TAVILY_API_KEY` environment variable for web search functionality
|
||||
- Node.js and npm for Tavily MCP execution
|
||||
### Fixed
|
||||
- UTF-8 encoding handling for MCP command output on all platforms (#507)
|
||||
|
||||
### Changed
|
||||
- MCP installer now offers AIRIS Gateway as recommended option (with Docker)
|
||||
- Individual MCP servers remain fully supported for users without Docker
|
||||
- Command documentation improved with boundaries, triggers, and next-step guidance
|
||||
|
||||
## [4.1.9] - 2026-01-15
|
||||
### Added
|
||||
- **Framework Restoration** - Complete SuperClaude framework restored from commit d4a17fc
|
||||
- **30 Slash Commands** - All slash commands restored with comprehensive documentation
|
||||
- **install.sh Script** - Missing installation script added (#483)
|
||||
- **MCP Command** - New `superclaude mcp` command for MCP server management
|
||||
- **Tavily MCP Server** - Web search integration for deep research capabilities
|
||||
- **Chrome DevTools MCP** - Browser debugging and performance analysis
|
||||
|
||||
### Fixed
|
||||
- Package distribution now includes all plugin resources
|
||||
- Commands path resolution prioritizes package location
|
||||
- Commands and skills properly included in MANIFEST.in
|
||||
|
||||
### Changed
|
||||
- Synchronized translated READMEs with main README structure
|
||||
- Added `__init__.py` to all packages for proper module resolution
|
||||
|
||||
## [4.1.5] - 2025-09-26
|
||||
### Added
|
||||
|
||||
@@ -18,33 +18,62 @@ uv run python script.py # Execute scripts
|
||||
|
||||
## 📂 Project Structure
|
||||
|
||||
**Current v4.1.9 Architecture**: Python package with slash commands
|
||||
**Current v4.3.0 Architecture**: Python package with 30 commands, 20 agents, 7 modes
|
||||
|
||||
```
|
||||
# Claude Code Configuration (v4.1.9)
|
||||
.claude/
|
||||
├── settings.json # User settings
|
||||
└── commands/ # Slash commands (installed via `superclaude install`)
|
||||
├── pm.md
|
||||
├── research.md
|
||||
└── index-repo.md
|
||||
# Claude Code Configuration (v4.3.0)
|
||||
# Installed via `superclaude install` to user's home directory
|
||||
~/.claude/
|
||||
├── settings.json
|
||||
├── commands/sc/ # 30 slash commands (/sc:research, /sc:implement, etc.)
|
||||
│ ├── pm.md
|
||||
│ ├── research.md
|
||||
│ ├── implement.md
|
||||
│ └── ... (30 total)
|
||||
├── agents/ # 20 domain-specialist agents (@pm-agent, @system-architect, etc.)
|
||||
│ ├── pm-agent.md
|
||||
│ ├── system-architect.md
|
||||
│ └── ... (20 total)
|
||||
└── skills/ # Skills (confidence-check, etc.)
|
||||
|
||||
# Python Package
|
||||
src/superclaude/ # Pytest plugin + CLI tools
|
||||
├── pytest_plugin.py # Auto-loaded pytest integration
|
||||
├── pm_agent/ # confidence.py, self_check.py, reflexion.py
|
||||
src/superclaude/
|
||||
├── __init__.py # Public API: ConfidenceChecker, SelfCheckProtocol, ReflexionPattern
|
||||
├── pytest_plugin.py # Auto-loaded pytest integration (5 fixtures, 9 markers)
|
||||
├── pm_agent/ # confidence.py, self_check.py, reflexion.py, token_budget.py
|
||||
├── execution/ # parallel.py, reflection.py, self_correction.py
|
||||
└── cli/ # main.py, doctor.py, install_skill.py
|
||||
├── cli/ # main.py, doctor.py, install_commands.py, install_mcp.py, install_skill.py
|
||||
├── commands/ # 30 slash command definitions (.md files)
|
||||
├── agents/ # 20 agent definitions (.md files)
|
||||
├── modes/ # 7 behavioral modes (.md files)
|
||||
├── skills/ # Installable skills (confidence-check, etc.)
|
||||
├── hooks/ # Claude Code hook definitions
|
||||
├── mcp/ # MCP server configurations (10 servers)
|
||||
└── core/ # Core utilities
|
||||
|
||||
# Project Files
|
||||
tests/ # Python test suite
|
||||
tests/ # Python test suite (136 tests)
|
||||
├── unit/ # Unit tests (auto-marked @pytest.mark.unit)
|
||||
└── integration/ # Integration tests (auto-marked @pytest.mark.integration)
|
||||
docs/ # Documentation
|
||||
scripts/ # Analysis tools (workflow metrics, A/B testing)
|
||||
plugins/ # Exported plugin artefacts for distribution
|
||||
PLANNING.md # Architecture, absolute rules
|
||||
TASK.md # Current tasks
|
||||
KNOWLEDGE.md # Accumulated insights
|
||||
```
|
||||
|
||||
### Claude Code Integration Points
|
||||
|
||||
SuperClaude integrates with Claude Code through these mechanisms:
|
||||
- **Slash Commands**: 30 commands installed to `~/.claude/commands/sc/` (e.g., `/sc:pm`, `/sc:research`)
|
||||
- **Agents**: 20 agents installed to `~/.claude/agents/` (e.g., `@pm-agent`, `@system-architect`)
|
||||
- **Skills**: Installed to `~/.claude/skills/` (e.g., confidence-check)
|
||||
- **Hooks**: Session lifecycle hooks in `src/superclaude/hooks/`
|
||||
- **Settings**: Project settings in `.claude/settings.json`
|
||||
- **Pytest Plugin**: Auto-loaded via entry point, provides fixtures and markers
|
||||
- **MCP Servers**: 8+ servers configurable via `superclaude mcp`
|
||||
|
||||
## 🔧 Development Workflow
|
||||
|
||||
### Essential Commands
|
||||
@@ -115,11 +144,13 @@ Registered via `pyproject.toml` entry point, automatically available after insta
|
||||
- Automatic dependency analysis
|
||||
- Example: [Read files in parallel] → Analyze → [Edit files in parallel]
|
||||
|
||||
### Slash Commands (v4.1.9)
|
||||
### Slash Commands, Agents & Modes (v4.3.0)
|
||||
|
||||
- Install via: `pipx install superclaude && superclaude install`
|
||||
- Commands installed to: `~/.claude/commands/`
|
||||
- Available: `/pm`, `/research`, `/index-repo`, and 27 others
|
||||
- **30 Commands** installed to `~/.claude/commands/sc/` (e.g., `/sc:pm`, `/sc:research`, `/sc:implement`)
|
||||
- **20 Agents** installed to `~/.claude/agents/` (e.g., `@pm-agent`, `@system-architect`, `@deep-research`)
|
||||
- **7 Behavioral Modes**: Brainstorming, Business Panel, Deep Research, Introspection, Orchestration, Task Management, Token Efficiency
|
||||
- **Skills**: Installable to `~/.claude/skills/` (e.g., confidence-check)
|
||||
|
||||
> **Note**: TypeScript plugin system planned for v5.0 ([#419](https://github.com/SuperClaude-Org/SuperClaude_Framework/issues/419))
|
||||
|
||||
@@ -241,7 +272,7 @@ superclaude mcp # Interactive install, gateway is default (requires Docker)
|
||||
|
||||
## 🚀 Development & Installation
|
||||
|
||||
### Current Installation Method (v4.1.9)
|
||||
### Current Installation Method (v4.3.0)
|
||||
|
||||
**Standard Installation**:
|
||||
```bash
|
||||
@@ -275,7 +306,7 @@ See `docs/plugin-reorg.md` for details.
|
||||
## 📊 Package Information
|
||||
|
||||
**Package name**: `superclaude`
|
||||
**Version**: 4.1.9
|
||||
**Version**: 4.3.0
|
||||
**Python**: >=3.10
|
||||
**Build system**: hatchling (PEP 517)
|
||||
|
||||
@@ -287,3 +318,24 @@ See `docs/plugin-reorg.md` for details.
|
||||
- pytest>=7.0.0
|
||||
- click>=8.0.0
|
||||
- rich>=13.0.0
|
||||
|
||||
## 🔌 Claude Code Native Features (for developers)
|
||||
|
||||
SuperClaude extends Claude Code through its native extension points. When developing SuperClaude features, use these Claude Code capabilities:
|
||||
|
||||
### Extension Points We Use
|
||||
- **Custom Commands** (`~/.claude/commands/sc/*.md`): 30 `/sc:*` commands
|
||||
- **Custom Agents** (`~/.claude/agents/*.md`): 20 domain-specialist agents
|
||||
- **Skills** (`~/.claude/skills/`): confidence-check skill
|
||||
- **Settings** (`.claude/settings.json`): Permission rules, hooks
|
||||
- **MCP Servers**: 8 pre-configured + AIRIS gateway
|
||||
- **Pytest Plugin**: Auto-loaded via entry point
|
||||
|
||||
### Extension Points We Should Use More
|
||||
- **Hooks** (28 events): `SessionStart`, `Stop`, `PostToolUse`, `TaskCompleted` — ideal for PM Agent auto-restore, self-check validation, and reflexion triggers
|
||||
- **Skills System**: Commands should migrate to proper skills with YAML frontmatter for auto-triggering, tool restrictions, and effort overrides
|
||||
- **Plan Mode**: Could integrate with confidence checks (block implementation when < 70%)
|
||||
- **Settings Profiles**: Could provide recommended permission/hook configs per workflow
|
||||
- **Native Session Persistence**: `--continue`/`--resume` instead of custom memory files
|
||||
|
||||
See `docs/user-guide/claude-code-integration.md` for the full gap analysis.
|
||||
|
||||
@@ -595,6 +595,48 @@ Ideas worth investigating:
|
||||
|
||||
---
|
||||
|
||||
## 🔌 **Claude Code Integration Gap Analysis** (March 2026)
|
||||
|
||||
### Key Finding: SuperClaude Under-uses Claude Code's Extension Points
|
||||
|
||||
Claude Code provides 60+ built-in commands, 28 hook events, a full skills system, 5 settings scopes, agent teams, plan mode, extended thinking, and 60+ MCP servers in its registry. SuperClaude currently uses only a fraction of these.
|
||||
|
||||
### Biggest Gaps (High Impact)
|
||||
|
||||
**1. Skills System (CRITICAL)**
|
||||
- Claude Code skills support YAML frontmatter with `model`, `effort`, `allowed-tools`, `context: fork`, auto-triggering via `description`, and argument substitution
|
||||
- SuperClaude has only 1 skill (confidence-check); 30 commands could be reimplemented as skills for better auto-triggering and tool restrictions
|
||||
- **Action**: Migrate key commands to skills format in v4.3+
|
||||
|
||||
**2. Hooks System (HIGH)**
|
||||
- Claude Code has 28 hook events (`SessionStart`, `Stop`, `PostToolUse`, `TaskCompleted`, `SubagentStop`, `PreCompact`, etc.)
|
||||
- SuperClaude defines hooks but doesn't leverage most events
|
||||
- **Action**: Use `SessionStart` for PM Agent auto-restore, `Stop` for session persistence, `PostToolUse` for self-check, `TaskCompleted` for reflexion
|
||||
|
||||
**3. Plan Mode Integration (MEDIUM)**
|
||||
- Claude Code's plan mode provides read-only exploration with visual markdown plans
|
||||
- SuperClaude's confidence checks could block transition from plan to implementation when confidence < 70%
|
||||
- **Action**: Connect confidence checker to plan mode exit gate
|
||||
|
||||
**4. Settings Profiles (MEDIUM)**
|
||||
- Claude Code has 5 settings scopes with granular permission rules (`Bash(pattern)`, `Edit(path)`, `mcp__server__tool`)
|
||||
- SuperClaude could provide recommended settings profiles per workflow (strict security, autonomous dev, research)
|
||||
- **Action**: Create `.claude/settings.json` templates for common workflows
|
||||
|
||||
### What's Working Well
|
||||
|
||||
- **Commands** (30): Well-integrated as custom commands in `~/.claude/commands/sc/`
|
||||
- **Agents** (20): Properly installed to `~/.claude/agents/` as subagents
|
||||
- **MCP Servers** (8+): Good coverage of common tools, AIRIS gateway unifies them
|
||||
- **Pytest Plugin**: Clean auto-loading, good fixture/marker system
|
||||
- **Behavioral Modes** (7): Effective context injection even without native support
|
||||
|
||||
### Reference
|
||||
|
||||
See `docs/user-guide/claude-code-integration.md` for the complete feature mapping and gap analysis.
|
||||
|
||||
---
|
||||
|
||||
*This document grows with the project. Everyone who encounters a problem and finds a solution should document it here.*
|
||||
|
||||
**Contributors**: SuperClaude development team and community
|
||||
|
||||
+10
-8
@@ -23,7 +23,7 @@ SuperClaude Framework transforms Claude Code into a structured development platf
|
||||
|
||||
## 🏗️ **Architecture Overview**
|
||||
|
||||
### **Current State (v4.1.9)**
|
||||
### **Current State (v4.3.0)**
|
||||
|
||||
SuperClaude is a **Python package** with:
|
||||
- Pytest plugin (auto-loaded via entry points)
|
||||
@@ -33,7 +33,7 @@ SuperClaude is a **Python package** with:
|
||||
- Optional slash commands (installed to ~/.claude/commands/)
|
||||
|
||||
```
|
||||
SuperClaude Framework v4.1.9
|
||||
SuperClaude Framework v4.3.0
|
||||
│
|
||||
├── Core Package (src/superclaude/)
|
||||
│ ├── pytest_plugin.py # Auto-loaded by pytest
|
||||
@@ -237,7 +237,7 @@ Use SelfCheckProtocol to prevent hallucinations:
|
||||
### **Version Management**
|
||||
|
||||
1. **Version sources of truth**:
|
||||
- Framework version: `VERSION` file (e.g., 4.1.9)
|
||||
- Framework version: `VERSION` file (e.g., 4.3.0)
|
||||
- Python package version: `pyproject.toml` (e.g., 0.4.0)
|
||||
- NPM package version: `package.json` (should match VERSION)
|
||||
|
||||
@@ -338,17 +338,19 @@ Before releasing a new version:
|
||||
|
||||
## 🚀 **Roadmap**
|
||||
|
||||
### **v4.1.9 (Current)**
|
||||
### **v4.3.0 (Current)**
|
||||
- ✅ Python package with pytest plugin
|
||||
- ✅ PM Agent patterns (confidence, self-check, reflexion)
|
||||
- ✅ Parallel execution framework
|
||||
- ✅ CLI tools
|
||||
- ✅ Optional slash commands
|
||||
- ✅ CLI tools and slash commands
|
||||
- ✅ AIRIS MCP Gateway (optional, requires Docker)
|
||||
- ✅ Explicit command boundaries and handoff instructions
|
||||
- ✅ Complete command reference documentation
|
||||
|
||||
### **v4.2.0 (Next)**
|
||||
### **v4.3.0 (Next)**
|
||||
- [ ] Complete placeholder implementations in confidence.py
|
||||
- [ ] Add comprehensive test coverage (>80%)
|
||||
- [ ] Enhance MCP server integration
|
||||
- [ ] Enhanced MCP server integration
|
||||
- [ ] Improve documentation
|
||||
|
||||
### **v5.0 (Future)**
|
||||
|
||||
+2
-2
@@ -5,7 +5,7 @@
|
||||
### **Claude Codeを構造化開発プラットフォームに変換**
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/version-4.1.9-blue" alt="Version">
|
||||
<img src="https://img.shields.io/badge/version-4.3.0-blue" alt="Version">
|
||||
<img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License">
|
||||
<img src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg" alt="PRs Welcome">
|
||||
</p>
|
||||
@@ -93,7 +93,7 @@ Claude Codeは[Anthropic](https://www.anthropic.com/)によって構築および
|
||||
> まだ利用できません(v5.0で予定)。v4.xの現在のインストール
|
||||
> 手順については、以下の手順に従ってください。
|
||||
|
||||
### **現在の安定バージョン (v4.1.9)**
|
||||
### **現在の安定バージョン (v4.3.0)**
|
||||
|
||||
SuperClaudeは現在スラッシュコマンドを使用しています。
|
||||
|
||||
|
||||
+2
-2
@@ -5,7 +5,7 @@
|
||||
### **Claude Code를 구조화된 개발 플랫폼으로 변환**
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/version-4.1.9-blue" alt="Version">
|
||||
<img src="https://img.shields.io/badge/version-4.3.0-blue" alt="Version">
|
||||
<img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License">
|
||||
<img src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg" alt="PRs Welcome">
|
||||
</p>
|
||||
@@ -96,7 +96,7 @@ Claude Code는 [Anthropic](https://www.anthropic.com/)에 의해 구축 및 유
|
||||
> 아직 사용할 수 없습니다(v5.0에서 계획). v4.x의 현재 설치
|
||||
> 지침은 아래 단계를 따르세요.
|
||||
|
||||
### **현재 안정 버전 (v4.1.9)**
|
||||
### **현재 안정 버전 (v4.3.0)**
|
||||
|
||||
SuperClaude는 현재 슬래시 명령어를 사용합니다.
|
||||
|
||||
|
||||
+2
-2
@@ -5,7 +5,7 @@
|
||||
### **将Claude Code转换为结构化开发平台**
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/version-4.1.9-blue" alt="Version">
|
||||
<img src="https://img.shields.io/badge/version-4.3.0-blue" alt="Version">
|
||||
<img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License">
|
||||
<img src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg" alt="PRs Welcome">
|
||||
</p>
|
||||
@@ -93,7 +93,7 @@ Claude Code是由[Anthropic](https://www.anthropic.com/)构建和维护的产品
|
||||
> 尚未可用(计划在v5.0中推出)。请按照以下v4.x的
|
||||
> 当前安装说明操作。
|
||||
|
||||
### **当前稳定版本 (v4.1.9)**
|
||||
### **当前稳定版本 (v4.3.0)**
|
||||
|
||||
SuperClaude目前使用斜杠命令。
|
||||
|
||||
|
||||
+646
@@ -0,0 +1,646 @@
|
||||
<div align="center">
|
||||
|
||||
# 🚀 SuperClaude Framework
|
||||
|
||||
[](https://smithery.ai/skills?ns=SuperClaude-Org&utm_source=github&utm_medium=badge)
|
||||
|
||||
|
||||
### **Transform Claude Code into a Structured Development Platform**
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/hesreallyhim/awesome-claude-code/">
|
||||
<img src="https://awesome.re/mentioned-badge-flat.svg" alt="Mentioned in Awesome Claude Code">
|
||||
</a>
|
||||
<a href="https://github.com/SuperClaude-Org/SuperGemini_Framework" target="_blank">
|
||||
<img src="https://img.shields.io/badge/Try-SuperGemini_Framework-blue" alt="Try SuperGemini Framework"/>
|
||||
</a>
|
||||
<a href="https://github.com/SuperClaude-Org/SuperQwen_Framework" target="_blank">
|
||||
<img src="https://img.shields.io/badge/Try-SuperQwen_Framework-orange" alt="Try SuperQwen Framework"/>
|
||||
</a>
|
||||
<img src="https://img.shields.io/badge/version-4.3.0-blue" alt="Version">
|
||||
<a href="https://github.com/SuperClaude-Org/SuperClaude_Framework/actions/workflows/test.yml">
|
||||
<img src="https://github.com/SuperClaude-Org/SuperClaude_Framework/actions/workflows/test.yml/badge.svg" alt="Tests">
|
||||
</a>
|
||||
<img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License">
|
||||
<img src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg" alt="PRs Welcome">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://superclaude.netlify.app/">
|
||||
<img src="https://img.shields.io/badge/🌐_Visit_Website-blue" alt="Website">
|
||||
</a>
|
||||
<a href="https://pypi.org/project/superclaude/">
|
||||
<img src="https://img.shields.io/pypi/v/SuperClaude.svg?" alt="PyPI">
|
||||
</a>
|
||||
<a href="https://pepy.tech/projects/superclaude">
|
||||
<img src="https://static.pepy.tech/personalized-badge/superclaude?period=total&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=GREEN&left_text=downloads" alt="PyPI sats">
|
||||
</a>
|
||||
<a href="https://www.npmjs.com/package/@bifrost_inc/superclaude">
|
||||
<img src="https://img.shields.io/npm/v/@bifrost_inc/superclaude.svg" alt="npm">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">
|
||||
<img src="https://img.shields.io/badge/🇺🇸_English-blue" alt="English">
|
||||
</a>
|
||||
<a href="README-zh.md">
|
||||
<img src="https://img.shields.io/badge/🇨🇳_中文-red" alt="中文">
|
||||
</a>
|
||||
<a href="README-ja.md">
|
||||
<img src="https://img.shields.io/badge/🇯🇵_日本語-green" alt="日本語">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="#-quick-installation">Quick Start</a> •
|
||||
<a href="#-support-the-project">Support</a> •
|
||||
<a href="#-whats-new-in-v4">Features</a> •
|
||||
<a href="#-documentation">Docs</a> •
|
||||
<a href="#-contributing">Contributing</a>
|
||||
</p>
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
## 📊 **Framework Statistics**
|
||||
|
||||
| **Commands** | **Agents** | **Modes** | **MCP Servers** |
|
||||
|:------------:|:----------:|:---------:|:---------------:|
|
||||
| **30** | **20** | **7** | **8** |
|
||||
| Slash Commands | Specialized AI | Behavioral | Integrations |
|
||||
|
||||
30 slash commands covering the complete development lifecycle from brainstorming to deployment.
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
## 🎯 **Overview**
|
||||
|
||||
SuperClaude is a **meta-programming configuration framework** that transforms Claude Code into a structured development platform through behavioral instruction injection and component orchestration. It provides systematic workflow automation with powerful tools and intelligent agents.
|
||||
|
||||
|
||||
## Disclaimer
|
||||
|
||||
This project is not affiliated with or endorsed by Anthropic.
|
||||
Claude Code is a product built and maintained by [Anthropic](https://www.anthropic.com/).
|
||||
|
||||
## 📖 **For Developers & Contributors**
|
||||
|
||||
**Essential documentation for working with SuperClaude Framework:**
|
||||
|
||||
| Document | Purpose | When to Read |
|
||||
|----------|---------|--------------|
|
||||
| **[PLANNING.md](PLANNING.md)** | Architecture, design principles, absolute rules | Session start, before implementation |
|
||||
| **[TASK.md](TASK.md)** | Current tasks, priorities, backlog | Daily, before starting work |
|
||||
| **[KNOWLEDGE.md](KNOWLEDGE.md)** | Accumulated insights, best practices, troubleshooting | When encountering issues, learning patterns |
|
||||
| **[CONTRIBUTING.md](CONTRIBUTING.md)** | Contribution guidelines, workflow | Before submitting PRs |
|
||||
| **[Commands Reference](docs/user-guide/commands.md)** | Complete reference for all 30 `/sc:*` commands with syntax, examples, workflows, and decision guides | Learning SuperClaude, choosing the right command |
|
||||
|
||||
> **💡 Pro Tip**: Claude Code reads these files at session start to ensure consistent, high-quality development aligned with project standards.
|
||||
>
|
||||
> **📚 New to SuperClaude?** Start with [Commands Reference](docs/user-guide/commands.md) — it contains visual decision trees, detailed command comparisons, and workflow examples to help you understand which commands to use and when.
|
||||
|
||||
## ⚡ **Quick Installation**
|
||||
|
||||
> **IMPORTANT**: The TypeScript plugin system described in older documentation is
|
||||
> not yet available (planned for v5.0). For current installation
|
||||
> instructions, please follow the steps below for v4.x.
|
||||
|
||||
### **Current Stable Version (v4.3.0)**
|
||||
|
||||
SuperClaude currently uses slash commands.
|
||||
|
||||
**Option 1: pipx (Recommended)**
|
||||
```bash
|
||||
# Install from PyPI
|
||||
pipx install superclaude
|
||||
|
||||
# Install commands (installs all 30 slash commands)
|
||||
superclaude install
|
||||
|
||||
# Install MCP servers (optional, for enhanced capabilities)
|
||||
superclaude mcp --list # List available MCP servers
|
||||
superclaude mcp # Interactive installation
|
||||
superclaude mcp --servers tavily --servers context7 # Install specific servers
|
||||
|
||||
# Verify installation
|
||||
superclaude install --list
|
||||
superclaude doctor
|
||||
```
|
||||
|
||||
After installation, restart Claude Code to use 30 commands including:
|
||||
- `/sc:research` - Deep web research (enhanced with Tavily MCP)
|
||||
- `/sc:brainstorm` - Structured brainstorming
|
||||
- `/sc:implement` - Code implementation
|
||||
- `/sc:test` - Testing workflows
|
||||
- `/sc:pm` - Project management
|
||||
- `/sc` - Show all 30 available commands
|
||||
|
||||
**Option 2: Direct Installation from Git**
|
||||
```bash
|
||||
# Clone the repository
|
||||
git clone https://github.com/SuperClaude-Org/SuperClaude_Framework.git
|
||||
cd SuperClaude_Framework
|
||||
|
||||
# Run the installation script
|
||||
./install.sh
|
||||
```
|
||||
|
||||
### **Coming in v5.0 (In Development)**
|
||||
|
||||
We are actively working on a new TypeScript plugin system (see issue [#419](https://github.com/SuperClaude-Org/SuperClaude_Framework/issues/419) for details). When released, installation will be simplified to:
|
||||
|
||||
```bash
|
||||
# This feature is not yet available
|
||||
/plugin marketplace add SuperClaude-Org/superclaude-plugin-marketplace
|
||||
/plugin install superclaude
|
||||
```
|
||||
|
||||
**Status**: In development. No ETA has been set.
|
||||
|
||||
### **Enhanced Performance (Optional MCPs)**
|
||||
|
||||
For **2-3x faster** execution and **30-50% fewer tokens**, optionally install MCP servers:
|
||||
|
||||
```bash
|
||||
# Optional MCP servers for enhanced performance (via airis-mcp-gateway):
|
||||
# - Serena: Code understanding (2-3x faster)
|
||||
# - Sequential: Token-efficient reasoning (30-50% fewer tokens)
|
||||
# - Tavily: Web search for Deep Research
|
||||
# - Context7: Official documentation lookup
|
||||
# - Mindbase: Semantic search across all conversations (optional enhancement)
|
||||
|
||||
# Note: Error learning available via built-in ReflexionMemory (no installation required)
|
||||
# Mindbase provides semantic search enhancement (requires "recommended" profile)
|
||||
# Install MCP servers: https://github.com/agiletec-inc/airis-mcp-gateway
|
||||
# See docs/mcp/mcp-integration-policy.md for details
|
||||
```
|
||||
|
||||
**Performance Comparison:**
|
||||
- **Without MCPs**: Fully functional, standard performance ✅
|
||||
- **With MCPs**: 2-3x faster, 30-50% fewer tokens ⚡
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
## 💖 **Support the Project**
|
||||
|
||||
> Hey, let's be real - maintaining SuperClaude takes time and resources.
|
||||
>
|
||||
> *The Claude Max subscription alone runs $100/month for testing, and that's before counting the hours spent on documentation, bug fixes, and feature development.*
|
||||
> *If you're finding value in SuperClaude for your daily work, consider supporting the project.*
|
||||
> *Even a few dollars helps cover the basics and keeps development active.*
|
||||
>
|
||||
> Every contributor matters, whether through code, feedback, or support. Thanks for being part of this community! 🙏
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center" width="33%">
|
||||
|
||||
### ☕ **Ko-fi**
|
||||
[](https://ko-fi.com/superclaude)
|
||||
|
||||
*One-time contributions*
|
||||
|
||||
</td>
|
||||
<td align="center" width="33%">
|
||||
|
||||
### 🎯 **Patreon**
|
||||
[](https://patreon.com/superclaude)
|
||||
|
||||
*Monthly support*
|
||||
|
||||
</td>
|
||||
<td align="center" width="33%">
|
||||
|
||||
### 💜 **GitHub**
|
||||
[](https://github.com/sponsors/SuperClaude-Org)
|
||||
|
||||
*Flexible tiers*
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
### **Your Support Enables:**
|
||||
|
||||
| Item | Cost/Impact |
|
||||
|------|-------------|
|
||||
| 🔬 **Claude Max Testing** | $100/month for validation & testing |
|
||||
| ⚡ **Feature Development** | New capabilities & improvements |
|
||||
| 📚 **Documentation** | Comprehensive guides & examples |
|
||||
| 🤝 **Community Support** | Quick issue responses & help |
|
||||
| 🔧 **MCP Integration** | Testing new server connections |
|
||||
| 🌐 **Infrastructure** | Hosting & deployment costs |
|
||||
|
||||
> **Note:** No pressure though - the framework stays open source regardless. Just knowing people use and appreciate it is motivating. Contributing code, documentation, or spreading the word helps too! 🙏
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
## 🎉 **What's New in v4.1**
|
||||
|
||||
> *Version 4.1 focuses on stabilizing the slash command architecture, enhancing agent capabilities, and improving documentation.*
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%">
|
||||
|
||||
### 🤖 **Smarter Agent System**
|
||||
**20 specialized agents** with domain expertise:
|
||||
- PM Agent ensures continuous learning through systematic documentation
|
||||
- Deep Research agent for autonomous web research
|
||||
- Security engineer catches real vulnerabilities
|
||||
- Frontend architect understands UI patterns
|
||||
- Automatic coordination based on context
|
||||
- Domain-specific expertise on demand
|
||||
|
||||
</td>
|
||||
<td width="50%">
|
||||
|
||||
### ⚡ **Optimized Performance**
|
||||
**Smaller framework, bigger projects:**
|
||||
- Reduced framework footprint
|
||||
- More context for your code
|
||||
- Longer conversations possible
|
||||
- Complex operations enabled
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%">
|
||||
|
||||
### 🔧 **MCP Server Integration**
|
||||
**8 powerful servers** with easy CLI installation:
|
||||
|
||||
```bash
|
||||
# List available MCP servers
|
||||
superclaude mcp --list
|
||||
|
||||
# Install specific servers
|
||||
superclaude mcp --servers tavily context7
|
||||
|
||||
# Interactive installation
|
||||
superclaude mcp
|
||||
```
|
||||
|
||||
**Available servers:**
|
||||
- **Tavily** → Primary web search (Deep Research)
|
||||
- **Context7** → Official documentation lookup
|
||||
- **Sequential-Thinking** → Multi-step reasoning
|
||||
- **Serena** → Session persistence & memory
|
||||
- **Playwright** → Cross-browser automation
|
||||
- **Magic** → UI component generation
|
||||
- **Morphllm-Fast-Apply** → Context-aware code modifications
|
||||
- **Chrome DevTools** → Performance analysis
|
||||
|
||||
</td>
|
||||
<td width="50%">
|
||||
|
||||
### 🎯 **Behavioral Modes**
|
||||
**7 adaptive modes** for different contexts:
|
||||
- **Brainstorming** → Asks right questions
|
||||
- **Business Panel** → Multi-expert strategic analysis
|
||||
- **Deep Research** → Autonomous web research
|
||||
- **Orchestration** → Efficient tool coordination
|
||||
- **Token-Efficiency** → 30-50% context savings
|
||||
- **Task Management** → Systematic organization
|
||||
- **Introspection** → Meta-cognitive analysis
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%">
|
||||
|
||||
### 📚 **Documentation Overhaul**
|
||||
**Complete rewrite** for developers:
|
||||
- Real examples & use cases
|
||||
- Common pitfalls documented
|
||||
- Practical workflows included
|
||||
- Better navigation structure
|
||||
|
||||
</td>
|
||||
<td width="50%">
|
||||
|
||||
### 🧪 **Enhanced Stability**
|
||||
**Focus on reliability:**
|
||||
- Bug fixes for core commands
|
||||
- Improved test coverage
|
||||
- More robust error handling
|
||||
- CI/CD pipeline improvements
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
## 🔬 **Deep Research Capabilities**
|
||||
|
||||
### **Autonomous Web Research Aligned with DR Agent Architecture**
|
||||
|
||||
SuperClaude v4.2 introduces comprehensive Deep Research capabilities, enabling autonomous, adaptive, and intelligent web research.
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%">
|
||||
|
||||
### 🎯 **Adaptive Planning**
|
||||
**Three intelligent strategies:**
|
||||
- **Planning-Only**: Direct execution for clear queries
|
||||
- **Intent-Planning**: Clarification for ambiguous requests
|
||||
- **Unified**: Collaborative plan refinement (default)
|
||||
|
||||
</td>
|
||||
<td width="50%">
|
||||
|
||||
### 🔄 **Multi-Hop Reasoning**
|
||||
**Up to 5 iterative searches:**
|
||||
- Entity expansion (Paper → Authors → Works)
|
||||
- Concept deepening (Topic → Details → Examples)
|
||||
- Temporal progression (Current → Historical)
|
||||
- Causal chains (Effect → Cause → Prevention)
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%">
|
||||
|
||||
### 📊 **Quality Scoring**
|
||||
**Confidence-based validation:**
|
||||
- Source credibility assessment (0.0-1.0)
|
||||
- Coverage completeness tracking
|
||||
- Synthesis coherence evaluation
|
||||
- Minimum threshold: 0.6, Target: 0.8
|
||||
|
||||
</td>
|
||||
<td width="50%">
|
||||
|
||||
### 🧠 **Case-Based Learning**
|
||||
**Cross-session intelligence:**
|
||||
- Pattern recognition and reuse
|
||||
- Strategy optimization over time
|
||||
- Successful query formulations saved
|
||||
- Performance improvement tracking
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
### **Research Command Usage**
|
||||
|
||||
```bash
|
||||
# Basic research with automatic depth
|
||||
/research "latest AI developments 2024"
|
||||
|
||||
# Controlled research depth (via options in TypeScript)
|
||||
/research "quantum computing breakthroughs" # depth: exhaustive
|
||||
|
||||
# Specific strategy selection
|
||||
/research "market analysis" # strategy: planning-only
|
||||
|
||||
# Domain-filtered research (Tavily MCP integration)
|
||||
/research "React patterns" # domains: reactjs.org,github.com
|
||||
```
|
||||
|
||||
### **Research Depth Levels**
|
||||
|
||||
| Depth | Sources | Hops | Time | Best For |
|
||||
|:-----:|:-------:|:----:|:----:|----------|
|
||||
| **Quick** | 5-10 | 1 | ~2min | Quick facts, simple queries |
|
||||
| **Standard** | 10-20 | 3 | ~5min | General research (default) |
|
||||
| **Deep** | 20-40 | 4 | ~8min | Comprehensive analysis |
|
||||
| **Exhaustive** | 40+ | 5 | ~10min | Academic-level research |
|
||||
|
||||
### **Integrated Tool Orchestration**
|
||||
|
||||
The Deep Research system intelligently coordinates multiple tools:
|
||||
- **Tavily MCP**: Primary web search and discovery
|
||||
- **Playwright MCP**: Complex content extraction
|
||||
- **Sequential MCP**: Multi-step reasoning and synthesis
|
||||
- **Serena MCP**: Memory and learning persistence
|
||||
- **Context7 MCP**: Technical documentation lookup
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
## 📚 **Documentation**
|
||||
|
||||
### **Complete Guide to SuperClaude**
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th align="center">🚀 Getting Started</th>
|
||||
<th align="center">📖 User Guides</th>
|
||||
<th align="center">🛠️ Developer Resources</th>
|
||||
<th align="center">📋 Reference</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td valign="top">
|
||||
|
||||
- 📝 [**Quick Start Guide**](docs/getting-started/quick-start.md)
|
||||
*Get up and running fast*
|
||||
|
||||
- 💾 [**Installation Guide**](docs/getting-started/installation.md)
|
||||
*Detailed setup instructions*
|
||||
|
||||
</td>
|
||||
<td valign="top">
|
||||
|
||||
- 🎯 [**Slash Commands**](docs/reference/commands-list.md)
|
||||
*All 30 commands organized by category*
|
||||
|
||||
- 🤖 [**Agents Guide**](docs/user-guide/agents.md)
|
||||
*20 specialized agents*
|
||||
|
||||
- 🎨 [**Behavioral Modes**](docs/user-guide/modes.md)
|
||||
*7 adaptive modes*
|
||||
|
||||
- 🚩 [**Flags Guide**](docs/user-guide/flags.md)
|
||||
*Control behaviors*
|
||||
|
||||
- 🔧 [**MCP Servers**](docs/user-guide/mcp-servers.md)
|
||||
*8 server integrations*
|
||||
|
||||
- 💼 [**Session Management**](docs/user-guide/session-management.md)
|
||||
*Save & restore state*
|
||||
|
||||
</td>
|
||||
<td valign="top">
|
||||
|
||||
- 🏗️ [**Technical Architecture**](docs/developer-guide/technical-architecture.md)
|
||||
*System design details*
|
||||
|
||||
- 💻 [**Contributing Code**](docs/developer-guide/contributing-code.md)
|
||||
*Development workflow*
|
||||
|
||||
- 🧪 [**Testing & Debugging**](docs/developer-guide/testing-debugging.md)
|
||||
*Quality assurance*
|
||||
|
||||
</td>
|
||||
<td valign="top">
|
||||
- 📓 [**Examples Cookbook**](docs/reference/examples-cookbook.md)
|
||||
*Real-world recipes*
|
||||
|
||||
- 🔍 [**Troubleshooting**](docs/reference/troubleshooting.md)
|
||||
*Common issues & fixes*
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
## 🤝 **Contributing**
|
||||
|
||||
### **Join the SuperClaude Community**
|
||||
|
||||
We welcome contributions of all kinds! Here's how you can help:
|
||||
|
||||
| Priority | Area | Description |
|
||||
|:--------:|------|-------------|
|
||||
| 📝 **High** | Documentation | Improve guides, add examples, fix typos |
|
||||
| 🔧 **High** | MCP Integration | Add server configs, test integrations |
|
||||
| 🎯 **Medium** | Workflows | Create command patterns & recipes |
|
||||
| 🧪 **Medium** | Testing | Add tests, validate features |
|
||||
| 🌐 **Low** | i18n | Translate docs to other languages |
|
||||
|
||||
<p align="center">
|
||||
<a href="CONTRIBUTING.md">
|
||||
<img src="https://img.shields.io/badge/📖_Read-Contributing_Guide-blue" alt="Contributing Guide">
|
||||
</a>
|
||||
<a href="https://github.com/SuperClaude-Org/SuperClaude_Framework/graphs/contributors">
|
||||
<img src="https://img.shields.io/badge/👥_View-All_Contributors-green" alt="Contributors">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
## ⚖️ **License**
|
||||
|
||||
This project is licensed under the **MIT License** - see the [LICENSE](LICENSE) file for details.
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/License-MIT-yellow.svg?" alt="MIT License">
|
||||
</p>
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
## ⭐ **Star History**
|
||||
|
||||
<a href="https://www.star-history.com/#SuperClaude-Org/SuperClaude_Framework&Timeline">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=SuperClaude-Org/SuperClaude_Framework&type=Timeline&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=SuperClaude-Org/SuperClaude_Framework&type=Timeline" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=SuperClaude-Org/SuperClaude_Framework&type=Timeline" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
### **🚀 Built with passion by the SuperClaude community**
|
||||
|
||||
<p align="center">
|
||||
<sub>Made with ❤️ for developers who push boundaries</sub>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="#-superclaude-framework">Back to Top ↑</a>
|
||||
</p>
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## 📋 **All 30 Commands**
|
||||
|
||||
<details>
|
||||
<summary><b>Click to expand full command list</b></summary>
|
||||
|
||||
### 🧠 Planning & Design (4)
|
||||
- `/brainstorm` - Structured brainstorming
|
||||
- `/design` - System architecture
|
||||
- `/estimate` - Time/effort estimation
|
||||
- `/spec-panel` - Specification analysis
|
||||
|
||||
### 💻 Development (5)
|
||||
- `/implement` - Code implementation
|
||||
- `/build` - Build workflows
|
||||
- `/improve` - Code improvements
|
||||
- `/cleanup` - Refactoring
|
||||
- `/explain` - Code explanation
|
||||
|
||||
### 🧪 Testing & Quality (4)
|
||||
- `/test` - Test generation
|
||||
- `/analyze` - Code analysis
|
||||
- `/troubleshoot` - Debugging
|
||||
- `/reflect` - Retrospectives
|
||||
|
||||
### 📚 Documentation (2)
|
||||
- `/document` - Doc generation
|
||||
- `/help` - Command help
|
||||
|
||||
### 🔧 Version Control (1)
|
||||
- `/git` - Git operations
|
||||
|
||||
### 📊 Project Management (3)
|
||||
- `/pm` - Project management
|
||||
- `/task` - Task tracking
|
||||
- `/workflow` - Workflow automation
|
||||
|
||||
### 🔍 Research & Analysis (2)
|
||||
- `/research` - Deep web research
|
||||
- `/business-panel` - Business analysis
|
||||
|
||||
### 🎯 Utilities (9)
|
||||
- `/agent` - AI agents
|
||||
- `/index-repo` - Repository indexing
|
||||
- `/index` - Indexing alias
|
||||
- `/recommend` - Command recommendations
|
||||
- `/select-tool` - Tool selection
|
||||
- `/spawn` - Parallel tasks
|
||||
- `/load` - Load sessions
|
||||
- `/save` - Save sessions
|
||||
- `/sc` - Show all commands
|
||||
|
||||
[**📖 View Detailed Command Reference →**](docs/reference/commands-list.md)
|
||||
|
||||
</details>
|
||||
|
||||
@@ -1,45 +1,34 @@
|
||||
<!-- WEHUB_ZH_README -->
|
||||
> [!NOTE]
|
||||
> 本文档由 WeHub 基于上游 README 翻译整理,属于社区翻译,非官方中文文档。
|
||||
> [English](./README.en.md) · [原始项目](https://github.com/SuperClaude-Org/SuperClaude_Framework) · [上游 README](https://github.com/SuperClaude-Org/SuperClaude_Framework/blob/HEAD/README.md)
|
||||
> 原作者、版权与许可证归属以原始项目及本仓库 LICENSE 文件为准。
|
||||
|
||||
<div align="center">
|
||||
|
||||
# 🚀 SuperClaude Framework
|
||||
# 🚀 SuperClaude 框架
|
||||
|
||||
[](https://smithery.ai/skills?ns=SuperClaude-Org&utm_source=github&utm_medium=badge)
|
||||
|
||||
|
||||
### **Transform Claude Code into a Structured Development Platform**
|
||||
### **将Claude Code转换为结构化开发平台**
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/hesreallyhim/awesome-claude-code/">
|
||||
<img src="https://awesome.re/mentioned-badge-flat.svg" alt="Mentioned in Awesome Claude Code">
|
||||
</a>
|
||||
<a href="https://github.com/SuperClaude-Org/SuperGemini_Framework" target="_blank">
|
||||
<img src="https://img.shields.io/badge/Try-SuperGemini_Framework-blue" alt="Try SuperGemini Framework"/>
|
||||
</a>
|
||||
<a href="https://github.com/SuperClaude-Org/SuperQwen_Framework" target="_blank">
|
||||
<img src="https://img.shields.io/badge/Try-SuperQwen_Framework-orange" alt="Try SuperQwen Framework"/>
|
||||
</a>
|
||||
<img src="https://img.shields.io/badge/version-4.1.9-blue" alt="Version">
|
||||
<a href="https://github.com/SuperClaude-Org/SuperClaude_Framework/actions/workflows/test.yml">
|
||||
<img src="https://github.com/SuperClaude-Org/SuperClaude_Framework/actions/workflows/test.yml/badge.svg" alt="Tests">
|
||||
</a>
|
||||
<img src="https://img.shields.io/badge/version-4.3.0-blue" alt="Version">
|
||||
<img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License">
|
||||
<img src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg" alt="PRs Welcome">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://superclaude.netlify.app/">
|
||||
<img src="https://img.shields.io/badge/🌐_Visit_Website-blue" alt="Website">
|
||||
<img src="https://img.shields.io/badge/🌐_访问网站-blue" alt="Website">
|
||||
</a>
|
||||
<a href="https://pypi.org/project/superclaude/">
|
||||
<img src="https://img.shields.io/pypi/v/SuperClaude.svg?" alt="PyPI">
|
||||
</a>
|
||||
<a href="https://pepy.tech/projects/superclaude">
|
||||
<img src="https://static.pepy.tech/personalized-badge/superclaude?period=total&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=GREEN&left_text=downloads" alt="PyPI sats">
|
||||
</a>
|
||||
<a href="https://www.npmjs.com/package/@bifrost_inc/superclaude">
|
||||
<img src="https://img.shields.io/npm/v/@bifrost_inc/superclaude.svg" alt="npm">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<!-- Language Selector -->
|
||||
<p align="center">
|
||||
<a href="README.md">
|
||||
<img src="https://img.shields.io/badge/🇺🇸_English-blue" alt="English">
|
||||
@@ -53,11 +42,11 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="#-quick-installation">Quick Start</a> •
|
||||
<a href="#-support-the-project">Support</a> •
|
||||
<a href="#-whats-new-in-v4">Features</a> •
|
||||
<a href="#-documentation">Docs</a> •
|
||||
<a href="#-contributing">Contributing</a>
|
||||
<a href="#-快速安装">快速开始</a> •
|
||||
<a href="#-支持项目">支持项目</a> •
|
||||
<a href="#-v4版本新功能">新功能</a> •
|
||||
<a href="#-文档">文档</a> •
|
||||
<a href="#-贡献">贡献</a>
|
||||
</p>
|
||||
|
||||
</div>
|
||||
@@ -66,14 +55,14 @@
|
||||
|
||||
<div align="center">
|
||||
|
||||
## 📊 **Framework Statistics**
|
||||
## 📊 **框架统计**
|
||||
|
||||
| **Commands** | **Agents** | **Modes** | **MCP Servers** |
|
||||
| **命令** | **智能体** | **模式** | **MCP服务器** |
|
||||
|:------------:|:----------:|:---------:|:---------------:|
|
||||
| **30** | **16** | **7** | **8** |
|
||||
| Slash Commands | Specialized AI | Behavioral | Integrations |
|
||||
| 斜杠命令 | 专业AI | 行为模式 | 集成服务 |
|
||||
|
||||
30 slash commands covering the complete development lifecycle from brainstorming to deployment.
|
||||
30个斜杠命令覆盖从头脑风暴到部署的完整开发生命周期。
|
||||
|
||||
</div>
|
||||
|
||||
@@ -81,111 +70,102 @@
|
||||
|
||||
<div align="center">
|
||||
|
||||
## 🎯 **Overview**
|
||||
## 🎯 **概述**
|
||||
|
||||
SuperClaude is a **meta-programming configuration framework** that transforms Claude Code into a structured development platform through behavioral instruction injection and component orchestration. It provides systematic workflow automation with powerful tools and intelligent agents.
|
||||
SuperClaude是一个**元编程配置框架**,通过行为指令注入和组件编排,将Claude Code转换为结构化开发平台。它提供系统化的工作流自动化,配备强大的工具和智能代理。
|
||||
|
||||
|
||||
## Disclaimer
|
||||
## 免责声明
|
||||
|
||||
This project is not affiliated with or endorsed by Anthropic.
|
||||
Claude Code is a product built and maintained by [Anthropic](https://www.anthropic.com/).
|
||||
本项目与Anthropic无关联或认可。
|
||||
Claude Code是由[Anthropic](https://www.anthropic.com/)构建和维护的产品。
|
||||
|
||||
## 📖 **For Developers & Contributors**
|
||||
## 📖 **开发者与贡献者指南**
|
||||
|
||||
**Essential documentation for working with SuperClaude Framework:**
|
||||
**使用SuperClaude框架的必备文档:**
|
||||
|
||||
| Document | Purpose | When to Read |
|
||||
| 文档 | 用途 | 何时阅读 |
|
||||
|----------|---------|--------------|
|
||||
| **[PLANNING.md](PLANNING.md)** | Architecture, design principles, absolute rules | Session start, before implementation |
|
||||
| **[TASK.md](TASK.md)** | Current tasks, priorities, backlog | Daily, before starting work |
|
||||
| **[KNOWLEDGE.md](KNOWLEDGE.md)** | Accumulated insights, best practices, troubleshooting | When encountering issues, learning patterns |
|
||||
| **[CONTRIBUTING.md](CONTRIBUTING.md)** | Contribution guidelines, workflow | Before submitting PRs |
|
||||
| **[Commands Reference](docs/user-guide/commands.md)** | Complete reference for all 30 `/sc:*` commands with syntax, examples, workflows, and decision guides | Learning SuperClaude, choosing the right command |
|
||||
| **[PLANNING.md](PLANNING.md)** | 架构、设计原则、绝对规则 | 会话开始、实施前 |
|
||||
| **[TASK.md](TASK.md)** | 当前任务、优先级、待办事项 | 每天、开始工作前 |
|
||||
| **[KNOWLEDGE.md](KNOWLEDGE.md)** | 积累的见解、最佳实践、故障排除 | 遇到问题时、学习模式 |
|
||||
| **[CONTRIBUTING.md](CONTRIBUTING.md)** | 贡献指南、工作流程 | 提交PR前 |
|
||||
|
||||
> **💡 Pro Tip**: Claude Code reads these files at session start to ensure consistent, high-quality development aligned with project standards.
|
||||
>
|
||||
> **📚 New to SuperClaude?** Start with [Commands Reference](docs/user-guide/commands.md) — it contains visual decision trees, detailed command comparisons, and workflow examples to help you understand which commands to use and when.
|
||||
> **💡 专业提示**:Claude Code在会话开始时会读取这些文件,以确保符合项目标准的一致、高质量开发。
|
||||
|
||||
## ⚡ **Quick Installation**
|
||||
## ⚡ **快速安装**
|
||||
|
||||
> **IMPORTANT**: The TypeScript plugin system described in older documentation is
|
||||
> not yet available (planned for v5.0). For current installation
|
||||
> instructions, please follow the steps below for v4.x.
|
||||
> **重要**:旧文档中描述的TypeScript插件系统
|
||||
> 尚未可用(计划在v5.0中推出)。请按照以下v4.x的
|
||||
> 当前安装说明操作。
|
||||
|
||||
### **Current Stable Version (v4.1.9)**
|
||||
### **当前稳定版本 (v4.3.0)**
|
||||
|
||||
SuperClaude currently uses slash commands.
|
||||
SuperClaude目前使用斜杠命令。
|
||||
|
||||
**Option 1: pipx (Recommended)**
|
||||
**选项1:pipx(推荐)**
|
||||
```bash
|
||||
# Install from PyPI
|
||||
# 从PyPI安装
|
||||
pipx install superclaude
|
||||
|
||||
# Install commands (installs all 30 slash commands)
|
||||
# 安装命令(安装 /research, /index-repo, /agent, /recommend)
|
||||
superclaude install
|
||||
|
||||
# Install MCP servers (optional, for enhanced capabilities)
|
||||
superclaude mcp --list # List available MCP servers
|
||||
superclaude mcp # Interactive installation
|
||||
superclaude mcp --servers tavily --servers context7 # Install specific servers
|
||||
|
||||
# Verify installation
|
||||
# 验证安装
|
||||
superclaude install --list
|
||||
superclaude doctor
|
||||
```
|
||||
|
||||
After installation, restart Claude Code to use 30 commands including:
|
||||
- `/sc:research` - Deep web research (enhanced with Tavily MCP)
|
||||
- `/sc:brainstorm` - Structured brainstorming
|
||||
- `/sc:implement` - Code implementation
|
||||
- `/sc:test` - Testing workflows
|
||||
- `/sc:pm` - Project management
|
||||
- `/sc` - Show all 30 available commands
|
||||
安装后,重启Claude Code以使用命令:
|
||||
- `/sc:research` - 并行搜索的深度网络研究
|
||||
- `/sc:index-repo` - 用于上下文优化的仓库索引
|
||||
- `/sc:agent` - 专业AI智能体
|
||||
- `/sc:recommend` - 命令推荐
|
||||
- `/sc` - 显示所有可用的SuperClaude命令
|
||||
|
||||
**Option 2: Direct Installation from Git**
|
||||
**选项2:从Git直接安装**
|
||||
```bash
|
||||
# Clone the repository
|
||||
# 克隆仓库
|
||||
git clone https://github.com/SuperClaude-Org/SuperClaude_Framework.git
|
||||
cd SuperClaude_Framework
|
||||
|
||||
# Run the installation script
|
||||
# 运行安装脚本
|
||||
./install.sh
|
||||
```
|
||||
|
||||
### **Coming in v5.0 (In Development)**
|
||||
### **v5.0即将推出(开发中)**
|
||||
|
||||
We are actively working on a new TypeScript plugin system (see issue [#419](https://github.com/SuperClaude-Org/SuperClaude_Framework/issues/419) for details). When released, installation will be simplified to:
|
||||
我们正在积极开发新的TypeScript插件系统(详见issue [#419](https://github.com/SuperClaude-Org/SuperClaude_Framework/issues/419))。发布后,安装将简化为:
|
||||
|
||||
```bash
|
||||
# This feature is not yet available
|
||||
# 此功能尚未可用
|
||||
/plugin marketplace add SuperClaude-Org/superclaude-plugin-marketplace
|
||||
/plugin install superclaude
|
||||
```
|
||||
|
||||
**Status**: In development. No ETA has been set.
|
||||
**状态**:开发中。尚未设定ETA。
|
||||
|
||||
### **Enhanced Performance (Optional MCPs)**
|
||||
### **增强性能(可选MCP)**
|
||||
|
||||
For **2-3x faster** execution and **30-50% fewer tokens**, optionally install MCP servers:
|
||||
要获得**2-3倍**更快的执行速度和**30-50%**更少的token消耗,可选择安装MCP服务器:
|
||||
|
||||
```bash
|
||||
# Optional MCP servers for enhanced performance (via airis-mcp-gateway):
|
||||
# - Serena: Code understanding (2-3x faster)
|
||||
# - Sequential: Token-efficient reasoning (30-50% fewer tokens)
|
||||
# - Tavily: Web search for Deep Research
|
||||
# - Context7: Official documentation lookup
|
||||
# - Mindbase: Semantic search across all conversations (optional enhancement)
|
||||
# 用于增强性能的可选MCP服务器(通过airis-mcp-gateway):
|
||||
# - Serena: 代码理解(快2-3倍)
|
||||
# - Sequential: Token高效推理(减少30-50% token)
|
||||
# - Tavily: 用于深度研究的网络搜索
|
||||
# - Context7: 官方文档查找
|
||||
# - Mindbase: 跨所有对话的语义搜索(可选增强)
|
||||
|
||||
# Note: Error learning available via built-in ReflexionMemory (no installation required)
|
||||
# Mindbase provides semantic search enhancement (requires "recommended" profile)
|
||||
# Install MCP servers: https://github.com/agiletec-inc/airis-mcp-gateway
|
||||
# See docs/mcp/mcp-integration-policy.md for details
|
||||
# 注意:错误学习通过内置的ReflexionMemory提供(无需安装)
|
||||
# Mindbase提供语义搜索增强(需要"recommended"配置文件)
|
||||
# 安装MCP服务器:https://github.com/agiletec-inc/airis-mcp-gateway
|
||||
# 详见 docs/mcp/mcp-integration-policy.md
|
||||
```
|
||||
|
||||
**Performance Comparison:**
|
||||
- **Without MCPs**: Fully functional, standard performance ✅
|
||||
- **With MCPs**: 2-3x faster, 30-50% fewer tokens ⚡
|
||||
**性能对比:**
|
||||
- **不使用MCP**:功能完整,标准性能 ✅
|
||||
- **使用MCP**:快2-3倍,减少30-50% token ⚡
|
||||
|
||||
</div>
|
||||
|
||||
@@ -193,15 +173,15 @@ For **2-3x faster** execution and **30-50% fewer tokens**, optionally install MC
|
||||
|
||||
<div align="center">
|
||||
|
||||
## 💖 **Support the Project**
|
||||
## 💖 **支持项目**
|
||||
|
||||
> Hey, let's be real - maintaining SuperClaude takes time and resources.
|
||||
> 说实话,维护SuperClaude需要时间和资源。
|
||||
>
|
||||
> *The Claude Max subscription alone runs $100/month for testing, and that's before counting the hours spent on documentation, bug fixes, and feature development.*
|
||||
> *If you're finding value in SuperClaude for your daily work, consider supporting the project.*
|
||||
> *Even a few dollars helps cover the basics and keeps development active.*
|
||||
> *仅Claude Max订阅每月就要100美元用于测试,这还不包括在文档、bug修复和功能开发上花费的时间。*
|
||||
> *如果您在日常工作中发现SuperClaude的价值,请考虑支持这个项目。*
|
||||
> *哪怕几美元也能帮助覆盖基础成本并保持开发活跃。*
|
||||
>
|
||||
> Every contributor matters, whether through code, feedback, or support. Thanks for being part of this community! 🙏
|
||||
> 每个贡献者都很重要,无论是代码、反馈还是支持。感谢成为这个社区的一员!🙏
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
@@ -210,7 +190,7 @@ For **2-3x faster** execution and **30-50% fewer tokens**, optionally install MC
|
||||
### ☕ **Ko-fi**
|
||||
[](https://ko-fi.com/superclaude)
|
||||
|
||||
*One-time contributions*
|
||||
*一次性贡献*
|
||||
|
||||
</td>
|
||||
<td align="center" width="33%">
|
||||
@@ -218,7 +198,7 @@ For **2-3x faster** execution and **30-50% fewer tokens**, optionally install MC
|
||||
### 🎯 **Patreon**
|
||||
[](https://patreon.com/superclaude)
|
||||
|
||||
*Monthly support*
|
||||
*月度支持*
|
||||
|
||||
</td>
|
||||
<td align="center" width="33%">
|
||||
@@ -226,24 +206,24 @@ For **2-3x faster** execution and **30-50% fewer tokens**, optionally install MC
|
||||
### 💜 **GitHub**
|
||||
[](https://github.com/sponsors/SuperClaude-Org)
|
||||
|
||||
*Flexible tiers*
|
||||
*灵活层级*
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
### **Your Support Enables:**
|
||||
### **您的支持使以下工作成为可能:**
|
||||
|
||||
| Item | Cost/Impact |
|
||||
| 项目 | 成本/影响 |
|
||||
|------|-------------|
|
||||
| 🔬 **Claude Max Testing** | $100/month for validation & testing |
|
||||
| ⚡ **Feature Development** | New capabilities & improvements |
|
||||
| 📚 **Documentation** | Comprehensive guides & examples |
|
||||
| 🤝 **Community Support** | Quick issue responses & help |
|
||||
| 🔧 **MCP Integration** | Testing new server connections |
|
||||
| 🌐 **Infrastructure** | Hosting & deployment costs |
|
||||
| 🔬 **Claude Max测试** | 每月100美元用于验证和测试 |
|
||||
| ⚡ **功能开发** | 新功能和改进 |
|
||||
| 📚 **文档编写** | 全面的指南和示例 |
|
||||
| 🤝 **社区支持** | 快速问题响应和帮助 |
|
||||
| 🔧 **MCP集成** | 测试新服务器连接 |
|
||||
| 🌐 **基础设施** | 托管和部署成本 |
|
||||
|
||||
> **Note:** No pressure though - the framework stays open source regardless. Just knowing people use and appreciate it is motivating. Contributing code, documentation, or spreading the word helps too! 🙏
|
||||
> **注意:** 不过没有压力——无论如何框架都会保持开源。仅仅知道有人在使用和欣赏它就很有激励作用。贡献代码、文档或传播消息也很有帮助!🙏
|
||||
|
||||
</div>
|
||||
|
||||
@@ -251,96 +231,83 @@ For **2-3x faster** execution and **30-50% fewer tokens**, optionally install MC
|
||||
|
||||
<div align="center">
|
||||
|
||||
## 🎉 **What's New in v4.1**
|
||||
## 🎉 **V4.1版本新功能**
|
||||
|
||||
> *Version 4.1 focuses on stabilizing the slash command architecture, enhancing agent capabilities, and improving documentation.*
|
||||
> *版本4.1专注于稳定斜杠命令架构、增强智能体能力和改进文档。*
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%">
|
||||
|
||||
### 🤖 **Smarter Agent System**
|
||||
**16 specialized agents** with domain expertise:
|
||||
- PM Agent ensures continuous learning through systematic documentation
|
||||
- Deep Research agent for autonomous web research
|
||||
- Security engineer catches real vulnerabilities
|
||||
- Frontend architect understands UI patterns
|
||||
- Automatic coordination based on context
|
||||
- Domain-specific expertise on demand
|
||||
### 🤖 **更智能的智能体系统**
|
||||
**16个专业智能体**具有领域专业知识:
|
||||
- PM Agent通过系统化文档确保持续学习
|
||||
- 深度研究智能体用于自主网络研究
|
||||
- 安全工程师发现真实漏洞
|
||||
- 前端架构师理解UI模式
|
||||
- 基于上下文的自动协调
|
||||
- 按需提供领域专业知识
|
||||
|
||||
</td>
|
||||
<td width="50%">
|
||||
|
||||
### ⚡ **Optimized Performance**
|
||||
**Smaller framework, bigger projects:**
|
||||
- Reduced framework footprint
|
||||
- More context for your code
|
||||
- Longer conversations possible
|
||||
- Complex operations enabled
|
||||
### ⚡ **优化性能**
|
||||
**更小的框架,更大的项目:**
|
||||
- 减少框架占用
|
||||
- 为您的代码提供更多上下文
|
||||
- 支持更长对话
|
||||
- 启用复杂操作
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%">
|
||||
|
||||
### 🔧 **MCP Server Integration**
|
||||
**8 powerful servers** with easy CLI installation:
|
||||
|
||||
```bash
|
||||
# List available MCP servers
|
||||
superclaude mcp --list
|
||||
|
||||
# Install specific servers
|
||||
superclaude mcp --servers tavily context7
|
||||
|
||||
# Interactive installation
|
||||
superclaude mcp
|
||||
```
|
||||
|
||||
**Available servers:**
|
||||
- **Tavily** → Primary web search (Deep Research)
|
||||
- **Context7** → Official documentation lookup
|
||||
- **Sequential-Thinking** → Multi-step reasoning
|
||||
- **Serena** → Session persistence & memory
|
||||
- **Playwright** → Cross-browser automation
|
||||
- **Magic** → UI component generation
|
||||
- **Morphllm-Fast-Apply** → Context-aware code modifications
|
||||
- **Chrome DevTools** → Performance analysis
|
||||
### 🔧 **MCP服务器集成**
|
||||
**8个强大服务器**(通过airis-mcp-gateway):
|
||||
- **Tavily** → 主要网络搜索(深度研究)
|
||||
- **Serena** → 会话持久化和内存
|
||||
- **Mindbase** → 跨会话学习(零占用)
|
||||
- **Sequential** → Token高效推理
|
||||
- **Context7** → 官方文档查找
|
||||
- **Playwright** → JavaScript重度内容提取
|
||||
- **Magic** → UI组件生成
|
||||
- **Chrome DevTools** → 性能分析
|
||||
|
||||
</td>
|
||||
<td width="50%">
|
||||
|
||||
### 🎯 **Behavioral Modes**
|
||||
**7 adaptive modes** for different contexts:
|
||||
- **Brainstorming** → Asks right questions
|
||||
- **Business Panel** → Multi-expert strategic analysis
|
||||
- **Deep Research** → Autonomous web research
|
||||
- **Orchestration** → Efficient tool coordination
|
||||
- **Token-Efficiency** → 30-50% context savings
|
||||
- **Task Management** → Systematic organization
|
||||
- **Introspection** → Meta-cognitive analysis
|
||||
### 🎯 **行为模式**
|
||||
**7种自适应模式**适应不同上下文:
|
||||
- **头脑风暴** → 提出正确问题
|
||||
- **商业面板** → 多专家战略分析
|
||||
- **深度研究** → 自主网络研究
|
||||
- **编排** → 高效工具协调
|
||||
- **令牌效率** → 30-50%上下文节省
|
||||
- **任务管理** → 系统化组织
|
||||
- **内省** → 元认知分析
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%">
|
||||
|
||||
### 📚 **Documentation Overhaul**
|
||||
**Complete rewrite** for developers:
|
||||
- Real examples & use cases
|
||||
- Common pitfalls documented
|
||||
- Practical workflows included
|
||||
- Better navigation structure
|
||||
### 📚 **文档全面改写**
|
||||
**为开发者完全重写:**
|
||||
- 真实示例和用例
|
||||
- 记录常见陷阱
|
||||
- 包含实用工作流
|
||||
- 更好的导航结构
|
||||
|
||||
</td>
|
||||
<td width="50%">
|
||||
|
||||
### 🧪 **Enhanced Stability**
|
||||
**Focus on reliability:**
|
||||
- Bug fixes for core commands
|
||||
- Improved test coverage
|
||||
- More robust error handling
|
||||
- CI/CD pipeline improvements
|
||||
### 🧪 **增强稳定性**
|
||||
**专注于可靠性:**
|
||||
- 核心命令的错误修复
|
||||
- 改进测试覆盖率
|
||||
- 更健壮的错误处理
|
||||
- CI/CD流水线改进
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
@@ -352,91 +319,91 @@ superclaude mcp
|
||||
|
||||
<div align="center">
|
||||
|
||||
## 🔬 **Deep Research Capabilities**
|
||||
## 🔬 **深度研究能力**
|
||||
|
||||
### **Autonomous Web Research Aligned with DR Agent Architecture**
|
||||
### **与DR智能体架构一致的自主网络研究**
|
||||
|
||||
SuperClaude v4.2 introduces comprehensive Deep Research capabilities, enabling autonomous, adaptive, and intelligent web research.
|
||||
SuperClaude v4.2引入了全面的深度研究能力,实现自主、自适应和智能的网络研究。
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%">
|
||||
|
||||
### 🎯 **Adaptive Planning**
|
||||
**Three intelligent strategies:**
|
||||
- **Planning-Only**: Direct execution for clear queries
|
||||
- **Intent-Planning**: Clarification for ambiguous requests
|
||||
- **Unified**: Collaborative plan refinement (default)
|
||||
### 🎯 **自适应规划**
|
||||
**三种智能策略:**
|
||||
- **仅规划**:对明确查询直接执行
|
||||
- **意图规划**:对模糊请求进行澄清
|
||||
- **统一**:协作式计划完善(默认)
|
||||
|
||||
</td>
|
||||
<td width="50%">
|
||||
|
||||
### 🔄 **Multi-Hop Reasoning**
|
||||
**Up to 5 iterative searches:**
|
||||
- Entity expansion (Paper → Authors → Works)
|
||||
- Concept deepening (Topic → Details → Examples)
|
||||
- Temporal progression (Current → Historical)
|
||||
- Causal chains (Effect → Cause → Prevention)
|
||||
### 🔄 **多跳推理**
|
||||
**最多5次迭代搜索:**
|
||||
- 实体扩展(论文 → 作者 → 作品)
|
||||
- 概念深化(主题 → 细节 → 示例)
|
||||
- 时间进展(当前 → 历史)
|
||||
- 因果链(效果 → 原因 → 预防)
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%">
|
||||
|
||||
### 📊 **Quality Scoring**
|
||||
**Confidence-based validation:**
|
||||
- Source credibility assessment (0.0-1.0)
|
||||
- Coverage completeness tracking
|
||||
- Synthesis coherence evaluation
|
||||
- Minimum threshold: 0.6, Target: 0.8
|
||||
### 📊 **质量评分**
|
||||
**基于置信度的验证:**
|
||||
- 来源可信度评估(0.0-1.0)
|
||||
- 覆盖完整性跟踪
|
||||
- 综合连贯性评估
|
||||
- 最低阈值:0.6,目标:0.8
|
||||
|
||||
</td>
|
||||
<td width="50%">
|
||||
|
||||
### 🧠 **Case-Based Learning**
|
||||
**Cross-session intelligence:**
|
||||
- Pattern recognition and reuse
|
||||
- Strategy optimization over time
|
||||
- Successful query formulations saved
|
||||
- Performance improvement tracking
|
||||
### 🧠 **基于案例的学习**
|
||||
**跨会话智能:**
|
||||
- 模式识别和重用
|
||||
- 随时间优化策略
|
||||
- 保存成功的查询公式
|
||||
- 性能改进跟踪
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
### **Research Command Usage**
|
||||
### **研究命令使用**
|
||||
|
||||
```bash
|
||||
# Basic research with automatic depth
|
||||
/research "latest AI developments 2024"
|
||||
# 使用自动深度的基本研究
|
||||
/research "2024年最新AI发展"
|
||||
|
||||
# Controlled research depth (via options in TypeScript)
|
||||
/research "quantum computing breakthroughs" # depth: exhaustive
|
||||
# 控制研究深度(通过TypeScript中的选项)
|
||||
/research "量子计算突破" # depth: exhaustive
|
||||
|
||||
# Specific strategy selection
|
||||
/research "market analysis" # strategy: planning-only
|
||||
# 特定策略选择
|
||||
/research "市场分析" # strategy: planning-only
|
||||
|
||||
# Domain-filtered research (Tavily MCP integration)
|
||||
/research "React patterns" # domains: reactjs.org,github.com
|
||||
# 领域过滤研究(Tavily MCP集成)
|
||||
/research "React模式" # domains: reactjs.org,github.com
|
||||
```
|
||||
|
||||
### **Research Depth Levels**
|
||||
### **研究深度级别**
|
||||
|
||||
| Depth | Sources | Hops | Time | Best For |
|
||||
| 深度 | 来源 | 跳数 | 时间 | 最适合 |
|
||||
|:-----:|:-------:|:----:|:----:|----------|
|
||||
| **Quick** | 5-10 | 1 | ~2min | Quick facts, simple queries |
|
||||
| **Standard** | 10-20 | 3 | ~5min | General research (default) |
|
||||
| **Deep** | 20-40 | 4 | ~8min | Comprehensive analysis |
|
||||
| **Exhaustive** | 40+ | 5 | ~10min | Academic-level research |
|
||||
| **快速** | 5-10 | 1 | ~2分钟 | 快速事实、简单查询 |
|
||||
| **标准** | 10-20 | 3 | ~5分钟 | 一般研究(默认) |
|
||||
| **深入** | 20-40 | 4 | ~8分钟 | 综合分析 |
|
||||
| **详尽** | 40+ | 5 | ~10分钟 | 学术级研究 |
|
||||
|
||||
### **Integrated Tool Orchestration**
|
||||
### **集成工具编排**
|
||||
|
||||
The Deep Research system intelligently coordinates multiple tools:
|
||||
- **Tavily MCP**: Primary web search and discovery
|
||||
- **Playwright MCP**: Complex content extraction
|
||||
- **Sequential MCP**: Multi-step reasoning and synthesis
|
||||
- **Serena MCP**: Memory and learning persistence
|
||||
- **Context7 MCP**: Technical documentation lookup
|
||||
深度研究系统智能协调多个工具:
|
||||
- **Tavily MCP**:主要网络搜索和发现
|
||||
- **Playwright MCP**:复杂内容提取
|
||||
- **Sequential MCP**:多步推理和综合
|
||||
- **Serena MCP**:内存和学习持久化
|
||||
- **Context7 MCP**:技术文档查找
|
||||
|
||||
</div>
|
||||
|
||||
@@ -444,66 +411,67 @@ The Deep Research system intelligently coordinates multiple tools:
|
||||
|
||||
<div align="center">
|
||||
|
||||
## 📚 **Documentation**
|
||||
## 📚 **文档**
|
||||
|
||||
### **Complete Guide to SuperClaude**
|
||||
### **SuperClaude完整指南**
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th align="center">🚀 Getting Started</th>
|
||||
<th align="center">📖 User Guides</th>
|
||||
<th align="center">🛠️ Developer Resources</th>
|
||||
<th align="center">📋 Reference</th>
|
||||
<th align="center">🚀 快速开始</th>
|
||||
<th align="center">📖 用户指南</th>
|
||||
<th align="center">🛠️ 开发资源</th>
|
||||
<th align="center">📋 参考资料</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td valign="top">
|
||||
|
||||
- 📝 [**Quick Start Guide**](docs/getting-started/quick-start.md)
|
||||
*Get up and running fast*
|
||||
- 📝 [**快速开始指南**](docs/getting-started/quick-start.md)
|
||||
*快速上手使用*
|
||||
|
||||
- 💾 [**Installation Guide**](docs/getting-started/installation.md)
|
||||
*Detailed setup instructions*
|
||||
- 💾 [**安装指南**](docs/getting-started/installation.md)
|
||||
*详细的安装说明*
|
||||
|
||||
</td>
|
||||
<td valign="top">
|
||||
|
||||
- 🎯 [**Slash Commands**](docs/reference/commands-list.md)
|
||||
*All 30 commands organized by category*
|
||||
- 🎯 [**斜杠命令**](docs/user-guide/commands.md)
|
||||
*完整的 `/sc` 命令列表*
|
||||
|
||||
- 🤖 [**Agents Guide**](docs/user-guide/agents.md)
|
||||
*16 specialized agents*
|
||||
- 🤖 [**智能体指南**](docs/user-guide/agents.md)
|
||||
*16个专业智能体*
|
||||
|
||||
- 🎨 [**Behavioral Modes**](docs/user-guide/modes.md)
|
||||
*7 adaptive modes*
|
||||
- 🎨 [**行为模式**](docs/user-guide/modes.md)
|
||||
*7种自适应模式*
|
||||
|
||||
- 🚩 [**Flags Guide**](docs/user-guide/flags.md)
|
||||
*Control behaviors*
|
||||
- 🚩 [**标志指南**](docs/user-guide/flags.md)
|
||||
*控制行为参数*
|
||||
|
||||
- 🔧 [**MCP Servers**](docs/user-guide/mcp-servers.md)
|
||||
*8 server integrations*
|
||||
- 🔧 [**MCP服务器**](docs/user-guide/mcp-servers.md)
|
||||
*8个服务器集成*
|
||||
|
||||
- 💼 [**Session Management**](docs/user-guide/session-management.md)
|
||||
*Save & restore state*
|
||||
- 💼 [**会话管理**](docs/user-guide/session-management.md)
|
||||
*保存和恢复状态*
|
||||
|
||||
</td>
|
||||
<td valign="top">
|
||||
|
||||
- 🏗️ [**Technical Architecture**](docs/developer-guide/technical-architecture.md)
|
||||
*System design details*
|
||||
- 🏗️ [**技术架构**](docs/developer-guide/technical-architecture.md)
|
||||
*系统设计详情*
|
||||
|
||||
- 💻 [**Contributing Code**](docs/developer-guide/contributing-code.md)
|
||||
*Development workflow*
|
||||
- 💻 [**贡献代码**](docs/developer-guide/contributing-code.md)
|
||||
*开发工作流程*
|
||||
|
||||
- 🧪 [**Testing & Debugging**](docs/developer-guide/testing-debugging.md)
|
||||
*Quality assurance*
|
||||
- 🧪 [**测试与调试**](docs/developer-guide/testing-debugging.md)
|
||||
*质量保证*
|
||||
|
||||
</td>
|
||||
<td valign="top">
|
||||
- 📓 [**Examples Cookbook**](docs/reference/examples-cookbook.md)
|
||||
*Real-world recipes*
|
||||
|
||||
- 🔍 [**Troubleshooting**](docs/reference/troubleshooting.md)
|
||||
*Common issues & fixes*
|
||||
- 📓 [**示例手册**](docs/reference/examples-cookbook.md)
|
||||
*实际应用示例*
|
||||
|
||||
- 🔍 [**故障排除**](docs/reference/troubleshooting.md)
|
||||
*常见问题和修复*
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
@@ -515,26 +483,26 @@ The Deep Research system intelligently coordinates multiple tools:
|
||||
|
||||
<div align="center">
|
||||
|
||||
## 🤝 **Contributing**
|
||||
## 🤝 **贡献**
|
||||
|
||||
### **Join the SuperClaude Community**
|
||||
### **加入SuperClaude社区**
|
||||
|
||||
We welcome contributions of all kinds! Here's how you can help:
|
||||
我们欢迎各种类型的贡献!以下是您可以帮助的方式:
|
||||
|
||||
| Priority | Area | Description |
|
||||
| 优先级 | 领域 | 描述 |
|
||||
|:--------:|------|-------------|
|
||||
| 📝 **High** | Documentation | Improve guides, add examples, fix typos |
|
||||
| 🔧 **High** | MCP Integration | Add server configs, test integrations |
|
||||
| 🎯 **Medium** | Workflows | Create command patterns & recipes |
|
||||
| 🧪 **Medium** | Testing | Add tests, validate features |
|
||||
| 🌐 **Low** | i18n | Translate docs to other languages |
|
||||
| 📝 **高** | 文档 | 改进指南,添加示例,修复错误 |
|
||||
| 🔧 **高** | MCP集成 | 添加服务器配置,测试集成 |
|
||||
| 🎯 **中** | 工作流 | 创建命令模式和配方 |
|
||||
| 🧪 **中** | 测试 | 添加测试,验证功能 |
|
||||
| 🌐 **低** | 国际化 | 将文档翻译为其他语言 |
|
||||
|
||||
<p align="center">
|
||||
<a href="CONTRIBUTING.md">
|
||||
<img src="https://img.shields.io/badge/📖_Read-Contributing_Guide-blue" alt="Contributing Guide">
|
||||
<img src="https://img.shields.io/badge/📖_阅读-贡献指南-blue" alt="Contributing Guide">
|
||||
</a>
|
||||
<a href="https://github.com/SuperClaude-Org/SuperClaude_Framework/graphs/contributors">
|
||||
<img src="https://img.shields.io/badge/👥_View-All_Contributors-green" alt="Contributors">
|
||||
<img src="https://img.shields.io/badge/👥_查看-所有贡献者-green" alt="Contributors">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
@@ -544,9 +512,9 @@ We welcome contributions of all kinds! Here's how you can help:
|
||||
|
||||
<div align="center">
|
||||
|
||||
## ⚖️ **License**
|
||||
## ⚖️ **许可证**
|
||||
|
||||
This project is licensed under the **MIT License** - see the [LICENSE](LICENSE) file for details.
|
||||
本项目基于**MIT许可证**授权 - 详情请参阅[LICENSE](LICENSE)文件。
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/License-MIT-yellow.svg?" alt="MIT License">
|
||||
@@ -558,7 +526,7 @@ This project is licensed under the **MIT License** - see the [LICENSE](LICENSE)
|
||||
|
||||
<div align="center">
|
||||
|
||||
## ⭐ **Star History**
|
||||
## ⭐ **Star历史**
|
||||
|
||||
<a href="https://www.star-history.com/#SuperClaude-Org/SuperClaude_Framework&Timeline">
|
||||
<picture>
|
||||
@@ -575,72 +543,71 @@ This project is licensed under the **MIT License** - see the [LICENSE](LICENSE)
|
||||
|
||||
<div align="center">
|
||||
|
||||
### **🚀 Built with passion by the SuperClaude community**
|
||||
### **🚀 由SuperClaude社区倾情打造**
|
||||
|
||||
<p align="center">
|
||||
<sub>Made with ❤️ for developers who push boundaries</sub>
|
||||
<sub>为突破边界的开发者用❤️制作</sub>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="#-superclaude-framework">Back to Top ↑</a>
|
||||
<a href="#-superclaude-框架">返回顶部 ↑</a>
|
||||
</p>
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## 📋 **All 30 Commands**
|
||||
## 📋 **全部30个命令**
|
||||
|
||||
<details>
|
||||
<summary><b>Click to expand full command list</b></summary>
|
||||
<summary><b>点击展开完整命令列表</b></summary>
|
||||
|
||||
### 🧠 Planning & Design (4)
|
||||
- `/brainstorm` - Structured brainstorming
|
||||
- `/design` - System architecture
|
||||
- `/estimate` - Time/effort estimation
|
||||
- `/spec-panel` - Specification analysis
|
||||
### 🧠 规划与设计 (4)
|
||||
- `/brainstorm` - 结构化头脑风暴
|
||||
- `/design` - 系统架构
|
||||
- `/estimate` - 时间/工作量估算
|
||||
- `/spec-panel` - 规格分析
|
||||
|
||||
### 💻 Development (5)
|
||||
- `/implement` - Code implementation
|
||||
- `/build` - Build workflows
|
||||
- `/improve` - Code improvements
|
||||
- `/cleanup` - Refactoring
|
||||
- `/explain` - Code explanation
|
||||
### 💻 开发 (5)
|
||||
- `/implement` - 代码实现
|
||||
- `/build` - 构建工作流
|
||||
- `/improve` - 代码改进
|
||||
- `/cleanup` - 重构
|
||||
- `/explain` - 代码解释
|
||||
|
||||
### 🧪 Testing & Quality (4)
|
||||
- `/test` - Test generation
|
||||
- `/analyze` - Code analysis
|
||||
- `/troubleshoot` - Debugging
|
||||
- `/reflect` - Retrospectives
|
||||
### 🧪 测试与质量 (4)
|
||||
- `/test` - 测试生成
|
||||
- `/analyze` - 代码分析
|
||||
- `/troubleshoot` - 调试
|
||||
- `/reflect` - 回顾
|
||||
|
||||
### 📚 Documentation (2)
|
||||
- `/document` - Doc generation
|
||||
- `/help` - Command help
|
||||
### 📚 文档 (2)
|
||||
- `/document` - 文档生成
|
||||
- `/help` - 命令帮助
|
||||
|
||||
### 🔧 Version Control (1)
|
||||
- `/git` - Git operations
|
||||
### 🔧 版本控制 (1)
|
||||
- `/git` - Git操作
|
||||
|
||||
### 📊 Project Management (3)
|
||||
- `/pm` - Project management
|
||||
- `/task` - Task tracking
|
||||
- `/workflow` - Workflow automation
|
||||
### 📊 项目管理 (3)
|
||||
- `/pm` - 项目管理
|
||||
- `/task` - 任务跟踪
|
||||
- `/workflow` - 工作流自动化
|
||||
|
||||
### 🔍 Research & Analysis (2)
|
||||
- `/research` - Deep web research
|
||||
- `/business-panel` - Business analysis
|
||||
### 🔍 研究与分析 (2)
|
||||
- `/research` - 深度网络研究
|
||||
- `/business-panel` - 业务分析
|
||||
|
||||
### 🎯 Utilities (9)
|
||||
- `/agent` - AI agents
|
||||
- `/index-repo` - Repository indexing
|
||||
- `/index` - Indexing alias
|
||||
- `/recommend` - Command recommendations
|
||||
- `/select-tool` - Tool selection
|
||||
- `/spawn` - Parallel tasks
|
||||
- `/load` - Load sessions
|
||||
- `/save` - Save sessions
|
||||
- `/sc` - Show all commands
|
||||
### 🎯 实用工具 (9)
|
||||
- `/agent` - AI智能体
|
||||
- `/index-repo` - 仓库索引
|
||||
- `/index` - 索引别名
|
||||
- `/recommend` - 命令推荐
|
||||
- `/select-tool` - 工具选择
|
||||
- `/spawn` - 并行任务
|
||||
- `/load` - 加载会话
|
||||
- `/save` - 保存会话
|
||||
- `/sc` - 显示所有命令
|
||||
|
||||
[**📖 View Detailed Command Reference →**](docs/reference/commands-list.md)
|
||||
[**📖 查看详细命令参考 →**](docs/reference/commands-list.md)
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# WeHub 来源说明
|
||||
|
||||
- 原始项目:`SuperClaude-Org/SuperClaude_Framework`
|
||||
- 原始仓库:https://github.com/SuperClaude-Org/SuperClaude_Framework
|
||||
- 导入方式:上游默认分支的最新快照
|
||||
- 原作者、版权和许可证信息以原始仓库及本仓库 LICENSE 为准
|
||||
- 本文件仅用于记录来源,不代表 WeHub 是原项目作者
|
||||
@@ -134,7 +134,7 @@ CLAUDE.md # This file is tracked but listed here
|
||||
|
||||
---
|
||||
|
||||
## 📋 **Medium Priority (v4.2.0 Minor Release)**
|
||||
## 📋 **Medium Priority (v4.3.0 Minor Release)**
|
||||
|
||||
### 5. Implement Mindbase Integration
|
||||
**Status**: TODO
|
||||
@@ -273,13 +273,13 @@ CLAUDE.md # This file is tracked but listed here
|
||||
### Test Coverage Goals
|
||||
- Current: 0% (tests just created)
|
||||
- Target v4.1.7: 50%
|
||||
- Target v4.2.0: 80%
|
||||
- Target v4.3.0: 80%
|
||||
- Target v5.0: 90%
|
||||
|
||||
### Documentation Goals
|
||||
- Current: 60% (good README, missing details)
|
||||
- Target v4.1.7: 70%
|
||||
- Target v4.2.0: 85%
|
||||
- Target v4.3.0: 85%
|
||||
- Target v5.0: 95%
|
||||
|
||||
### Performance Goals
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# PM Agent Mode Integration Guide
|
||||
|
||||
**Last Updated**: 2025-10-14
|
||||
**Target Version**: 4.2.0
|
||||
**Target Version**: 4.3.0
|
||||
**Status**: Implementation Guide
|
||||
|
||||
---
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
|
||||
# 📦 SuperClaude Installation Guide
|
||||
|
||||
### **Transform Claude Code with 21 Commands, 14 Agents & 6 MCP Servers**
|
||||
### **Transform Claude Code with 30 Commands, 20 Agents, 7 Modes & 8 MCP Servers**
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/version-4.1.5-blue?style=for-the-badge" alt="Version">
|
||||
<img src="https://img.shields.io/badge/version-4.3.0-blue?style=for-the-badge" alt="Version">
|
||||
<img src="https://img.shields.io/badge/Python-3.8+-green?style=for-the-badge" alt="Python">
|
||||
<img src="https://img.shields.io/badge/Platform-Linux%20|%20macOS%20|%20Windows-orange?style=for-the-badge" alt="Platform">
|
||||
</p>
|
||||
@@ -270,7 +270,7 @@ SuperClaude install --dry-run
|
||||
```bash
|
||||
# Verify SuperClaude version
|
||||
python3 -m SuperClaude --version
|
||||
# Expected: SuperClaude 4.1.5
|
||||
# Expected: SuperClaude 4.3.0
|
||||
|
||||
# List installed components
|
||||
SuperClaude install --list-components
|
||||
@@ -504,7 +504,7 @@ brew install python3
|
||||
You now have access to:
|
||||
|
||||
<p align="center">
|
||||
<b>21 Commands</b> • <b>14 AI Agents</b> • <b>6 Behavioral Modes</b> • <b>6 MCP Servers</b>
|
||||
<b>30 Commands</b> • <b>20 AI Agents</b> • <b>7 Behavioral Modes</b> • <b>8 MCP Servers</b>
|
||||
</p>
|
||||
|
||||
**Ready to start?** Try `/sc:brainstorm` in Claude Code for your first SuperClaude experience!
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/Framework-Context_Engineering-purple?style=for-the-badge" alt="Framework">
|
||||
<img src="https://img.shields.io/badge/Version-4.1.5-blue?style=for-the-badge" alt="Version">
|
||||
<img src="https://img.shields.io/badge/Version-4.3.0-blue?style=for-the-badge" alt="Version">
|
||||
<img src="https://img.shields.io/badge/Time_to_Start-5_Minutes-green?style=for-the-badge" alt="Quick Start">
|
||||
</p>
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
|
||||
| **Commands** | **AI Agents** | **Behavioral Modes** | **MCP Servers** |
|
||||
|:------------:|:-------------:|:-------------------:|:---------------:|
|
||||
| **21** | **14** | **6** | **6** |
|
||||
| **30** | **20** | **7** | **8** |
|
||||
| `/sc:` triggers | Domain specialists | Context adaptation | Tool integration |
|
||||
|
||||
</div>
|
||||
@@ -486,7 +486,7 @@ Create custom workflows
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<sub>SuperClaude v4.1.5 - Context Engineering for Claude Code</sub>
|
||||
<sub>SuperClaude v4.3.0 - Context Engineering for Claude Code</sub>
|
||||
</p>
|
||||
|
||||
</div>
|
||||
@@ -0,0 +1,185 @@
|
||||
# Windows Installation Guide
|
||||
|
||||
Step-by-step guide for installing SuperClaude Framework on Windows using PowerShell.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
| Component | Version | Check Command |
|
||||
|-----------|---------|---------------|
|
||||
| **Python** | 3.10+ | `python --version` |
|
||||
| **pip** | Latest | `pip --version` |
|
||||
| **Claude Code** | Latest | `claude --version` |
|
||||
| **Git** | Any | `git --version` |
|
||||
|
||||
> **Note:** On Windows, use `python` instead of `python3`. If `python` is not found, check that you selected "Add Python to PATH" during installation.
|
||||
|
||||
### Installing Python
|
||||
|
||||
1. Download from [python.org/downloads](https://www.python.org/downloads/)
|
||||
2. Run the installer and **check "Add python.exe to PATH"** at the bottom of the first screen
|
||||
3. Click "Install Now"
|
||||
4. Open a **new** PowerShell window and verify:
|
||||
```powershell
|
||||
python --version
|
||||
pip --version
|
||||
```
|
||||
|
||||
### Installing Claude Code
|
||||
|
||||
Follow the official instructions at [claude.ai/code](https://claude.ai/code), then verify:
|
||||
|
||||
```powershell
|
||||
claude --version
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
### Method 1: pip (Recommended for Windows)
|
||||
|
||||
Open PowerShell and run:
|
||||
|
||||
```powershell
|
||||
pip install superclaude
|
||||
```
|
||||
|
||||
Then install the slash commands:
|
||||
|
||||
```powershell
|
||||
superclaude install
|
||||
```
|
||||
|
||||
If `superclaude` is not recognized after install, use:
|
||||
|
||||
```powershell
|
||||
python -m superclaude install
|
||||
```
|
||||
|
||||
### Method 2: pipx
|
||||
|
||||
```powershell
|
||||
pip install pipx
|
||||
pipx ensurepath
|
||||
```
|
||||
|
||||
Close and reopen PowerShell, then:
|
||||
|
||||
```powershell
|
||||
pipx install superclaude
|
||||
superclaude install
|
||||
```
|
||||
|
||||
### Method 3: Development install from source
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/SuperClaude-Org/SuperClaude_Framework.git
|
||||
cd SuperClaude_Framework
|
||||
|
||||
pip install -e ".[dev]"
|
||||
superclaude install
|
||||
```
|
||||
|
||||
> **Note:** The `install.sh` script is for Linux/macOS. On Windows, use the pip commands above instead.
|
||||
|
||||
---
|
||||
|
||||
## Verify Installation
|
||||
|
||||
```powershell
|
||||
# Check version
|
||||
superclaude --version
|
||||
|
||||
# List installed commands
|
||||
superclaude install --list
|
||||
|
||||
# Run health check
|
||||
superclaude doctor
|
||||
```
|
||||
|
||||
You should see 30 slash commands installed to `~/.claude/commands/sc/`.
|
||||
|
||||
---
|
||||
|
||||
## Post-Install: Test in Claude Code
|
||||
|
||||
Open Claude Code and try:
|
||||
|
||||
```
|
||||
/sc:help
|
||||
/sc:brainstorm "test project"
|
||||
```
|
||||
|
||||
If `/sc:` commands are not appearing, restart Claude Code — it reads commands from `~/.claude/commands/` on startup.
|
||||
|
||||
---
|
||||
|
||||
## Optional: MCP Servers
|
||||
|
||||
MCP servers add enhanced capabilities (web search, context retrieval, etc.):
|
||||
|
||||
```powershell
|
||||
# List available servers
|
||||
superclaude mcp --list
|
||||
|
||||
# Interactive install
|
||||
superclaude mcp
|
||||
|
||||
# Install specific servers
|
||||
superclaude mcp --servers tavily --servers context7
|
||||
```
|
||||
|
||||
Requires Node.js. Install from [nodejs.org](https://nodejs.org/) if needed.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "superclaude" is not recognized
|
||||
|
||||
pip installs scripts to a `Scripts/` directory that may not be on your PATH.
|
||||
|
||||
```powershell
|
||||
# Find where pip installed it
|
||||
python -c "import sysconfig; print(sysconfig.get_path('scripts'))"
|
||||
|
||||
# Add that directory to your PATH (current session)
|
||||
$env:PATH += ";$(python -c \"import sysconfig; print(sysconfig.get_path('scripts'))\")"
|
||||
|
||||
# Or run via python module
|
||||
python -m superclaude install
|
||||
```
|
||||
|
||||
To add it permanently, search "Environment Variables" in the Start menu, edit the user `Path` variable, and add the scripts directory.
|
||||
|
||||
### Permission errors
|
||||
|
||||
Run PowerShell as Administrator, or use `--user` flag:
|
||||
|
||||
```powershell
|
||||
pip install --user superclaude
|
||||
```
|
||||
|
||||
### Python not found / wrong version
|
||||
|
||||
If you have multiple Python versions, use the full path or the `py` launcher:
|
||||
|
||||
```powershell
|
||||
py -3.12 -m pip install superclaude
|
||||
py -3.12 -m superclaude install
|
||||
```
|
||||
|
||||
### Slash commands don't appear in Claude Code
|
||||
|
||||
1. Verify commands were installed: `superclaude install --list`
|
||||
2. Check the directory exists: `ls ~/.claude/commands/sc/`
|
||||
3. Restart Claude Code completely (close and reopen)
|
||||
4. If using a custom `CLAUDE_CONFIG_DIR`, ensure commands are installed there
|
||||
|
||||
### install.sh doesn't work on Windows
|
||||
|
||||
The `install.sh` script is a bash script for Linux/macOS. On Windows, use the pip commands from the Installation section above. If you need bash, install [Git for Windows](https://gitforwindows.org/) which includes Git Bash, then run:
|
||||
|
||||
```bash
|
||||
bash install.sh
|
||||
```
|
||||
@@ -54,3 +54,67 @@
|
||||
{"error_type": "FileNotFoundError", "error_message": "config.json not found", "solution": "Create config.json in project root", "session": "session_1", "timestamp": "2025-11-14T14:27:24.523965"}
|
||||
{"test_name": "test_reflexion_marker_integration", "error_type": "IntegrationTestError", "error_message": "Testing reflexion integration", "timestamp": "2025-11-14T14:27:24.525993"}
|
||||
{"test_name": "test_reflexion_with_real_exception", "error_type": "ZeroDivisionError", "error_message": "division by zero", "traceback": "simulated traceback", "solution": "Check denominator is not zero before division", "timestamp": "2025-11-14T14:27:24.527061"}
|
||||
{"test_name": "test_feature", "error_type": "AssertionError", "error_message": "Expected 5, got 3", "traceback": "File test.py, line 10...", "timestamp": "2026-03-22T16:50:20.950586"}
|
||||
{"test_name": "test_database_connection", "error_type": "ConnectionError", "error_message": "Could not connect to database", "solution": "Ensure database is running and credentials are correct", "timestamp": "2026-03-22T16:50:20.951276"}
|
||||
{"error_type": "ImportError", "error_message": "No module named 'pytest'", "solution": "Install pytest: pip install pytest", "timestamp": "2026-03-22T16:50:20.952238"}
|
||||
{"error_type": "TypeError", "error_message": "expected str, got int", "solution": "Convert int to str using str()", "timestamp": "2026-03-22T16:50:20.985628"}
|
||||
{"error_type": "TypeError", "error_message": "expected int, got str", "solution": "Convert str to int using int()", "timestamp": "2026-03-22T16:50:20.985833"}
|
||||
{"error_type": "FileNotFoundError", "error_message": "config.json not found", "solution": "Create config.json in project root", "session": "session_1", "timestamp": "2026-03-22T16:50:20.996012"}
|
||||
{"test_name": "test_reflexion_marker_integration", "error_type": "IntegrationTestError", "error_message": "Testing reflexion integration", "timestamp": "2026-03-22T16:50:21.003121"}
|
||||
{"test_name": "test_reflexion_with_real_exception", "error_type": "ZeroDivisionError", "error_message": "division by zero", "traceback": "simulated traceback", "solution": "Check denominator is not zero before division", "timestamp": "2026-03-22T16:50:21.003868"}
|
||||
{"test_name": "test_feature", "error_type": "AssertionError", "error_message": "Expected 5, got 3", "traceback": "File test.py, line 10...", "timestamp": "2026-03-22T16:50:25.072506"}
|
||||
{"test_name": "test_database_connection", "error_type": "ConnectionError", "error_message": "Could not connect to database", "solution": "Ensure database is running and credentials are correct", "timestamp": "2026-03-22T16:50:25.073210"}
|
||||
{"error_type": "ImportError", "error_message": "No module named 'pytest'", "solution": "Install pytest: pip install pytest", "timestamp": "2026-03-22T16:50:25.074234"}
|
||||
{"error_type": "TypeError", "error_message": "expected str, got int", "solution": "Convert int to str using str()", "timestamp": "2026-03-22T16:50:25.082456"}
|
||||
{"error_type": "TypeError", "error_message": "expected int, got str", "solution": "Convert str to int using int()", "timestamp": "2026-03-22T16:50:25.082601"}
|
||||
{"error_type": "FileNotFoundError", "error_message": "config.json not found", "solution": "Create config.json in project root", "session": "session_1", "timestamp": "2026-03-22T16:50:25.092667"}
|
||||
{"test_name": "test_reflexion_marker_integration", "error_type": "IntegrationTestError", "error_message": "Testing reflexion integration", "timestamp": "2026-03-22T16:50:25.100216"}
|
||||
{"test_name": "test_reflexion_with_real_exception", "error_type": "ZeroDivisionError", "error_message": "division by zero", "traceback": "simulated traceback", "solution": "Check denominator is not zero before division", "timestamp": "2026-03-22T16:50:25.100936"}
|
||||
{"test_name": "test_feature", "error_type": "AssertionError", "error_message": "Expected 5, got 3", "traceback": "File test.py, line 10...", "timestamp": "2026-03-22T16:52:51.573720"}
|
||||
{"test_name": "test_database_connection", "error_type": "ConnectionError", "error_message": "Could not connect to database", "solution": "Ensure database is running and credentials are correct", "timestamp": "2026-03-22T16:52:51.574534"}
|
||||
{"error_type": "ImportError", "error_message": "No module named 'pytest'", "solution": "Install pytest: pip install pytest", "timestamp": "2026-03-22T16:52:51.575446"}
|
||||
{"error_type": "TypeError", "error_message": "expected str, got int", "solution": "Convert int to str using str()", "timestamp": "2026-03-22T16:52:51.583917"}
|
||||
{"error_type": "TypeError", "error_message": "expected int, got str", "solution": "Convert str to int using int()", "timestamp": "2026-03-22T16:52:51.584096"}
|
||||
{"error_type": "FileNotFoundError", "error_message": "config.json not found", "solution": "Create config.json in project root", "session": "session_1", "timestamp": "2026-03-22T16:52:51.592781"}
|
||||
{"test_name": "test_reflexion_marker_integration", "error_type": "IntegrationTestError", "error_message": "Testing reflexion integration", "timestamp": "2026-03-22T16:52:51.599514"}
|
||||
{"test_name": "test_reflexion_with_real_exception", "error_type": "ZeroDivisionError", "error_message": "division by zero", "traceback": "simulated traceback", "solution": "Check denominator is not zero before division", "timestamp": "2026-03-22T16:52:51.600215"}
|
||||
{"test_name": "test_feature", "error_type": "AssertionError", "error_message": "Expected 5, got 3", "traceback": "File test.py, line 10...", "timestamp": "2026-03-22T17:00:13.653054"}
|
||||
{"test_name": "test_database_connection", "error_type": "ConnectionError", "error_message": "Could not connect to database", "solution": "Ensure database is running and credentials are correct", "timestamp": "2026-03-22T17:00:13.653728"}
|
||||
{"error_type": "ImportError", "error_message": "No module named 'pytest'", "solution": "Install pytest: pip install pytest", "timestamp": "2026-03-22T17:00:13.654889"}
|
||||
{"error_type": "TypeError", "error_message": "expected str, got int", "solution": "Convert int to str using str()", "timestamp": "2026-03-22T17:00:13.662985"}
|
||||
{"error_type": "TypeError", "error_message": "expected int, got str", "solution": "Convert str to int using int()", "timestamp": "2026-03-22T17:00:13.663142"}
|
||||
{"error_type": "FileNotFoundError", "error_message": "config.json not found", "solution": "Create config.json in project root", "session": "session_1", "timestamp": "2026-03-22T17:00:13.671993"}
|
||||
{"test_name": "test_reflexion_marker_integration", "error_type": "IntegrationTestError", "error_message": "Testing reflexion integration", "timestamp": "2026-03-22T17:00:13.679043"}
|
||||
{"test_name": "test_reflexion_with_real_exception", "error_type": "ZeroDivisionError", "error_message": "division by zero", "traceback": "simulated traceback", "solution": "Check denominator is not zero before division", "timestamp": "2026-03-22T17:00:13.679835"}
|
||||
{"test_name": "test_feature", "error_type": "AssertionError", "error_message": "Expected 5, got 3", "traceback": "File test.py, line 10...", "timestamp": "2026-03-22T17:07:17.673419"}
|
||||
{"test_name": "test_database_connection", "error_type": "ConnectionError", "error_message": "Could not connect to database", "solution": "Ensure database is running and credentials are correct", "timestamp": "2026-03-22T17:07:17.674107"}
|
||||
{"error_type": "ImportError", "error_message": "No module named 'pytest'", "solution": "Install pytest: pip install pytest", "timestamp": "2026-03-22T17:07:17.674959"}
|
||||
{"error_type": "TypeError", "error_message": "expected str, got int", "solution": "Convert int to str using str()", "timestamp": "2026-03-22T17:07:17.683755"}
|
||||
{"error_type": "TypeError", "error_message": "expected int, got str", "solution": "Convert str to int using int()", "timestamp": "2026-03-22T17:07:17.683905"}
|
||||
{"error_type": "FileNotFoundError", "error_message": "config.json not found", "solution": "Create config.json in project root", "session": "session_1", "timestamp": "2026-03-22T17:07:17.692517"}
|
||||
{"test_name": "test_reflexion_marker_integration", "error_type": "IntegrationTestError", "error_message": "Testing reflexion integration", "timestamp": "2026-03-22T17:07:17.699298"}
|
||||
{"test_name": "test_reflexion_with_real_exception", "error_type": "ZeroDivisionError", "error_message": "division by zero", "traceback": "simulated traceback", "solution": "Check denominator is not zero before division", "timestamp": "2026-03-22T17:07:17.699998"}
|
||||
{"test_name": "test_feature", "error_type": "AssertionError", "error_message": "Expected 5, got 3", "traceback": "File test.py, line 10...", "timestamp": "2026-03-22T17:11:35.482403"}
|
||||
{"test_name": "test_database_connection", "error_type": "ConnectionError", "error_message": "Could not connect to database", "solution": "Ensure database is running and credentials are correct", "timestamp": "2026-03-22T17:11:35.483736"}
|
||||
{"error_type": "ImportError", "error_message": "No module named 'pytest'", "solution": "Install pytest: pip install pytest", "timestamp": "2026-03-22T17:11:35.485379"}
|
||||
{"error_type": "TypeError", "error_message": "expected str, got int", "solution": "Convert int to str using str()", "timestamp": "2026-03-22T17:11:35.496376"}
|
||||
{"error_type": "TypeError", "error_message": "expected int, got str", "solution": "Convert str to int using int()", "timestamp": "2026-03-22T17:11:35.496668"}
|
||||
{"error_type": "FileNotFoundError", "error_message": "config.json not found", "solution": "Create config.json in project root", "session": "session_1", "timestamp": "2026-03-22T17:11:35.507509"}
|
||||
{"test_name": "test_reflexion_marker_integration", "error_type": "IntegrationTestError", "error_message": "Testing reflexion integration", "timestamp": "2026-03-22T17:11:35.516363"}
|
||||
{"test_name": "test_reflexion_with_real_exception", "error_type": "ZeroDivisionError", "error_message": "division by zero", "traceback": "simulated traceback", "solution": "Check denominator is not zero before division", "timestamp": "2026-03-22T17:11:35.517603"}
|
||||
{"test_name": "test_feature", "error_type": "AssertionError", "error_message": "Expected 5, got 3", "traceback": "File test.py, line 10...", "timestamp": "2026-03-22T17:15:41.253376"}
|
||||
{"test_name": "test_database_connection", "error_type": "ConnectionError", "error_message": "Could not connect to database", "solution": "Ensure database is running and credentials are correct", "timestamp": "2026-03-22T17:15:41.254220"}
|
||||
{"error_type": "ImportError", "error_message": "No module named 'pytest'", "solution": "Install pytest: pip install pytest", "timestamp": "2026-03-22T17:15:41.255370"}
|
||||
{"error_type": "TypeError", "error_message": "expected str, got int", "solution": "Convert int to str using str()", "timestamp": "2026-03-22T17:15:41.274867"}
|
||||
{"error_type": "TypeError", "error_message": "expected int, got str", "solution": "Convert str to int using int()", "timestamp": "2026-03-22T17:15:41.275041"}
|
||||
{"error_type": "FileNotFoundError", "error_message": "config.json not found", "solution": "Create config.json in project root", "session": "session_1", "timestamp": "2026-03-22T17:15:41.286770"}
|
||||
{"test_name": "test_reflexion_marker_integration", "error_type": "IntegrationTestError", "error_message": "Testing reflexion integration", "timestamp": "2026-03-22T17:15:41.294290"}
|
||||
{"test_name": "test_reflexion_with_real_exception", "error_type": "ZeroDivisionError", "error_message": "division by zero", "traceback": "simulated traceback", "solution": "Check denominator is not zero before division", "timestamp": "2026-03-22T17:15:41.295051"}
|
||||
{"test_name": "test_feature", "error_type": "AssertionError", "error_message": "Expected 5, got 3", "traceback": "File test.py, line 10...", "timestamp": "2026-03-22T17:25:06.359136"}
|
||||
{"test_name": "test_database_connection", "error_type": "ConnectionError", "error_message": "Could not connect to database", "solution": "Ensure database is running and credentials are correct", "timestamp": "2026-03-22T17:25:06.359840"}
|
||||
{"error_type": "ImportError", "error_message": "No module named 'pytest'", "solution": "Install pytest: pip install pytest", "timestamp": "2026-03-22T17:25:06.360709"}
|
||||
{"error_type": "TypeError", "error_message": "expected str, got int", "solution": "Convert int to str using str()", "timestamp": "2026-03-22T17:25:06.369433"}
|
||||
{"error_type": "TypeError", "error_message": "expected int, got str", "solution": "Convert str to int using int()", "timestamp": "2026-03-22T17:25:06.369581"}
|
||||
{"error_type": "FileNotFoundError", "error_message": "config.json not found", "solution": "Create config.json in project root", "session": "session_1", "timestamp": "2026-03-22T17:25:06.378488"}
|
||||
{"test_name": "test_reflexion_marker_integration", "error_type": "IntegrationTestError", "error_message": "Testing reflexion integration", "timestamp": "2026-03-22T17:25:06.385454"}
|
||||
{"test_name": "test_reflexion_with_real_exception", "error_type": "ZeroDivisionError", "error_message": "division by zero", "traceback": "simulated traceback", "solution": "Check denominator is not zero before division", "timestamp": "2026-03-22T17:25:06.386261"}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
# Mistake Record: test_database_connection
|
||||
|
||||
**Date**: 2026-03-22
|
||||
**Error Type**: ConnectionError
|
||||
|
||||
---
|
||||
|
||||
## ❌ What Happened
|
||||
|
||||
Could not connect to database
|
||||
|
||||
```
|
||||
No traceback
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔍 Root Cause
|
||||
|
||||
Not analyzed
|
||||
|
||||
---
|
||||
|
||||
## 🤔 Why Missed
|
||||
|
||||
Not analyzed
|
||||
|
||||
---
|
||||
|
||||
## ✅ Fix Applied
|
||||
|
||||
Ensure database is running and credentials are correct
|
||||
|
||||
---
|
||||
|
||||
## 🛡️ Prevention Checklist
|
||||
|
||||
Not documented
|
||||
|
||||
---
|
||||
|
||||
## 💡 Lesson Learned
|
||||
|
||||
Not documented
|
||||
@@ -0,0 +1,44 @@
|
||||
# Mistake Record: test_reflexion_with_real_exception
|
||||
|
||||
**Date**: 2026-03-22
|
||||
**Error Type**: ZeroDivisionError
|
||||
|
||||
---
|
||||
|
||||
## ❌ What Happened
|
||||
|
||||
division by zero
|
||||
|
||||
```
|
||||
simulated traceback
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔍 Root Cause
|
||||
|
||||
Not analyzed
|
||||
|
||||
---
|
||||
|
||||
## 🤔 Why Missed
|
||||
|
||||
Not analyzed
|
||||
|
||||
---
|
||||
|
||||
## ✅ Fix Applied
|
||||
|
||||
Check denominator is not zero before division
|
||||
|
||||
---
|
||||
|
||||
## 🛡️ Prevention Checklist
|
||||
|
||||
Not documented
|
||||
|
||||
---
|
||||
|
||||
## 💡 Lesson Learned
|
||||
|
||||
Not documented
|
||||
@@ -0,0 +1,44 @@
|
||||
# Mistake Record: unknown
|
||||
|
||||
**Date**: 2026-03-22
|
||||
**Error Type**: FileNotFoundError
|
||||
|
||||
---
|
||||
|
||||
## ❌ What Happened
|
||||
|
||||
config.json not found
|
||||
|
||||
```
|
||||
No traceback
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔍 Root Cause
|
||||
|
||||
Not analyzed
|
||||
|
||||
---
|
||||
|
||||
## 🤔 Why Missed
|
||||
|
||||
Not analyzed
|
||||
|
||||
---
|
||||
|
||||
## ✅ Fix Applied
|
||||
|
||||
Create config.json in project root
|
||||
|
||||
---
|
||||
|
||||
## 🛡️ Prevention Checklist
|
||||
|
||||
Not documented
|
||||
|
||||
---
|
||||
|
||||
## 💡 Lesson Learned
|
||||
|
||||
Not documented
|
||||
@@ -0,0 +1,216 @@
|
||||
# Claude Code Integration Guide
|
||||
|
||||
How SuperClaude integrates with — and extends — Claude Code's native features.
|
||||
|
||||
## Overview
|
||||
|
||||
SuperClaude enhances Claude Code through **context engineering**. It doesn't replace Claude Code — it configures and extends it with specialized commands, agents, modes, and development patterns through Claude Code's native extension points.
|
||||
|
||||
This guide maps every SuperClaude feature to its Claude Code integration point, and identifies gaps where SuperClaude could better leverage Claude Code's capabilities.
|
||||
|
||||
---
|
||||
|
||||
## Integration Points
|
||||
|
||||
### 1. Slash Commands → Claude Code Custom Commands
|
||||
|
||||
**Claude Code native**: Reads `.md` files from `~/.claude/commands/` and makes them available as `/` commands. Supports YAML frontmatter, argument substitution (`$ARGUMENTS`, `$0`, `$1`), dynamic context injection (`` !`command` ``), and subagent execution (`context: fork`).
|
||||
|
||||
**SuperClaude provides**: 30 slash commands installed to `~/.claude/commands/sc/`, namespaced as `/sc:*`.
|
||||
|
||||
| Category | Commands |
|
||||
|----------|----------|
|
||||
| **Planning & Design** | `/sc:pm`, `/sc:brainstorm`, `/sc:design`, `/sc:estimate`, `/sc:spec-panel` |
|
||||
| **Development** | `/sc:implement`, `/sc:build`, `/sc:improve`, `/sc:cleanup`, `/sc:explain` |
|
||||
| **Testing & Quality** | `/sc:test`, `/sc:analyze`, `/sc:troubleshoot`, `/sc:reflect` |
|
||||
| **Documentation** | `/sc:document`, `/sc:help` |
|
||||
| **Version Control** | `/sc:git` |
|
||||
| **Research** | `/sc:research`, `/sc:business-panel` |
|
||||
| **Project Management** | `/sc:task`, `/sc:workflow` |
|
||||
| **Utilities** | `/sc:agent`, `/sc:index-repo`, `/sc:recommend`, `/sc:select-tool`, `/sc:spawn`, `/sc:load`, `/sc:save` |
|
||||
|
||||
**Installation**: `superclaude install`
|
||||
|
||||
### 2. Agents → Claude Code Custom Subagents
|
||||
|
||||
**Claude Code native**: Supports custom subagent definitions in `~/.claude/agents/` (user) and `.claude/agents/` (project). Agents have YAML frontmatter with `model`, `allowed-tools`, `effort`, `context`, and `hooks` fields. Invocable via `@agent-name` syntax. 6 built-in subagents: Explore, Plan, General-purpose, Bash, statusline-setup, Claude Code Guide.
|
||||
|
||||
**SuperClaude provides**: 20 domain-specialist agents installed to `~/.claude/agents/`.
|
||||
|
||||
| Agent | Specialization |
|
||||
|-------|---------------|
|
||||
| `@pm-agent` | Project management, PDCA cycles, context persistence |
|
||||
| `@system-architect` | System design, architecture decisions |
|
||||
| `@frontend-architect` | UI/UX, component design, accessibility |
|
||||
| `@backend-architect` | APIs, databases, infrastructure |
|
||||
| `@security-engineer` | Security audit, vulnerability analysis |
|
||||
| `@deep-research` | Multi-source research with citations |
|
||||
| `@deep-research-agent` | Alternative research agent |
|
||||
| `@quality-engineer` | Testing strategy, code quality |
|
||||
| `@performance-engineer` | Optimization, profiling, benchmarks |
|
||||
| `@python-expert` | Python-specific best practices |
|
||||
| `@technical-writer` | Documentation, API docs |
|
||||
| `@devops-architect` | CI/CD, deployment, infrastructure |
|
||||
| `@refactoring-expert` | Code refactoring patterns |
|
||||
| `@requirements-analyst` | Requirements engineering |
|
||||
| `@root-cause-analyst` | Root cause analysis |
|
||||
| `@socratic-mentor` | Teaching through questions |
|
||||
| `@learning-guide` | Learning path guidance |
|
||||
| `@self-review` | Code self-review |
|
||||
| `@repo-index` | Repository indexing |
|
||||
| `@business-panel-experts` | Business stakeholder analysis |
|
||||
|
||||
**Installation**: `superclaude install` (installs both commands and agents)
|
||||
|
||||
### 3. Behavioral Modes
|
||||
|
||||
**Claude Code native**: Supports permission modes (`default`, `plan`, `acceptEdits`, `bypassPermissions`), effort levels (`low`, `medium`, `high`, `max`), and extended thinking. No direct "behavioral mode" concept — SuperClaude adds this through context injection.
|
||||
|
||||
**SuperClaude provides**: 7 behavioral modes that adapt Claude's response patterns:
|
||||
|
||||
| Mode | Effect | Claude Code Mapping |
|
||||
|------|--------|-------------------|
|
||||
| **Brainstorming** | Divergent thinking, idea generation | Context injection via command |
|
||||
| **Business Panel** | Multi-stakeholder analysis | Multi-agent orchestration |
|
||||
| **Deep Research** | Systematic investigation with citations | Extended thinking + research agent |
|
||||
| **Introspection** | Self-reflection, meta-analysis | Extended thinking context |
|
||||
| **Orchestration** | Multi-agent coordination | Subagent delegation |
|
||||
| **Task Management** | PDCA cycles, progress tracking | TodoWrite + session persistence |
|
||||
| **Token Efficiency** | Minimal token usage, concise responses | Effort level adjustment |
|
||||
|
||||
### 4. Skills → Claude Code Skills System
|
||||
|
||||
**Claude Code native**: Full skills system with YAML frontmatter (`name`, `description`, `allowed-tools`, `model`, `effort`, `context`, `agent`, `hooks`), argument substitution, dynamic context injection, subagent execution, and auto-discovery in `.claude/skills/` directories. Skills can be user-invocable or auto-triggered.
|
||||
|
||||
**SuperClaude provides**: 1 skill currently (`confidence-check`). This is a significant gap — many SuperClaude commands could be reimplemented as proper Claude Code skills for better integration.
|
||||
|
||||
**Installation**: `superclaude install-skill <name>`
|
||||
|
||||
### 5. Hooks → Claude Code Hooks System
|
||||
|
||||
**Claude Code native**: 28 hook event types with 4 handler types (command, HTTP, prompt, agent). Events include `SessionStart`, `SessionEnd`, `PreToolUse`, `PostToolUse`, `Stop`, `SubagentStart`, `SubagentStop`, `UserPromptSubmit`, `PreCompact`, `PostCompact`, `TaskCompleted`, `WorktreeCreate`, and more. Hooks are configured in `settings.json` under the `hooks` key.
|
||||
|
||||
**SuperClaude provides**: Hook definitions in `src/superclaude/hooks/hooks.json`. Currently limited — does not leverage many available hook events.
|
||||
|
||||
**Gap**: SuperClaude could use hooks for:
|
||||
- `SessionStart` — Auto-restore PM Agent context
|
||||
- `PostToolUse` — Self-check validation after edits
|
||||
- `Stop` — Session summary and next-actions persistence
|
||||
- `TaskCompleted` — Reflexion pattern trigger
|
||||
- `SubagentStop` — Quality gate checks
|
||||
|
||||
### 6. Settings → Claude Code Settings System
|
||||
|
||||
**Claude Code native**: 5 settings scopes (managed, CLI flags, local project, shared project, user). Supports permissions (`allow`/`ask`/`deny`), tool-specific rules with wildcards (`Bash(npm *)`, `Edit(/path/**)`), sandbox configuration, model overrides, auto-memory, and MCP server management.
|
||||
|
||||
**SuperClaude provides**: Project-level `.claude/settings.json` with basic permission rules.
|
||||
|
||||
**Gap**: Could provide recommended settings profiles for different workflows (e.g., strict security mode, autonomous development mode, research mode).
|
||||
|
||||
### 7. MCP Servers → Claude Code MCP Integration
|
||||
|
||||
**Claude Code native**: Supports stdio and SSE transports, OAuth authentication, 3 configuration scopes (local, project, user), tool search, channel push notifications, and elicitation (interactive input). 60+ servers in the official registry.
|
||||
|
||||
**SuperClaude provides**: 8 pre-configured servers + AIRIS Gateway:
|
||||
|
||||
| Server | Purpose | Transport |
|
||||
|--------|---------|-----------|
|
||||
| **AIRIS Gateway** | Unified gateway with 60+ tools | SSE |
|
||||
| **Tavily** | Web search for deep research | stdio |
|
||||
| **Context7** | Official library documentation | stdio |
|
||||
| **Sequential Thinking** | Multi-step problem solving | stdio |
|
||||
| **Playwright** | Browser automation and E2E testing | stdio |
|
||||
| **Serena** | Semantic code analysis | stdio |
|
||||
| **Magic** | UI component generation | stdio |
|
||||
| **MorphLLM** | Fast Apply for code modifications | stdio |
|
||||
|
||||
**Installation**: `superclaude mcp` (interactive) or `superclaude mcp --servers tavily context7`
|
||||
|
||||
### 8. Pytest Plugin (Auto-loaded)
|
||||
|
||||
**Claude Code native**: No built-in test framework — relies on tool use (`Bash`) to run tests.
|
||||
|
||||
**SuperClaude adds**: Auto-loaded pytest plugin registered via `pyproject.toml` entry point.
|
||||
|
||||
**Fixtures**: `confidence_checker`, `self_check_protocol`, `reflexion_pattern`, `token_budget`, `pm_context`
|
||||
|
||||
**Auto-markers**: Tests in `/unit/` → `@pytest.mark.unit`, `/integration/` → `@pytest.mark.integration`
|
||||
|
||||
**Custom markers**: `confidence_check`, `self_check`, `reflexion`, `complexity`
|
||||
|
||||
---
|
||||
|
||||
## Feature Mapping: Claude Code ↔ SuperClaude
|
||||
|
||||
| Claude Code Feature | SuperClaude Enhancement | Gap? |
|
||||
|--------------------|------------------------|------|
|
||||
| 60+ built-in `/` commands | 30 custom `/sc:*` commands | Complementary |
|
||||
| 6 built-in subagents | 20 domain-specialist `@agents` | Complementary |
|
||||
| Skills system (YAML + MD) | 1 skill (confidence-check) | **Large gap** — should convert commands to skills |
|
||||
| 28 hook events | Basic hook definitions | **Large gap** — most events unused |
|
||||
| 5 settings scopes | 1 project scope used | **Medium gap** — no recommended profiles |
|
||||
| Permission modes (4) | Not leveraged | **Gap** — could provide mode presets |
|
||||
| Extended thinking | Deep Research mode uses it | Partial |
|
||||
| Agent teams (preview) | Orchestration mode | Partial alignment |
|
||||
| Voice dictation (20 langs) | Not leveraged | Not applicable |
|
||||
| Desktop app features | Not leveraged | Not applicable (CLI-focused) |
|
||||
| Plan mode | Not leveraged | **Gap** — could integrate with confidence checks |
|
||||
| Session persistence | PM Agent memory files | Partial — could use native sessions |
|
||||
| `/compact` context mgmt | Token Efficiency mode | Partial alignment |
|
||||
| MCP 60+ registry servers | 8 pre-configured + gateway | Partial |
|
||||
| Worktree isolation | Documented in CLAUDE.md | Documented |
|
||||
| `--effort` levels | Token Efficiency mode | Partial alignment |
|
||||
| `/batch` parallel changes | Parallel execution engine | Complementary |
|
||||
| Fast mode | Not leveraged | Not applicable |
|
||||
|
||||
---
|
||||
|
||||
## Key Gaps to Address
|
||||
|
||||
### High Priority
|
||||
|
||||
1. **Skills Migration**: Convert key `/sc:*` commands into proper Claude Code skills with YAML frontmatter. This enables auto-triggering, tool restrictions, effort overrides, and better IDE integration.
|
||||
|
||||
2. **Hooks Integration**: Leverage Claude Code's 28 hook events for:
|
||||
- `SessionStart` → PM Agent context restoration
|
||||
- `Stop` → Session summary persistence
|
||||
- `PostToolUse` → Self-check after edits
|
||||
- `TaskCompleted` → Reflexion pattern
|
||||
|
||||
3. **Plan Mode Integration**: Connect confidence checks with Claude Code's native plan mode — block implementation when confidence < 70%.
|
||||
|
||||
### Medium Priority
|
||||
|
||||
4. **Settings Profiles**: Provide recommended `.claude/settings.json` profiles for different workflows (strict security, autonomous dev, research).
|
||||
|
||||
5. **Native Session Persistence**: Use Claude Code's `--continue` / `--resume` instead of custom memory files for PM Agent context.
|
||||
|
||||
6. **Permission Presets**: Pre-configured permission rules for SuperClaude's common workflows.
|
||||
|
||||
### Future (v5.0+)
|
||||
|
||||
7. **TypeScript Plugin System**: Native Claude Code plugin marketplace distribution.
|
||||
8. **IDE Extensions**: VS Code / JetBrains integration for SuperClaude features.
|
||||
9. **Agent Teams**: Align Orchestration mode with Claude Code's agent teams feature.
|
||||
|
||||
---
|
||||
|
||||
## Claude Code Native Features Reference
|
||||
|
||||
For developers working on SuperClaude, these are the key Claude Code capabilities to be aware of:
|
||||
|
||||
| Feature | Documentation |
|
||||
|---------|--------------|
|
||||
| Custom commands | `~/.claude/commands/*.md` with YAML frontmatter |
|
||||
| Custom agents | `~/.claude/agents/*.md` with model/tools/effort config |
|
||||
| Skills | `~/.claude/skills/` with auto-discovery and argument substitution |
|
||||
| Hooks | 28 events in `settings.json` → command/HTTP/prompt/agent handlers |
|
||||
| Settings | 5 scopes: managed > CLI > local > shared > user |
|
||||
| Permissions | `Bash(pattern)`, `Edit(path)`, `mcp__server__tool` rules |
|
||||
| MCP | stdio/SSE transports, OAuth, 3 scopes, elicitation |
|
||||
| Subagents | `Agent` tool with model/tools/isolation/background options |
|
||||
| Plan mode | Read-only exploration, visual plan markdown |
|
||||
| Extended thinking | `--effort max`, `Alt+T` toggle, `MAX_THINKING_TOKENS` |
|
||||
| Voice | 20 languages, push-to-talk, `/voice` command |
|
||||
| Session mgmt | Named sessions, resume, fork, 7-day persistence |
|
||||
| Context | `/context` visualization, auto-compaction at ~95% |
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@bifrost_inc/superclaude",
|
||||
"version": "4.1.7",
|
||||
"version": "4.3.0",
|
||||
"description": "SuperClaude Framework NPM wrapper - Official Node.js wrapper for the Python SuperClaude package. Enhances Claude Code with specialized commands and AI development tools.",
|
||||
"scripts": {
|
||||
"postinstall": "node ./bin/install.js",
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "superclaude",
|
||||
"version": "4.3.0",
|
||||
"description": "AI-enhanced development framework for Claude Code — 30 commands, 20 agents, 7 modes, confidence checks, parallel execution, and reflexion-based learning",
|
||||
"author": {
|
||||
"name": "SuperClaude Org",
|
||||
"url": "https://github.com/SuperClaude-Org"
|
||||
},
|
||||
"homepage": "https://github.com/SuperClaude-Org/SuperClaude_Framework",
|
||||
"repository": "https://github.com/SuperClaude-Org/SuperClaude_Framework",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"development",
|
||||
"pm-agent",
|
||||
"confidence-check",
|
||||
"parallel-execution",
|
||||
"reflexion",
|
||||
"pdca",
|
||||
"code-quality",
|
||||
"testing",
|
||||
"research",
|
||||
"architecture"
|
||||
],
|
||||
"commands": "./commands/",
|
||||
"agents": "./agents/",
|
||||
"skills": "./skills/",
|
||||
"hooks": "./hooks/hooks.json",
|
||||
"mcpServers": "./.mcp.json"
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"context7": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@upstash/context7-mcp@latest"]
|
||||
},
|
||||
"sequential-thinking": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-sequential-thinking"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
# SuperClaude Plugin for Claude Code
|
||||
|
||||
AI-enhanced development framework — 30 commands, 20 agents, 7 skills, and lifecycle hooks.
|
||||
|
||||
## Installation
|
||||
|
||||
### From marketplace (when published)
|
||||
|
||||
```bash
|
||||
/plugin marketplace add SuperClaude-Org/SuperClaude_Framework
|
||||
/plugin install superclaude@SuperClaude-Org/SuperClaude_Framework --scope user
|
||||
```
|
||||
|
||||
### Local development
|
||||
|
||||
```bash
|
||||
claude --plugin-dir ./plugins/superclaude
|
||||
```
|
||||
|
||||
## What's Included
|
||||
|
||||
### 30 Slash Commands (`/superclaude:*`)
|
||||
|
||||
Planning: `pm`, `brainstorm`, `design`, `estimate`, `spec-panel`
|
||||
Development: `implement`, `build`, `improve`, `cleanup`, `explain`
|
||||
Testing: `test`, `analyze`, `troubleshoot`, `reflect`
|
||||
Documentation: `document`, `help`
|
||||
Research: `research`, `business-panel`
|
||||
Utilities: `agent`, `index-repo`, `git`, `task`, `workflow`, `spawn`, `load`, `save`
|
||||
|
||||
### 20 Domain-Specialist Agents
|
||||
|
||||
`@pm-agent`, `@system-architect`, `@frontend-architect`, `@backend-architect`,
|
||||
`@security-engineer`, `@deep-research`, `@quality-engineer`, `@performance-engineer`,
|
||||
`@python-expert`, `@technical-writer`, `@devops-architect`, `@refactoring-expert`,
|
||||
`@requirements-analyst`, `@root-cause-analyst`, `@socratic-mentor`, `@learning-guide`,
|
||||
`@self-review`, `@repo-index`, `@business-panel-experts`, `@deep-research-agent`
|
||||
|
||||
### 7 Skills
|
||||
|
||||
| Skill | Auto-triggers on |
|
||||
|-------|-----------------|
|
||||
| `confidence-check` | Pre-implementation confidence assessment |
|
||||
| `deep-research` | Research, investigate, explore requests |
|
||||
| `brainstorm` | Vague requests, idea exploration |
|
||||
| `troubleshoot` | Error reports, debugging |
|
||||
| `pm` | Session start, task planning |
|
||||
| `token-efficiency` | Low context, brevity requests |
|
||||
|
||||
### Hooks
|
||||
|
||||
| Event | Behavior |
|
||||
|-------|----------|
|
||||
| `SessionStart` | Initialize session context |
|
||||
| `Stop` | Check for uncommitted changes and incomplete tasks |
|
||||
| `PostToolUse` (Write/Edit) | Verify edit correctness |
|
||||
|
||||
### MCP Servers
|
||||
|
||||
- **Context7** — Official library documentation (prevents hallucination)
|
||||
- **Sequential Thinking** — Multi-step problem solving
|
||||
|
||||
## Version
|
||||
|
||||
4.3.0
|
||||
@@ -10,7 +10,7 @@ category: meta
|
||||
- **Session Start (MANDATORY)**: ALWAYS activates to restore context from Serena MCP memory
|
||||
- **Post-Implementation**: After any task completion requiring documentation
|
||||
- **Mistake Detection**: Immediate analysis when errors or bugs occur
|
||||
- **State Questions**: "どこまで進んでた", "現状", "進捗" trigger context report
|
||||
- **State Questions**: "where did we leave off", "current status", "progress" trigger context report
|
||||
- **Monthly Maintenance**: Regular documentation health reviews
|
||||
- **Manual Invocation**: `/sc:pm` command for explicit PM Agent activation
|
||||
- **Knowledge Gap**: When patterns emerge requiring documentation
|
||||
@@ -24,7 +24,7 @@ PM Agent maintains continuous context across sessions using Serena MCP memory op
|
||||
```yaml
|
||||
Activation Trigger:
|
||||
- EVERY Claude Code session start (no user command needed)
|
||||
- "どこまで進んでた", "現状", "進捗" queries
|
||||
- "where did we leave off", "current status", "progress" queries
|
||||
|
||||
Context Restoration:
|
||||
1. list_memories() → Check for existing PM Agent state
|
||||
@@ -34,10 +34,10 @@ Context Restoration:
|
||||
5. read_memory("next_actions") → What to do next
|
||||
|
||||
User Report:
|
||||
前回: [last session summary]
|
||||
進捗: [current progress status]
|
||||
今回: [planned next actions]
|
||||
課題: [blockers or issues]
|
||||
Previous: [last session summary]
|
||||
Progress: [current progress status]
|
||||
Next: [planned next actions]
|
||||
Blockers: [blockers or issues]
|
||||
|
||||
Ready for Work:
|
||||
- User can immediately continue from last checkpoint
|
||||
@@ -48,7 +48,7 @@ Ready for Work:
|
||||
### During Work (Continuous PDCA Cycle)
|
||||
|
||||
```yaml
|
||||
1. Plan Phase (仮説 - Hypothesis):
|
||||
1. Plan Phase (Hypothesis):
|
||||
Actions:
|
||||
- write_memory("plan", goal_statement)
|
||||
- Create docs/temp/hypothesis-YYYY-MM-DD.md
|
||||
@@ -60,22 +60,22 @@ Ready for Work:
|
||||
hypothesis: "Use Supabase Auth + Kong Gateway pattern"
|
||||
success_criteria: "Login works, tokens validated via Kong"
|
||||
|
||||
2. Do Phase (実験 - Experiment):
|
||||
2. Do Phase (Experiment):
|
||||
Actions:
|
||||
- TodoWrite for task tracking (3+ steps required)
|
||||
- write_memory("checkpoint", progress) every 30min
|
||||
- Create docs/temp/experiment-YYYY-MM-DD.md
|
||||
- Record 試行錯誤 (trial and error), errors, solutions
|
||||
- Record trial and error, errors, solutions
|
||||
|
||||
Example Memory:
|
||||
checkpoint: "Implemented login form, testing Kong routing"
|
||||
errors_encountered: ["CORS issue", "JWT validation failed"]
|
||||
solutions_applied: ["Added Kong CORS plugin", "Fixed JWT secret"]
|
||||
|
||||
3. Check Phase (評価 - Evaluation):
|
||||
3. Check Phase (Evaluation):
|
||||
Actions:
|
||||
- think_about_task_adherence() → Self-evaluation
|
||||
- "何がうまくいった?何が失敗?" (What worked? What failed?)
|
||||
- "What worked? What failed?"
|
||||
- Create docs/temp/lessons-YYYY-MM-DD.md
|
||||
- Assess against success criteria
|
||||
|
||||
@@ -84,10 +84,10 @@ Ready for Work:
|
||||
what_failed: "Forgot organization_id in initial implementation"
|
||||
lessons: "ALWAYS check multi-tenancy docs before queries"
|
||||
|
||||
4. Act Phase (改善 - Improvement):
|
||||
4. Act Phase (Improvement):
|
||||
Actions:
|
||||
- Success → Move docs/temp/experiment-* → docs/patterns/[pattern-name].md (清書)
|
||||
- Failure → Create docs/mistakes/mistake-YYYY-MM-DD.md (防止策)
|
||||
- Success → Move docs/temp/experiment-* → docs/patterns/[pattern-name].md (clean copy)
|
||||
- Failure → Create docs/mistakes/mistake-YYYY-MM-DD.md (prevention measures)
|
||||
- Update CLAUDE.md if global pattern discovered
|
||||
- write_memory("summary", outcomes)
|
||||
|
||||
@@ -139,19 +139,19 @@ State Preservation:
|
||||
PM Agent continuously evaluates its own performance using the PDCA cycle:
|
||||
|
||||
```yaml
|
||||
Plan (仮説生成):
|
||||
Plan (Hypothesis Generation):
|
||||
- "What am I trying to accomplish?"
|
||||
- "What approach should I take?"
|
||||
- "What are the success criteria?"
|
||||
- "What could go wrong?"
|
||||
|
||||
Do (実験実行):
|
||||
Do (Experiment Execution):
|
||||
- Execute planned approach
|
||||
- Monitor for deviations from plan
|
||||
- Record unexpected issues
|
||||
- Adapt strategy as needed
|
||||
|
||||
Check (自己評価):
|
||||
Check (Self-Evaluation):
|
||||
Think About Questions:
|
||||
- "Did I follow the architecture patterns?" (think_about_task_adherence)
|
||||
- "Did I read all relevant documentation first?"
|
||||
@@ -160,7 +160,7 @@ Check (自己評価):
|
||||
- "What mistakes did I make?"
|
||||
- "What did I learn?"
|
||||
|
||||
Act (改善実行):
|
||||
Act (Improvement Execution):
|
||||
Success Path:
|
||||
- Extract successful pattern
|
||||
- Document in docs/patterns/
|
||||
@@ -187,7 +187,7 @@ Temporary Documentation (docs/temp/):
|
||||
- lessons-YYYY-MM-DD.md: Reflections, what worked, what failed
|
||||
|
||||
Characteristics:
|
||||
- 試行錯誤 OK (trial and error welcome)
|
||||
- Trial and error welcome
|
||||
- Raw notes and observations
|
||||
- Not polished or formal
|
||||
- Temporary (moved or deleted after 7 days)
|
||||
@@ -198,7 +198,7 @@ Formal Documentation (docs/patterns/):
|
||||
Process:
|
||||
- Read docs/temp/experiment-*.md
|
||||
- Extract successful approach
|
||||
- Clean up and formalize (清書)
|
||||
- Clean up and formalize (clean copy)
|
||||
- Add concrete examples
|
||||
- Include "Last Verified" date
|
||||
|
||||
@@ -211,12 +211,12 @@ Mistake Documentation (docs/mistakes/):
|
||||
Purpose: Error records with prevention strategies
|
||||
Trigger: Mistake detected, root cause identified
|
||||
Process:
|
||||
- What Happened (現象)
|
||||
- Root Cause (根本原因)
|
||||
- Why Missed (なぜ見逃したか)
|
||||
- Fix Applied (修正内容)
|
||||
- Prevention Checklist (防止策)
|
||||
- Lesson Learned (教訓)
|
||||
- What Happened
|
||||
- Root Cause
|
||||
- Why Missed
|
||||
- Fix Applied
|
||||
- Prevention Checklist
|
||||
- Lesson Learned
|
||||
|
||||
Example:
|
||||
docs/temp/experiment-2025-10-13.md
|
||||
|
||||
@@ -14,8 +14,8 @@ personas: [pm-agent]
|
||||
## Auto-Activation Triggers
|
||||
- **Session Start (MANDATORY)**: ALWAYS activates to restore context via Serena MCP memory
|
||||
- **All User Requests**: Default entry point for all interactions unless explicit sub-agent override
|
||||
- **State Questions**: "どこまで進んでた", "現状", "進捗" trigger context report
|
||||
- **Vague Requests**: "作りたい", "実装したい", "どうすれば" trigger discovery mode
|
||||
- **State Questions**: "where did we leave off", "current status", "progress" trigger context report
|
||||
- **Vague Requests**: "I want to build", "I want to implement", "how do I" trigger discovery mode
|
||||
- **Multi-Domain Tasks**: Cross-functional coordination requiring multiple specialists
|
||||
- **Complex Projects**: Systematic planning and PDCA cycle execution
|
||||
|
||||
@@ -43,10 +43,10 @@ personas: [pm-agent]
|
||||
- read_memory("next_actions") → What to do next
|
||||
|
||||
2. Report to User:
|
||||
"前回: [last session summary]
|
||||
進捗: [current progress status]
|
||||
今回: [planned next actions]
|
||||
課題: [blockers or issues]"
|
||||
"Previous: [last session summary]
|
||||
Progress: [current progress status]
|
||||
Next: [planned next actions]
|
||||
Blockers: [blockers or issues]"
|
||||
|
||||
3. Ready for Work:
|
||||
User can immediately continue from last checkpoint
|
||||
@@ -55,26 +55,26 @@ personas: [pm-agent]
|
||||
|
||||
### During Work (Continuous PDCA Cycle)
|
||||
```yaml
|
||||
1. Plan (仮説):
|
||||
1. Plan (Hypothesis):
|
||||
- write_memory("plan", goal_statement)
|
||||
- Create docs/temp/hypothesis-YYYY-MM-DD.md
|
||||
- Define what to implement and why
|
||||
|
||||
2. Do (実験):
|
||||
2. Do (Experiment):
|
||||
- TodoWrite for task tracking
|
||||
- write_memory("checkpoint", progress) every 30min
|
||||
- Update docs/temp/experiment-YYYY-MM-DD.md
|
||||
- Record試行錯誤, errors, solutions
|
||||
- Record trial-and-error, errors, solutions
|
||||
|
||||
3. Check (評価):
|
||||
3. Check (Evaluation):
|
||||
- think_about_task_adherence() → Self-evaluation
|
||||
- "何がうまくいった?何が失敗?"
|
||||
- "What went well? What failed?"
|
||||
- Update docs/temp/lessons-YYYY-MM-DD.md
|
||||
- Assess against goals
|
||||
|
||||
4. Act (改善):
|
||||
- Success → docs/patterns/[pattern-name].md (清書)
|
||||
- Failure → docs/mistakes/mistake-YYYY-MM-DD.md (防止策)
|
||||
4. Act (Improvement):
|
||||
- Success → docs/patterns/[pattern-name].md (formalized)
|
||||
- Failure → docs/mistakes/mistake-YYYY-MM-DD.md (prevention measures)
|
||||
- Update CLAUDE.md if global pattern
|
||||
- write_memory("summary", outcomes)
|
||||
```
|
||||
@@ -146,7 +146,7 @@ Testing Phase:
|
||||
|
||||
### Vague Feature Request Pattern
|
||||
```
|
||||
User: "アプリに認証機能作りたい"
|
||||
User: "I want to add authentication to the app"
|
||||
|
||||
PM Agent Workflow:
|
||||
1. Activate Brainstorming Mode
|
||||
@@ -297,19 +297,19 @@ Output: Frontend-optimized implementation
|
||||
Error Detection Protocol:
|
||||
1. Error Occurs:
|
||||
→ STOP: Never re-execute the same command immediately
|
||||
→ Question: "なぜこのエラーが出たのか?"
|
||||
→ Question: "Why did this error occur?"
|
||||
|
||||
2. Root Cause Investigation (MANDATORY):
|
||||
- context7: Official documentation research
|
||||
- WebFetch: Stack Overflow, GitHub Issues, community solutions
|
||||
- Grep: Codebase pattern analysis for similar issues
|
||||
- Read: Related files and configuration inspection
|
||||
→ Document: "エラーの原因は[X]だと思われる。なぜなら[証拠Y]"
|
||||
→ Document: "The cause of the error is likely [X], because [evidence Y]"
|
||||
|
||||
3. Hypothesis Formation:
|
||||
- Create docs/pdca/[feature]/hypothesis-error-fix.md
|
||||
- State: "原因は[X]。根拠: [Y]。解決策: [Z]"
|
||||
- Rationale: "[なぜこの方法なら解決するか]"
|
||||
- State: "Cause: [X]. Evidence: [Y]. Solution: [Z]"
|
||||
- Rationale: "[Why this approach will solve the problem]"
|
||||
|
||||
4. Solution Design (MUST BE DIFFERENT):
|
||||
- Previous Approach A failed → Design Approach B
|
||||
@@ -325,22 +325,22 @@ Error Detection Protocol:
|
||||
- Failure → Return to Step 2 with new hypothesis
|
||||
- Document: docs/pdca/[feature]/do.md (trial-and-error log)
|
||||
|
||||
Anti-Patterns (絶対禁止):
|
||||
❌ "エラーが出た。もう一回やってみよう"
|
||||
❌ "再試行: 1回目... 2回目... 3回目..."
|
||||
❌ "タイムアウトだから待ち時間を増やそう" (root cause無視)
|
||||
❌ "Warningあるけど動くからOK" (将来的な技術的負債)
|
||||
Anti-Patterns (strictly prohibited):
|
||||
❌ "Got an error. Let's just try again"
|
||||
❌ "Retry: attempt 1... attempt 2... attempt 3..."
|
||||
❌ "It timed out, so let's increase the wait time" (ignoring root cause)
|
||||
❌ "There are warnings but it works, so it's fine" (future technical debt)
|
||||
|
||||
Correct Patterns (必須):
|
||||
✅ "エラーが出た。公式ドキュメントで調査"
|
||||
✅ "原因: 環境変数未設定。なぜ必要?仕様を理解"
|
||||
✅ "解決策: .env追加 + 起動時バリデーション実装"
|
||||
✅ "学習: 次回から環境変数チェックを最初に実行"
|
||||
Correct Patterns (required):
|
||||
✅ "Got an error. Investigating via official documentation"
|
||||
✅ "Cause: environment variable not set. Why is it needed? Understanding the spec"
|
||||
✅ "Solution: add to .env + implement startup validation"
|
||||
✅ "Learning: run environment variable checks first from now on"
|
||||
```
|
||||
|
||||
### Warning/Error Investigation Culture
|
||||
|
||||
**Rule: 全ての警告・エラーに興味を持って調査する**
|
||||
**Rule: Investigate every warning and error with curiosity**
|
||||
|
||||
```yaml
|
||||
Zero Tolerance for Dismissal:
|
||||
@@ -372,7 +372,7 @@ Zero Tolerance for Dismissal:
|
||||
5. Learning: Deprecation = future breaking change
|
||||
6. Document: docs/pdca/[feature]/do.md
|
||||
|
||||
Example - Wrong Behavior (禁止):
|
||||
Example - Wrong Behavior (prohibited):
|
||||
Warning: "Deprecated API usage"
|
||||
PM Agent: "Probably fine, ignoring" ❌ NEVER DO THIS
|
||||
|
||||
@@ -396,17 +396,17 @@ session/:
|
||||
session/checkpoint # Progress snapshots (30-min intervals)
|
||||
|
||||
plan/:
|
||||
plan/[feature]/hypothesis # Plan phase: 仮説・設計
|
||||
plan/[feature]/hypothesis # Plan phase: hypothesis and design
|
||||
plan/[feature]/architecture # Architecture decisions
|
||||
plan/[feature]/rationale # Why this approach chosen
|
||||
|
||||
execution/:
|
||||
execution/[feature]/do # Do phase: 実験・試行錯誤
|
||||
execution/[feature]/do # Do phase: experimentation and trial-and-error
|
||||
execution/[feature]/errors # Error log with timestamps
|
||||
execution/[feature]/solutions # Solution attempts log
|
||||
|
||||
evaluation/:
|
||||
evaluation/[feature]/check # Check phase: 評価・分析
|
||||
evaluation/[feature]/check # Check phase: evaluation and analysis
|
||||
evaluation/[feature]/metrics # Quality metrics (coverage, performance)
|
||||
evaluation/[feature]/lessons # What worked, what failed
|
||||
|
||||
@@ -434,32 +434,32 @@ Example Usage:
|
||||
**Location: `docs/pdca/[feature-name]/`**
|
||||
|
||||
```yaml
|
||||
Structure (明確・わかりやすい):
|
||||
Structure (clear and intuitive):
|
||||
docs/pdca/[feature-name]/
|
||||
├── plan.md # Plan: 仮説・設計
|
||||
├── do.md # Do: 実験・試行錯誤
|
||||
├── check.md # Check: 評価・分析
|
||||
└── act.md # Act: 改善・次アクション
|
||||
├── plan.md # Plan: hypothesis and design
|
||||
├── do.md # Do: experimentation and trial-and-error
|
||||
├── check.md # Check: evaluation and analysis
|
||||
└── act.md # Act: improvement and next actions
|
||||
|
||||
Template - plan.md:
|
||||
# Plan: [Feature Name]
|
||||
|
||||
## Hypothesis
|
||||
[何を実装するか、なぜそのアプローチか]
|
||||
[What to implement and why this approach]
|
||||
|
||||
## Expected Outcomes (定量的)
|
||||
## Expected Outcomes (quantitative)
|
||||
- Test Coverage: 45% → 85%
|
||||
- Implementation Time: ~4 hours
|
||||
- Security: OWASP compliance
|
||||
|
||||
## Risks & Mitigation
|
||||
- [Risk 1] → [対策]
|
||||
- [Risk 2] → [対策]
|
||||
- [Risk 1] → [mitigation]
|
||||
- [Risk 2] → [mitigation]
|
||||
|
||||
Template - do.md:
|
||||
# Do: [Feature Name]
|
||||
|
||||
## Implementation Log (時系列)
|
||||
## Implementation Log (chronological)
|
||||
- 10:00 Started auth middleware implementation
|
||||
- 10:30 Error: JWTError - SUPABASE_JWT_SECRET undefined
|
||||
→ Investigation: context7 "Supabase JWT configuration"
|
||||
@@ -525,7 +525,7 @@ Lifecycle:
|
||||
### Implementation Documentation
|
||||
```yaml
|
||||
After each successful implementation:
|
||||
- Create docs/patterns/[feature-name].md (清書)
|
||||
- Create docs/patterns/[feature-name].md (formalized)
|
||||
- Document architecture decisions in ADR format
|
||||
- Update CLAUDE.md with new best practices
|
||||
- write_memory("learning/patterns/[name]", reusable_pattern)
|
||||
|
||||
@@ -5,8 +5,29 @@
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "./scripts/session-init.sh",
|
||||
"timeout": 10
|
||||
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/session-init.sh",
|
||||
"timeout": 10000
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"Stop": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "prompt",
|
||||
"prompt": "Before ending, check if there are uncommitted changes or incomplete tasks. If so, briefly note what remains to be done."
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Write|Edit",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "prompt",
|
||||
"prompt": "Verify the edit was correct: check for syntax errors, missing imports, or broken logic in the changed file. If issues found, fix them immediately."
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
---
|
||||
name: brainstorm
|
||||
description: Activate brainstorming mode for collaborative discovery and creative problem-solving. Use when users have vague requests, want to explore ideas, or need requirements discovery.
|
||||
---
|
||||
|
||||
# Brainstorming Mode
|
||||
|
||||
You are now in Brainstorming Mode. Use Socratic dialogue to explore ideas.
|
||||
|
||||
## Approach
|
||||
|
||||
1. **Ask, Don't Assume**: Use probing questions to uncover requirements
|
||||
2. **Diverge First**: Generate multiple options before narrowing
|
||||
3. **Build on Ideas**: Use "Yes, and..." thinking
|
||||
4. **Visualize**: Use tables, lists, and comparisons
|
||||
5. **Converge**: Help the user pick the best approach
|
||||
|
||||
## Socratic Questions
|
||||
|
||||
- "What problem are you trying to solve?"
|
||||
- "Who are the users? What do they need?"
|
||||
- "What constraints do we have? (time, budget, tech stack)"
|
||||
- "What does success look like?"
|
||||
- "What are the risks if we don't do this?"
|
||||
|
||||
## Output Format
|
||||
|
||||
Present ideas as structured options:
|
||||
|
||||
```
|
||||
## Option A: [Name]
|
||||
- Pros: [...]
|
||||
- Cons: [...]
|
||||
- Effort: [Low/Medium/High]
|
||||
- Risk: [Low/Medium/High]
|
||||
|
||||
## Option B: [Name]
|
||||
...
|
||||
|
||||
## Recommendation
|
||||
[Which option and why]
|
||||
```
|
||||
|
||||
Apply this to: $ARGUMENTS
|
||||
@@ -0,0 +1,47 @@
|
||||
---
|
||||
name: deep-research
|
||||
description: Activate deep research mode for systematic investigation. Use when the user asks to research, investigate, explore, or needs current information with citations.
|
||||
---
|
||||
|
||||
# Deep Research Mode
|
||||
|
||||
You are now in Deep Research Mode. Follow this systematic investigation process:
|
||||
|
||||
## Research Protocol
|
||||
|
||||
1. **Scope Definition**: Clarify the research question and boundaries
|
||||
2. **Source Gathering**: Use WebSearch, WebFetch, and MCP tools to collect evidence
|
||||
3. **Evidence Evaluation**: Assess source credibility and relevance
|
||||
4. **Synthesis**: Combine findings into a coherent analysis
|
||||
5. **Citation**: Always cite sources with URLs
|
||||
|
||||
## Requirements
|
||||
|
||||
- Every claim must have a source
|
||||
- Present multiple perspectives when they exist
|
||||
- Distinguish between facts, consensus, and speculation
|
||||
- Use tables for comparisons
|
||||
- Provide a confidence level for conclusions (high/medium/low)
|
||||
- Include a "Sources" section at the end
|
||||
|
||||
## Output Format
|
||||
|
||||
```
|
||||
## Research: [Topic]
|
||||
|
||||
### Key Findings
|
||||
- Finding 1 (Source: [URL])
|
||||
- Finding 2 (Source: [URL])
|
||||
|
||||
### Analysis
|
||||
[Synthesized analysis with inline citations]
|
||||
|
||||
### Confidence: [High/Medium/Low]
|
||||
[Reasoning for confidence level]
|
||||
|
||||
### Sources
|
||||
1. [Title](URL) - [Brief description]
|
||||
2. [Title](URL) - [Brief description]
|
||||
```
|
||||
|
||||
Apply this to: $ARGUMENTS
|
||||
@@ -0,0 +1,54 @@
|
||||
---
|
||||
name: pm
|
||||
description: Project management with PDCA cycles, confidence checks, and context persistence. Auto-activates at session start to restore context. Use for task planning, progress tracking, and structured development.
|
||||
---
|
||||
|
||||
# PM Agent Mode
|
||||
|
||||
You are the Project Management Agent. Manage development through PDCA cycles.
|
||||
|
||||
## Session Start Protocol
|
||||
|
||||
1. Check for existing context (docs/memory/, TASK.md, KNOWLEDGE.md)
|
||||
2. Report status to user:
|
||||
- Previous: [last session summary]
|
||||
- Progress: [current status]
|
||||
- Next: [planned actions]
|
||||
- Blockers: [issues]
|
||||
|
||||
## PDCA Cycle
|
||||
|
||||
### Plan (Hypothesis)
|
||||
- Define what to implement and why
|
||||
- Set success criteria
|
||||
- Identify risks
|
||||
|
||||
### Do (Experiment)
|
||||
- Track tasks with TodoWrite
|
||||
- Record trial-and-error, errors, solutions
|
||||
- Checkpoint progress regularly
|
||||
|
||||
### Check (Evaluation)
|
||||
- "What went well? What failed?"
|
||||
- Assess against success criteria
|
||||
- Identify lessons learned
|
||||
|
||||
### Act (Improvement)
|
||||
- Success: Document pattern for reuse
|
||||
- Failure: Document mistake with prevention measures
|
||||
- Update project knowledge base
|
||||
|
||||
## Confidence Check (before implementation)
|
||||
|
||||
Assess confidence on 5 dimensions:
|
||||
1. No duplicate implementations? (25%)
|
||||
2. Architecture compliant? (25%)
|
||||
3. Official docs verified? (20%)
|
||||
4. OSS references checked? (15%)
|
||||
5. Root cause identified? (15%)
|
||||
|
||||
- >=90%: Proceed immediately
|
||||
- 70-89%: Present alternatives, investigate more
|
||||
- <70%: STOP and gather more information
|
||||
|
||||
Apply this to: $ARGUMENTS
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
name: token-efficiency
|
||||
description: Activate ultra-compressed output mode for maximum token efficiency. Use when context is running low, user requests brevity, or dealing with large-scale operations.
|
||||
---
|
||||
|
||||
# Token Efficiency Mode
|
||||
|
||||
Minimize token usage while preserving information quality (>=95%).
|
||||
|
||||
## Rules
|
||||
|
||||
- Use bullet points and tables, never verbose paragraphs
|
||||
- Abbreviate common terms (fn=function, impl=implementation, cfg=config)
|
||||
- Use symbols for status: OK, FAIL, WARN, SKIP
|
||||
- One sentence per concept
|
||||
- Code blocks only — no prose explanations of code
|
||||
- Skip preamble, greetings, and transitions
|
||||
- Target: 30-50% token reduction vs normal output
|
||||
@@ -0,0 +1,40 @@
|
||||
---
|
||||
name: troubleshoot
|
||||
description: Systematic troubleshooting with root cause analysis. Use when users report errors, bugs, or unexpected behavior. Never retry without understanding why.
|
||||
---
|
||||
|
||||
# Troubleshooting Protocol
|
||||
|
||||
Follow this systematic root cause analysis process. NEVER retry the same approach without understanding WHY it failed.
|
||||
|
||||
## Protocol
|
||||
|
||||
1. **STOP**: Do not re-execute the same command
|
||||
2. **Observe**: What exactly happened? What was expected?
|
||||
3. **Hypothesize**: What could cause this? (list 2-3 possibilities)
|
||||
4. **Investigate**: Check official docs, logs, stack traces, config
|
||||
5. **Root Cause**: Identify the fundamental cause (not symptoms)
|
||||
6. **Fix**: Implement a solution that addresses the root cause
|
||||
7. **Verify**: Confirm the fix works
|
||||
8. **Learn**: Document the solution for future reference
|
||||
|
||||
## Anti-Patterns (strictly prohibited)
|
||||
|
||||
- "Got an error. Let's just try again"
|
||||
- "Retry: attempt 1... attempt 2... attempt 3..."
|
||||
- "It timed out, so let's increase the wait time" (ignoring root cause)
|
||||
- "There are warnings but it works, so it's fine" (future technical debt)
|
||||
|
||||
## Required Format
|
||||
|
||||
```
|
||||
## Root Cause Analysis
|
||||
|
||||
**Error**: [Exact error message]
|
||||
**Expected**: [What should have happened]
|
||||
**Cause**: [Root cause with evidence]
|
||||
**Fix**: [Solution addressing root cause]
|
||||
**Prevention**: [How to prevent recurrence]
|
||||
```
|
||||
|
||||
Apply this to: $ARGUMENTS
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "superclaude"
|
||||
version = "4.2.0"
|
||||
version = "4.3.0"
|
||||
description = "AI-enhanced development framework for Claude Code - pytest plugin with optional skills"
|
||||
readme = "README.md"
|
||||
license = {text = "MIT"}
|
||||
|
||||
Executable
+959
@@ -0,0 +1,959 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
SuperClaude Framework Sync Script
|
||||
Automated pull-sync with namespace isolation for Plugin distribution
|
||||
|
||||
This script synchronizes content from SuperClaude_Framework repository and
|
||||
transforms it for distribution as a Claude Code plugin with proper namespace
|
||||
isolation (sc: prefix for commands, sc- prefix for filenames).
|
||||
|
||||
Usage:
|
||||
python scripts/sync_from_framework.py [OPTIONS]
|
||||
|
||||
Options:
|
||||
--framework-repo URL Framework repository URL
|
||||
--plugin-root PATH Plugin repository root path
|
||||
--dry-run Preview changes without applying
|
||||
--output-report PATH Save sync report to file
|
||||
"""
|
||||
|
||||
import sys
|
||||
import argparse
|
||||
import tempfile
|
||||
import shutil
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Tuple, Optional
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
from dataclasses import dataclass, asdict
|
||||
from datetime import datetime
|
||||
import logging
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ProtectionViolationError(RuntimeError):
|
||||
"""Raised when sync would overwrite a Plugin-owned file listed in PROTECTED_PATHS."""
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class SyncResult:
|
||||
"""Results from sync operation."""
|
||||
success: bool
|
||||
timestamp: str
|
||||
framework_commit: str
|
||||
framework_version: str
|
||||
files_synced: int
|
||||
files_modified: int
|
||||
commands_transformed: int
|
||||
agents_transformed: int
|
||||
mcp_servers_merged: int
|
||||
warnings: List[str]
|
||||
errors: List[str]
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
class ContentTransformer:
|
||||
"""Transforms Framework content for Plugin namespace."""
|
||||
|
||||
# Regex patterns for transformation
|
||||
COMMAND_HEADER_PATTERN = re.compile(r'^(#+\s+)/(\w+)', re.MULTILINE)
|
||||
COMMAND_REF_PATTERN = re.compile(r'(?<![/\w])/(\w+)(?=\s|$|:|`|\)|\])')
|
||||
LINK_REF_PATTERN = re.compile(r'\[/(\w+)\]')
|
||||
FRONTMATTER_NAME_PATTERN = re.compile(r'^name:\s*(.+)$', re.MULTILINE)
|
||||
|
||||
@staticmethod
|
||||
def transform_command(content: str, filename: str) -> str:
|
||||
"""
|
||||
Transform command content for sc: namespace.
|
||||
|
||||
Transformations:
|
||||
- Header: # /brainstorm → # /sc:brainstorm
|
||||
- References: /analyze → /sc:analyze
|
||||
- Links: [/task] → [/sc:task]
|
||||
|
||||
Args:
|
||||
content: Original command file content
|
||||
filename: Command filename (for logging)
|
||||
|
||||
Returns:
|
||||
Transformed content with sc: namespace
|
||||
"""
|
||||
logger.debug(f"Transforming command: {filename}")
|
||||
|
||||
# Transform main header
|
||||
content = ContentTransformer.COMMAND_HEADER_PATTERN.sub(
|
||||
r'\1/sc:\2',
|
||||
content
|
||||
)
|
||||
|
||||
# Transform command references in text
|
||||
content = ContentTransformer.COMMAND_REF_PATTERN.sub(
|
||||
r'/sc:\1',
|
||||
content
|
||||
)
|
||||
|
||||
# Transform command references in links
|
||||
content = ContentTransformer.LINK_REF_PATTERN.sub(
|
||||
r'[/sc:\1]',
|
||||
content
|
||||
)
|
||||
|
||||
return content
|
||||
|
||||
@staticmethod
|
||||
def transform_agent(content: str, filename: str) -> str:
|
||||
"""
|
||||
Transform agent frontmatter name.
|
||||
|
||||
Transformations:
|
||||
- name: backend-architect → name: sc-backend-architect
|
||||
|
||||
Args:
|
||||
content: Original agent file content
|
||||
filename: Agent filename (for logging)
|
||||
|
||||
Returns:
|
||||
Transformed content with sc- prefix in name field
|
||||
"""
|
||||
logger.debug(f"Transforming agent: {filename}")
|
||||
|
||||
# Parse frontmatter
|
||||
frontmatter_pattern = re.compile(
|
||||
r'^---\n(.*?)\n---',
|
||||
re.DOTALL | re.MULTILINE
|
||||
)
|
||||
|
||||
match = frontmatter_pattern.search(content)
|
||||
if not match:
|
||||
logger.warning(f"No frontmatter found in agent: {filename}")
|
||||
return content
|
||||
|
||||
frontmatter = match.group(1)
|
||||
|
||||
# Transform name field (add sc- prefix if not already present)
|
||||
def add_prefix(match):
|
||||
name = match.group(1).strip()
|
||||
if not name.startswith('sc-'):
|
||||
return f'name: sc-{name}'
|
||||
return match.group(0)
|
||||
|
||||
frontmatter = ContentTransformer.FRONTMATTER_NAME_PATTERN.sub(
|
||||
add_prefix,
|
||||
frontmatter
|
||||
)
|
||||
|
||||
# Replace frontmatter
|
||||
content = frontmatter_pattern.sub(
|
||||
f'---\n{frontmatter}\n---',
|
||||
content,
|
||||
count=1
|
||||
)
|
||||
|
||||
return content
|
||||
|
||||
|
||||
class FileSyncer:
|
||||
"""Handles file synchronization with git integration."""
|
||||
|
||||
def __init__(self, plugin_root: Path, dry_run: bool = False):
|
||||
self.plugin_root = plugin_root
|
||||
self.dry_run = dry_run
|
||||
self.git_available = self._check_git()
|
||||
|
||||
def _check_git(self) -> bool:
|
||||
"""Check if git is available and repo is initialized."""
|
||||
try:
|
||||
subprocess.run(
|
||||
['git', 'rev-parse', '--git-dir'],
|
||||
cwd=self.plugin_root,
|
||||
capture_output=True,
|
||||
check=True
|
||||
)
|
||||
return True
|
||||
except (subprocess.CalledProcessError, FileNotFoundError):
|
||||
logger.warning("Git not available - file operations will not preserve history")
|
||||
return False
|
||||
|
||||
def sync_directory(
|
||||
self,
|
||||
source_dir: Path,
|
||||
dest_dir: Path,
|
||||
filename_prefix: str = "",
|
||||
transform_fn=None
|
||||
) -> Dict[str, int]:
|
||||
"""
|
||||
Sync directory with namespace prefix and transformation.
|
||||
|
||||
Args:
|
||||
source_dir: Source directory path
|
||||
dest_dir: Destination directory path
|
||||
filename_prefix: Prefix to add to filenames (e.g., 'sc-')
|
||||
transform_fn: Optional content transformation function
|
||||
|
||||
Returns:
|
||||
Statistics dict with counts of synced/modified files
|
||||
"""
|
||||
stats = {'synced': 0, 'modified': 0, 'renamed': 0}
|
||||
|
||||
if not source_dir.exists():
|
||||
logger.warning(f"Source directory not found: {source_dir}")
|
||||
return stats
|
||||
|
||||
dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Get existing files in dest (with sc- prefix)
|
||||
existing_files = {f.name: f for f in dest_dir.glob('*.md')}
|
||||
synced_files = set()
|
||||
|
||||
for source_file in source_dir.glob('*.md'):
|
||||
# Apply filename prefix
|
||||
new_name = f"{filename_prefix}{source_file.name}"
|
||||
synced_files.add(new_name)
|
||||
dest_file = dest_dir / new_name
|
||||
|
||||
# Read and transform content
|
||||
content = source_file.read_text(encoding='utf-8')
|
||||
if transform_fn:
|
||||
content = transform_fn(content, source_file.name)
|
||||
|
||||
# Check if file exists with different name (needs git mv)
|
||||
old_unprefixed = source_file.name
|
||||
old_file_path = dest_dir / old_unprefixed
|
||||
|
||||
if old_file_path.exists() and new_name != old_unprefixed:
|
||||
# File needs renaming: use git mv to preserve history
|
||||
if self.git_available:
|
||||
self._git_mv(old_file_path, dest_file)
|
||||
stats['renamed'] += 1
|
||||
else:
|
||||
# Fallback to regular rename
|
||||
if not self.dry_run:
|
||||
old_file_path.rename(dest_file)
|
||||
stats['renamed'] += 1
|
||||
logger.info(f" 📝 Renamed: {old_unprefixed} → {new_name}")
|
||||
|
||||
# Write content
|
||||
if not self.dry_run:
|
||||
dest_file.write_text(content, encoding='utf-8')
|
||||
|
||||
if dest_file.exists():
|
||||
stats['modified'] += 1
|
||||
else:
|
||||
stats['synced'] += 1
|
||||
|
||||
# Remove files that no longer exist in source
|
||||
# (only remove files with prefix that aren't in synced set)
|
||||
for filename, filepath in existing_files.items():
|
||||
if filename.startswith(filename_prefix) and filename not in synced_files:
|
||||
if not self.dry_run:
|
||||
filepath.unlink()
|
||||
logger.info(f" 🗑️ Removed: {filepath.relative_to(self.plugin_root)}")
|
||||
|
||||
return stats
|
||||
|
||||
def _git_mv(self, old_path: Path, new_path: Path):
|
||||
"""Use git mv to preserve history."""
|
||||
if self.dry_run:
|
||||
logger.info(f" [DRY RUN] git mv {old_path.name} {new_path.name}")
|
||||
return
|
||||
|
||||
try:
|
||||
subprocess.run(
|
||||
['git', 'mv', str(old_path), str(new_path)],
|
||||
cwd=self.plugin_root,
|
||||
check=True,
|
||||
capture_output=True
|
||||
)
|
||||
logger.info(f" 📝 Renamed (git mv): {old_path.name} → {new_path.name}")
|
||||
except subprocess.CalledProcessError as e:
|
||||
# Fallback to regular rename
|
||||
logger.warning(f" ⚠️ Git mv failed, using regular rename: {e}")
|
||||
old_path.rename(new_path)
|
||||
|
||||
def copy_directory(self, source_dir: Path, dest_dir: Path) -> int:
|
||||
"""
|
||||
Copy directory contents as-is (no transformation).
|
||||
|
||||
Args:
|
||||
source_dir: Source directory path
|
||||
dest_dir: Destination directory path
|
||||
|
||||
Returns:
|
||||
Number of files copied
|
||||
"""
|
||||
if not source_dir.exists():
|
||||
logger.warning(f"Source directory not found: {source_dir}")
|
||||
return 0
|
||||
|
||||
dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
count = 0
|
||||
|
||||
for source_file in source_dir.glob('**/*'):
|
||||
if source_file.is_file():
|
||||
rel_path = source_file.relative_to(source_dir)
|
||||
dest_file = dest_dir / rel_path
|
||||
dest_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if not self.dry_run:
|
||||
shutil.copy2(source_file, dest_file)
|
||||
|
||||
count += 1
|
||||
logger.debug(f" 📄 Copied: {rel_path}")
|
||||
|
||||
return count
|
||||
|
||||
|
||||
class PluginJsonGenerator:
|
||||
"""Generates .claude-plugin/plugin.json from synced commands."""
|
||||
|
||||
def __init__(self, plugin_root: Path):
|
||||
self.plugin_root = plugin_root
|
||||
|
||||
def generate(self, framework_version: str) -> dict:
|
||||
"""
|
||||
Generate plugin.json with command mappings.
|
||||
|
||||
Args:
|
||||
framework_version: Version from Framework repository
|
||||
|
||||
Returns:
|
||||
Complete plugin.json dictionary
|
||||
"""
|
||||
commands_dir = self.plugin_root / 'commands'
|
||||
|
||||
# Base metadata from existing plugin.json
|
||||
root_plugin_json = self.plugin_root / 'plugin.json'
|
||||
if root_plugin_json.exists():
|
||||
base_metadata = json.loads(root_plugin_json.read_text())
|
||||
else:
|
||||
base_metadata = {
|
||||
"name": "sc",
|
||||
"description": "SuperClaude Plugin",
|
||||
"author": {"name": "SuperClaude Team"},
|
||||
"license": "MIT"
|
||||
}
|
||||
|
||||
# Build command mappings
|
||||
commands = {}
|
||||
if commands_dir.exists():
|
||||
for cmd_file in sorted(commands_dir.glob('sc-*.md')):
|
||||
# Extract command name from filename
|
||||
# sc-brainstorm.md → brainstorm
|
||||
cmd_name = cmd_file.stem.replace('sc-', '')
|
||||
|
||||
# Map sc:brainstorm to path
|
||||
commands[f"sc:{cmd_name}"] = f"commands/{cmd_file.name}"
|
||||
|
||||
plugin_json = {
|
||||
"name": "sc",
|
||||
"version": framework_version,
|
||||
"description": base_metadata.get("description", ""),
|
||||
"author": base_metadata.get("author", {}),
|
||||
"homepage": base_metadata.get("homepage", ""),
|
||||
"repository": base_metadata.get("repository", ""),
|
||||
"license": base_metadata.get("license", "MIT"),
|
||||
"keywords": base_metadata.get("keywords", [])
|
||||
}
|
||||
|
||||
logger.info(f"✅ Generated plugin.json with {len(commands)} commands")
|
||||
|
||||
return plugin_json
|
||||
|
||||
def write(self, plugin_json: dict, dry_run: bool = False):
|
||||
"""Write plugin.json to .claude-plugin/ directory."""
|
||||
output_path = self.plugin_root / '.claude-plugin' / 'plugin.json'
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if dry_run:
|
||||
logger.info(f"[DRY RUN] Would write plugin.json to: {output_path}")
|
||||
logger.info(json.dumps(plugin_json, indent=2))
|
||||
return
|
||||
|
||||
output_path.write_text(
|
||||
json.dumps(plugin_json, indent=2) + '\n',
|
||||
encoding='utf-8'
|
||||
)
|
||||
logger.info(f"✅ Written: {output_path}")
|
||||
|
||||
|
||||
class McpMerger:
|
||||
"""Safely merges MCP server configurations."""
|
||||
|
||||
def __init__(self, plugin_root: Path):
|
||||
self.plugin_root = plugin_root
|
||||
|
||||
def merge(
|
||||
self,
|
||||
framework_mcp: dict,
|
||||
plugin_mcp: dict
|
||||
) -> Tuple[dict, List[str]]:
|
||||
"""
|
||||
Merge MCP configurations with conflict detection.
|
||||
|
||||
Strategy:
|
||||
- Framework servers take precedence
|
||||
- Preserve Plugin-specific servers
|
||||
- Log warnings for conflicts
|
||||
|
||||
Args:
|
||||
framework_mcp: MCP servers from Framework
|
||||
plugin_mcp: MCP servers from Plugin
|
||||
|
||||
Returns:
|
||||
(merged_config, warnings)
|
||||
"""
|
||||
merged = {}
|
||||
warnings = []
|
||||
|
||||
# Add Framework servers (source of truth)
|
||||
for name, config in framework_mcp.items():
|
||||
merged[name] = config
|
||||
|
||||
# Add Plugin-specific servers if not in Framework
|
||||
for name, config in plugin_mcp.items():
|
||||
if name not in merged:
|
||||
merged[name] = config
|
||||
warnings.append(
|
||||
f"Preserved plugin-specific MCP server: {name}"
|
||||
)
|
||||
else:
|
||||
# Check if configurations differ
|
||||
if config != merged[name]:
|
||||
warnings.append(
|
||||
f"MCP server '{name}' conflict - using Framework version"
|
||||
)
|
||||
|
||||
return merged, warnings
|
||||
|
||||
def backup_current(self) -> Optional[Path]:
|
||||
"""Create backup of current plugin.json."""
|
||||
plugin_json = self.plugin_root / 'plugin.json'
|
||||
if not plugin_json.exists():
|
||||
return None
|
||||
|
||||
backup_dir = self.plugin_root / 'backups'
|
||||
backup_dir.mkdir(exist_ok=True)
|
||||
|
||||
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
||||
backup_path = backup_dir / f'plugin.json.{timestamp}.backup'
|
||||
|
||||
shutil.copy2(plugin_json, backup_path)
|
||||
logger.info(f"📦 Backup created: {backup_path}")
|
||||
|
||||
return backup_path
|
||||
|
||||
|
||||
class FrameworkSyncer:
|
||||
"""Main orchestrator for Framework → Plugin sync."""
|
||||
|
||||
# ── SYNC MAPPINGS ──────────────────────────────────────────────────────────
|
||||
# What to pull from Framework and transform for Plugin distribution.
|
||||
# Symmetric pair with PROTECTED_PATHS below: a path appears in one or the other,
|
||||
# never both.
|
||||
SYNC_MAPPINGS = {
|
||||
"src/superclaude/commands": "commands", # /cmd → /sc:cmd, sc- prefix
|
||||
"src/superclaude/agents": "agents", # name → sc-name in frontmatter
|
||||
# core/ and modes/ are intentionally absent — they live in PROTECTED_PATHS
|
||||
}
|
||||
|
||||
# ── PROTECTED PATHS ────────────────────────────────────────────────────────
|
||||
# Plugin-owned files and directories that must NEVER be overwritten by sync,
|
||||
# regardless of what the Framework contains.
|
||||
#
|
||||
# Algorithm: before sync → hash all protected paths → after sync → re-hash
|
||||
# and raise ProtectionViolationError if anything changed.
|
||||
#
|
||||
# To move a path from protected to synced: remove it here, add to SYNC_MAPPINGS.
|
||||
PROTECTED_PATHS: List[str] = [
|
||||
# Plugin-specific documentation (Plugin spec, not Framework spec)
|
||||
"README.md",
|
||||
"README-ja.md",
|
||||
"README-zh.md",
|
||||
"BACKUP_GUIDE.md",
|
||||
"MIGRATION_GUIDE.md",
|
||||
"SECURITY.md",
|
||||
"CLAUDE.md",
|
||||
"LICENSE",
|
||||
".gitignore",
|
||||
# Plugin configuration & marketplace metadata
|
||||
".claude-plugin/",
|
||||
# Plugin infrastructure (workflows, scripts, tests are Plugin-owned)
|
||||
".github/",
|
||||
"docs/",
|
||||
"scripts/",
|
||||
"tests/",
|
||||
"backups/",
|
||||
# Plugin-customized behavioral content
|
||||
# Plugin maintains its own tuned versions; Framework versions are ignored.
|
||||
"core/",
|
||||
"modes/",
|
||||
]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
framework_repo: str,
|
||||
plugin_root: Path,
|
||||
dry_run: bool = False
|
||||
):
|
||||
self.framework_repo = framework_repo
|
||||
self.plugin_root = plugin_root
|
||||
self.dry_run = dry_run
|
||||
self.temp_dir = None
|
||||
self.warnings = []
|
||||
self.errors = []
|
||||
|
||||
def sync(self) -> SyncResult:
|
||||
"""Execute full sync workflow."""
|
||||
try:
|
||||
logger.info("🔄 Starting Framework sync...")
|
||||
|
||||
# Step 1: Clone Framework
|
||||
framework_path = self._clone_framework()
|
||||
framework_commit = self._get_commit_hash(framework_path)
|
||||
framework_version = self._get_version(framework_path)
|
||||
|
||||
logger.info(f"📦 Framework version: {framework_version}")
|
||||
logger.info(f"📝 Framework commit: {framework_commit[:8]}")
|
||||
|
||||
# Step 2: Snapshot protected files BEFORE any changes
|
||||
protection_snapshot = self._snapshot_protected_files()
|
||||
|
||||
# Step 3: Create backup
|
||||
self._create_backup()
|
||||
|
||||
# Step 4: Transform and sync content
|
||||
stats = self._sync_content(framework_path)
|
||||
|
||||
# Step 5: Verify protected files were NOT touched
|
||||
self._validate_protected_files(protection_snapshot)
|
||||
|
||||
# Step 6: Generate plugin.json
|
||||
self._generate_plugin_json(framework_version)
|
||||
|
||||
# Step 7: Merge MCP configurations
|
||||
mcp_merged = self._merge_mcp_configs(framework_path)
|
||||
|
||||
# Step 8: Validate sync results
|
||||
self._validate_sync()
|
||||
|
||||
logger.info("✅ Sync completed successfully!")
|
||||
|
||||
return SyncResult(
|
||||
success=True,
|
||||
timestamp=datetime.now().isoformat(),
|
||||
framework_commit=framework_commit,
|
||||
framework_version=framework_version,
|
||||
files_synced=stats['files_synced'],
|
||||
files_modified=stats['files_modified'],
|
||||
commands_transformed=stats['commands'],
|
||||
agents_transformed=stats['agents'],
|
||||
mcp_servers_merged=mcp_merged,
|
||||
warnings=self.warnings,
|
||||
errors=self.errors
|
||||
)
|
||||
|
||||
except ProtectionViolationError as e:
|
||||
# Protection violations are logged already; surface them clearly in the report
|
||||
self.errors.append(str(e))
|
||||
return SyncResult(
|
||||
success=False,
|
||||
timestamp=datetime.now().isoformat(),
|
||||
framework_commit="",
|
||||
framework_version="",
|
||||
files_synced=0,
|
||||
files_modified=0,
|
||||
commands_transformed=0,
|
||||
agents_transformed=0,
|
||||
mcp_servers_merged=0,
|
||||
warnings=self.warnings,
|
||||
errors=self.errors
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"❌ Sync failed: {e}", exc_info=True)
|
||||
self.errors.append(str(e))
|
||||
return SyncResult(
|
||||
success=False,
|
||||
timestamp=datetime.now().isoformat(),
|
||||
framework_commit="",
|
||||
framework_version="",
|
||||
files_synced=0,
|
||||
files_modified=0,
|
||||
commands_transformed=0,
|
||||
agents_transformed=0,
|
||||
mcp_servers_merged=0,
|
||||
warnings=self.warnings,
|
||||
errors=self.errors
|
||||
)
|
||||
finally:
|
||||
self._cleanup()
|
||||
|
||||
# ── Protection helpers ─────────────────────────────────────────────────────
|
||||
|
||||
@staticmethod
|
||||
def _hash_file(path: Path) -> str:
|
||||
"""Return SHA-256 hex digest of a file's contents."""
|
||||
h = hashlib.sha256()
|
||||
h.update(path.read_bytes())
|
||||
return h.hexdigest()
|
||||
|
||||
def _snapshot_protected_files(self) -> Dict[str, str]:
|
||||
"""
|
||||
Hash every file that lives under a PROTECTED_PATHS entry.
|
||||
|
||||
Called BEFORE sync begins so we have a baseline to compare against.
|
||||
|
||||
Returns:
|
||||
Mapping of relative-path-string → SHA-256 hex digest.
|
||||
"""
|
||||
snapshot: Dict[str, str] = {}
|
||||
for protected in self.PROTECTED_PATHS:
|
||||
target = self.plugin_root / protected
|
||||
if target.is_file():
|
||||
rel = protected
|
||||
snapshot[rel] = self._hash_file(target)
|
||||
elif target.is_dir():
|
||||
for f in sorted(target.rglob('*')):
|
||||
if f.is_file():
|
||||
rel = str(f.relative_to(self.plugin_root))
|
||||
snapshot[rel] = self._hash_file(f)
|
||||
logger.info(f"🔒 Protection snapshot: {len(snapshot)} Plugin-owned files hashed")
|
||||
return snapshot
|
||||
|
||||
def _validate_protected_files(self, snapshot: Dict[str, str]) -> None:
|
||||
"""
|
||||
Re-hash every file from the snapshot and compare.
|
||||
|
||||
Called AFTER sync to verify no protected file was touched.
|
||||
|
||||
Raises:
|
||||
ProtectionViolationError: if any protected file was modified or deleted.
|
||||
"""
|
||||
violations: List[str] = []
|
||||
for rel_path, original_hash in snapshot.items():
|
||||
current = self.plugin_root / rel_path
|
||||
if not current.exists():
|
||||
violations.append(f"DELETED : {rel_path}")
|
||||
else:
|
||||
current_hash = self._hash_file(current)
|
||||
if current_hash != original_hash:
|
||||
violations.append(f"MODIFIED : {rel_path}")
|
||||
|
||||
if violations:
|
||||
msg = (
|
||||
"🚨 PROTECTION VIOLATION — sync modified Plugin-owned files:\n"
|
||||
+ "\n".join(f" • {v}" for v in violations)
|
||||
+ "\n\nFix: ensure SYNC_MAPPINGS does not target any path in PROTECTED_PATHS."
|
||||
)
|
||||
logger.error(msg)
|
||||
raise ProtectionViolationError(msg)
|
||||
|
||||
logger.info(f"🔒 Protection check passed — {len(snapshot)} Plugin-owned files unchanged")
|
||||
|
||||
# ── Core sync workflow ─────────────────────────────────────────────────────
|
||||
|
||||
def _clone_framework(self) -> Path:
|
||||
"""Clone Framework repository to temp directory."""
|
||||
logger.info(f"📥 Cloning Framework: {self.framework_repo}")
|
||||
|
||||
self.temp_dir = tempfile.mkdtemp(prefix='superclaude_framework_')
|
||||
framework_path = Path(self.temp_dir) / 'framework'
|
||||
|
||||
try:
|
||||
subprocess.run(
|
||||
['git', 'clone', '--depth', '1', self.framework_repo, str(framework_path)],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True
|
||||
)
|
||||
logger.info(f"✅ Cloned to: {framework_path}")
|
||||
return framework_path
|
||||
|
||||
except subprocess.CalledProcessError as e:
|
||||
logger.error(f"Failed to clone Framework: {e.stderr}")
|
||||
raise
|
||||
|
||||
def _get_commit_hash(self, repo_path: Path) -> str:
|
||||
"""Get current commit hash from repository."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
['git', 'rev-parse', 'HEAD'],
|
||||
cwd=repo_path,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True
|
||||
)
|
||||
return result.stdout.strip()
|
||||
except subprocess.CalledProcessError:
|
||||
return "unknown"
|
||||
|
||||
def _get_version(self, framework_path: Path) -> str:
|
||||
"""Extract version from Framework."""
|
||||
# Try to read version from plugin.json or package.json
|
||||
for version_file in ['plugin.json', 'package.json']:
|
||||
version_path = framework_path / version_file
|
||||
if version_path.exists():
|
||||
try:
|
||||
data = json.loads(version_path.read_text())
|
||||
if 'version' in data:
|
||||
return data['version']
|
||||
except (json.JSONDecodeError, KeyError):
|
||||
continue
|
||||
|
||||
# Fallback to current Plugin version
|
||||
plugin_json = self.plugin_root / 'plugin.json'
|
||||
if plugin_json.exists():
|
||||
try:
|
||||
data = json.loads(plugin_json.read_text())
|
||||
return data.get('version', '1.0.0')
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
return '1.0.0'
|
||||
|
||||
def _create_backup(self):
|
||||
"""Create backup of current plugin state."""
|
||||
logger.info("📦 Creating backup...")
|
||||
|
||||
mcp_merger = McpMerger(self.plugin_root)
|
||||
backup_path = mcp_merger.backup_current()
|
||||
|
||||
if backup_path:
|
||||
logger.info(f"✅ Backup created: {backup_path}")
|
||||
|
||||
def _sync_content(self, framework_path: Path) -> Dict[str, int]:
|
||||
"""Sync and transform content from Framework."""
|
||||
logger.info("🔄 Syncing content...")
|
||||
|
||||
file_syncer = FileSyncer(self.plugin_root, self.dry_run)
|
||||
stats = {
|
||||
'files_synced': 0,
|
||||
'files_modified': 0,
|
||||
'commands': 0,
|
||||
'agents': 0
|
||||
}
|
||||
|
||||
# Sync commands with transformation
|
||||
logger.info("📝 Syncing commands...")
|
||||
source_commands = framework_path / 'src/superclaude/commands'
|
||||
dest_commands = self.plugin_root / 'commands'
|
||||
|
||||
if source_commands.exists():
|
||||
cmd_stats = file_syncer.sync_directory(
|
||||
source_commands,
|
||||
dest_commands,
|
||||
filename_prefix='sc-',
|
||||
transform_fn=ContentTransformer.transform_command
|
||||
)
|
||||
stats['commands'] = cmd_stats['synced'] + cmd_stats['modified']
|
||||
stats['files_synced'] += cmd_stats['synced']
|
||||
stats['files_modified'] += cmd_stats['modified']
|
||||
logger.info(f"✅ Commands: {stats['commands']} transformed")
|
||||
|
||||
# Sync agents with transformation
|
||||
logger.info("📝 Syncing agents...")
|
||||
source_agents = framework_path / 'src/superclaude/agents'
|
||||
dest_agents = self.plugin_root / 'agents'
|
||||
|
||||
if source_agents.exists():
|
||||
agent_stats = file_syncer.sync_directory(
|
||||
source_agents,
|
||||
dest_agents,
|
||||
filename_prefix='sc-',
|
||||
transform_fn=ContentTransformer.transform_agent
|
||||
)
|
||||
stats['agents'] = agent_stats['synced'] + agent_stats['modified']
|
||||
stats['files_synced'] += agent_stats['synced']
|
||||
stats['files_modified'] += agent_stats['modified']
|
||||
logger.info(f"✅ Agents: {stats['agents']} transformed")
|
||||
|
||||
# core/ and modes/ are in PROTECTED_PATHS — Plugin maintains its own versions.
|
||||
# They are intentionally excluded from SYNC_MAPPINGS and will never be
|
||||
# overwritten here. To re-enable Framework sync for either directory,
|
||||
# remove it from PROTECTED_PATHS and add it back to SYNC_MAPPINGS.
|
||||
logger.info("🔒 core/ and modes/ are Plugin-owned (PROTECTED_PATHS) — skipping")
|
||||
|
||||
return stats
|
||||
|
||||
def _generate_plugin_json(self, framework_version: str):
|
||||
"""Generate plugin.json from synced commands."""
|
||||
logger.info("📄 Generating plugin.json...")
|
||||
|
||||
generator = PluginJsonGenerator(self.plugin_root)
|
||||
plugin_json = generator.generate(framework_version)
|
||||
generator.write(plugin_json, self.dry_run)
|
||||
|
||||
def _merge_mcp_configs(self, framework_path: Path) -> int:
|
||||
"""Merge MCP configurations from Framework."""
|
||||
logger.info("🔗 Merging MCP configurations...")
|
||||
|
||||
# Read Framework MCP config
|
||||
framework_plugin_json = framework_path / 'plugin.json'
|
||||
framework_mcp = {}
|
||||
|
||||
if framework_plugin_json.exists():
|
||||
try:
|
||||
data = json.loads(framework_plugin_json.read_text())
|
||||
framework_mcp = data.get('mcpServers', {})
|
||||
except json.JSONDecodeError:
|
||||
logger.warning("Failed to read Framework plugin.json")
|
||||
|
||||
# Read Plugin MCP config
|
||||
plugin_json_path = self.plugin_root / 'plugin.json'
|
||||
plugin_mcp = {}
|
||||
|
||||
if plugin_json_path.exists():
|
||||
try:
|
||||
data = json.loads(plugin_json_path.read_text())
|
||||
plugin_mcp = data.get('mcpServers', {})
|
||||
except json.JSONDecodeError:
|
||||
logger.warning("Failed to read Plugin plugin.json")
|
||||
|
||||
# Merge configurations
|
||||
merger = McpMerger(self.plugin_root)
|
||||
merged_mcp, warnings = merger.merge(framework_mcp, plugin_mcp)
|
||||
|
||||
# Log warnings
|
||||
for warning in warnings:
|
||||
logger.warning(f"⚠️ {warning}")
|
||||
self.warnings.append(warning)
|
||||
|
||||
# Update plugin.json with merged MCP config
|
||||
if not self.dry_run and plugin_json_path.exists():
|
||||
data = json.loads(plugin_json_path.read_text())
|
||||
data['mcpServers'] = merged_mcp
|
||||
plugin_json_path.write_text(
|
||||
json.dumps(data, indent=2) + '\n',
|
||||
encoding='utf-8'
|
||||
)
|
||||
|
||||
logger.info(f"✅ MCP servers merged: {len(merged_mcp)}")
|
||||
return len(merged_mcp)
|
||||
|
||||
def _validate_sync(self):
|
||||
"""Validate sync results."""
|
||||
logger.info("🔍 Validating sync...")
|
||||
|
||||
# Check commands directory
|
||||
commands_dir = self.plugin_root / 'commands'
|
||||
if commands_dir.exists():
|
||||
sc_commands = list(commands_dir.glob('sc-*.md'))
|
||||
logger.info(f"✅ Found {len(sc_commands)} sc- prefixed commands")
|
||||
|
||||
# Check agents directory
|
||||
agents_dir = self.plugin_root / 'agents'
|
||||
if agents_dir.exists():
|
||||
sc_agents = list(agents_dir.glob('sc-*.md'))
|
||||
logger.info(f"✅ Found {len(sc_agents)} sc- prefixed agents")
|
||||
|
||||
# Check plugin.json
|
||||
plugin_json_path = self.plugin_root / '.claude-plugin' / 'plugin.json'
|
||||
if plugin_json_path.exists():
|
||||
logger.info(f"✅ plugin.json exists at {plugin_json_path}")
|
||||
else:
|
||||
logger.warning("⚠️ plugin.json not found")
|
||||
|
||||
def _cleanup(self):
|
||||
"""Clean up temporary directories."""
|
||||
if self.temp_dir and Path(self.temp_dir).exists():
|
||||
shutil.rmtree(self.temp_dir)
|
||||
logger.debug(f"🧹 Cleaned up temp directory: {self.temp_dir}")
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Sync SuperClaude Framework to Plugin with namespace isolation'
|
||||
)
|
||||
parser.add_argument(
|
||||
'--framework-repo',
|
||||
default='https://github.com/SuperClaude-Org/SuperClaude_Framework',
|
||||
help='Framework repository URL'
|
||||
)
|
||||
parser.add_argument(
|
||||
'--plugin-root',
|
||||
type=Path,
|
||||
default=Path.cwd(),
|
||||
help='Plugin repository root path'
|
||||
)
|
||||
parser.add_argument(
|
||||
'--dry-run',
|
||||
type=lambda x: x.lower() in ('true', '1', 'yes'),
|
||||
default=False,
|
||||
help='Preview changes without applying'
|
||||
)
|
||||
parser.add_argument(
|
||||
'--output-report',
|
||||
type=Path,
|
||||
help='Save sync report to file'
|
||||
)
|
||||
parser.add_argument(
|
||||
'--verbose',
|
||||
action='store_true',
|
||||
help='Enable verbose logging'
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.verbose:
|
||||
logging.getLogger().setLevel(logging.DEBUG)
|
||||
|
||||
if args.dry_run:
|
||||
logger.info("🔍 DRY RUN MODE - No changes will be applied")
|
||||
|
||||
# Run sync
|
||||
syncer = FrameworkSyncer(
|
||||
framework_repo=args.framework_repo,
|
||||
plugin_root=args.plugin_root,
|
||||
dry_run=args.dry_run
|
||||
)
|
||||
|
||||
result = syncer.sync()
|
||||
|
||||
# Output report
|
||||
if args.output_report:
|
||||
args.output_report.write_text(
|
||||
json.dumps(result.to_dict(), indent=2) + '\n'
|
||||
)
|
||||
logger.info(f"📊 Report saved to: {args.output_report}")
|
||||
|
||||
# Print summary
|
||||
print("\n" + "=" * 60)
|
||||
print("SYNC SUMMARY")
|
||||
print("=" * 60)
|
||||
print(f"Success: {result.success}")
|
||||
print(f"Framework Version: {result.framework_version}")
|
||||
print(f"Framework Commit: {result.framework_commit[:8]}")
|
||||
print(f"Files Synced: {result.files_synced}")
|
||||
print(f"Files Modified: {result.files_modified}")
|
||||
print(f"Commands Transformed: {result.commands_transformed}")
|
||||
print(f"Agents Transformed: {result.agents_transformed}")
|
||||
print(f"MCP Servers Merged: {result.mcp_servers_merged}")
|
||||
|
||||
if result.warnings:
|
||||
print(f"\n⚠️ Warnings: {len(result.warnings)}")
|
||||
for warning in result.warnings:
|
||||
print(f" - {warning}")
|
||||
|
||||
if result.errors:
|
||||
print(f"\n❌ Errors: {len(result.errors)}")
|
||||
for error in result.errors:
|
||||
print(f" - {error}")
|
||||
|
||||
print("=" * 60)
|
||||
|
||||
sys.exit(0 if result.success else 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -5,7 +5,7 @@ AI-enhanced development framework for Claude Code.
|
||||
Provides pytest plugin for enhanced testing and optional skills system.
|
||||
"""
|
||||
|
||||
__version__ = "4.2.0"
|
||||
__version__ = "4.3.0"
|
||||
__author__ = "NomenAK, Mithun Gowda B"
|
||||
|
||||
# Expose main components
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
"""Version information for SuperClaude"""
|
||||
|
||||
__version__ = "0.4.0"
|
||||
__version__ = "4.3.0"
|
||||
|
||||
@@ -10,7 +10,7 @@ category: meta
|
||||
- **Session Start (MANDATORY)**: ALWAYS activates to restore context from Serena MCP memory
|
||||
- **Post-Implementation**: After any task completion requiring documentation
|
||||
- **Mistake Detection**: Immediate analysis when errors or bugs occur
|
||||
- **State Questions**: "どこまで進んでた", "現状", "進捗" trigger context report
|
||||
- **State Questions**: "where did we leave off", "current status", "progress" trigger context report
|
||||
- **Monthly Maintenance**: Regular documentation health reviews
|
||||
- **Manual Invocation**: `/sc:pm` command for explicit PM Agent activation
|
||||
- **Knowledge Gap**: When patterns emerge requiring documentation
|
||||
@@ -24,7 +24,7 @@ PM Agent maintains continuous context across sessions using Serena MCP memory op
|
||||
```yaml
|
||||
Activation Trigger:
|
||||
- EVERY Claude Code session start (no user command needed)
|
||||
- "どこまで進んでた", "現状", "進捗" queries
|
||||
- "where did we leave off", "current status", "progress" queries
|
||||
|
||||
Context Restoration:
|
||||
1. list_memories() → Check for existing PM Agent state
|
||||
@@ -34,10 +34,10 @@ Context Restoration:
|
||||
5. read_memory("next_actions") → What to do next
|
||||
|
||||
User Report:
|
||||
前回: [last session summary]
|
||||
進捗: [current progress status]
|
||||
今回: [planned next actions]
|
||||
課題: [blockers or issues]
|
||||
Previous: [last session summary]
|
||||
Progress: [current progress status]
|
||||
Next: [planned next actions]
|
||||
Blockers: [blockers or issues]
|
||||
|
||||
Ready for Work:
|
||||
- User can immediately continue from last checkpoint
|
||||
@@ -48,7 +48,7 @@ Ready for Work:
|
||||
### During Work (Continuous PDCA Cycle)
|
||||
|
||||
```yaml
|
||||
1. Plan Phase (仮説 - Hypothesis):
|
||||
1. Plan Phase (Hypothesis):
|
||||
Actions:
|
||||
- write_memory("plan", goal_statement)
|
||||
- Create docs/temp/hypothesis-YYYY-MM-DD.md
|
||||
@@ -60,22 +60,22 @@ Ready for Work:
|
||||
hypothesis: "Use Supabase Auth + Kong Gateway pattern"
|
||||
success_criteria: "Login works, tokens validated via Kong"
|
||||
|
||||
2. Do Phase (実験 - Experiment):
|
||||
2. Do Phase (Experiment):
|
||||
Actions:
|
||||
- TodoWrite for task tracking (3+ steps required)
|
||||
- write_memory("checkpoint", progress) every 30min
|
||||
- Create docs/temp/experiment-YYYY-MM-DD.md
|
||||
- Record 試行錯誤 (trial and error), errors, solutions
|
||||
- Record trial and error, errors, solutions
|
||||
|
||||
Example Memory:
|
||||
checkpoint: "Implemented login form, testing Kong routing"
|
||||
errors_encountered: ["CORS issue", "JWT validation failed"]
|
||||
solutions_applied: ["Added Kong CORS plugin", "Fixed JWT secret"]
|
||||
|
||||
3. Check Phase (評価 - Evaluation):
|
||||
3. Check Phase (Evaluation):
|
||||
Actions:
|
||||
- think_about_task_adherence() → Self-evaluation
|
||||
- "何がうまくいった?何が失敗?" (What worked? What failed?)
|
||||
- "What worked? What failed?"
|
||||
- Create docs/temp/lessons-YYYY-MM-DD.md
|
||||
- Assess against success criteria
|
||||
|
||||
@@ -84,10 +84,10 @@ Ready for Work:
|
||||
what_failed: "Forgot organization_id in initial implementation"
|
||||
lessons: "ALWAYS check multi-tenancy docs before queries"
|
||||
|
||||
4. Act Phase (改善 - Improvement):
|
||||
4. Act Phase (Improvement):
|
||||
Actions:
|
||||
- Success → Move docs/temp/experiment-* → docs/patterns/[pattern-name].md (清書)
|
||||
- Failure → Create docs/mistakes/mistake-YYYY-MM-DD.md (防止策)
|
||||
- Success → Move docs/temp/experiment-* → docs/patterns/[pattern-name].md (clean copy)
|
||||
- Failure → Create docs/mistakes/mistake-YYYY-MM-DD.md (prevention measures)
|
||||
- Update CLAUDE.md if global pattern discovered
|
||||
- write_memory("summary", outcomes)
|
||||
|
||||
@@ -139,19 +139,19 @@ State Preservation:
|
||||
PM Agent continuously evaluates its own performance using the PDCA cycle:
|
||||
|
||||
```yaml
|
||||
Plan (仮説生成):
|
||||
Plan (Hypothesis Generation):
|
||||
- "What am I trying to accomplish?"
|
||||
- "What approach should I take?"
|
||||
- "What are the success criteria?"
|
||||
- "What could go wrong?"
|
||||
|
||||
Do (実験実行):
|
||||
Do (Experiment Execution):
|
||||
- Execute planned approach
|
||||
- Monitor for deviations from plan
|
||||
- Record unexpected issues
|
||||
- Adapt strategy as needed
|
||||
|
||||
Check (自己評価):
|
||||
Check (Self-Evaluation):
|
||||
Think About Questions:
|
||||
- "Did I follow the architecture patterns?" (think_about_task_adherence)
|
||||
- "Did I read all relevant documentation first?"
|
||||
@@ -160,7 +160,7 @@ Check (自己評価):
|
||||
- "What mistakes did I make?"
|
||||
- "What did I learn?"
|
||||
|
||||
Act (改善実行):
|
||||
Act (Improvement Execution):
|
||||
Success Path:
|
||||
- Extract successful pattern
|
||||
- Document in docs/patterns/
|
||||
@@ -187,7 +187,7 @@ Temporary Documentation (docs/temp/):
|
||||
- lessons-YYYY-MM-DD.md: Reflections, what worked, what failed
|
||||
|
||||
Characteristics:
|
||||
- 試行錯誤 OK (trial and error welcome)
|
||||
- Trial and error welcome
|
||||
- Raw notes and observations
|
||||
- Not polished or formal
|
||||
- Temporary (moved or deleted after 7 days)
|
||||
@@ -198,7 +198,7 @@ Formal Documentation (docs/patterns/):
|
||||
Process:
|
||||
- Read docs/temp/experiment-*.md
|
||||
- Extract successful approach
|
||||
- Clean up and formalize (清書)
|
||||
- Clean up and formalize (clean copy)
|
||||
- Add concrete examples
|
||||
- Include "Last Verified" date
|
||||
|
||||
@@ -211,12 +211,12 @@ Mistake Documentation (docs/mistakes/):
|
||||
Purpose: Error records with prevention strategies
|
||||
Trigger: Mistake detected, root cause identified
|
||||
Process:
|
||||
- What Happened (現象)
|
||||
- Root Cause (根本原因)
|
||||
- Why Missed (なぜ見逃したか)
|
||||
- Fix Applied (修正内容)
|
||||
- Prevention Checklist (防止策)
|
||||
- Lesson Learned (教訓)
|
||||
- What Happened
|
||||
- Root Cause
|
||||
- Why Missed
|
||||
- Fix Applied
|
||||
- Prevention Checklist
|
||||
- Lesson Learned
|
||||
|
||||
Example:
|
||||
docs/temp/experiment-2025-10-13.md
|
||||
|
||||
@@ -160,3 +160,112 @@ def list_installed_commands() -> List[str]:
|
||||
installed.append(file.stem)
|
||||
|
||||
return sorted(installed)
|
||||
|
||||
|
||||
def _get_agents_source() -> Path:
|
||||
"""
|
||||
Get source directory for agent files
|
||||
|
||||
Agents are stored in:
|
||||
1. package_root/agents/ (installed package)
|
||||
2. plugins/superclaude/agents/ (source checkout)
|
||||
|
||||
Returns:
|
||||
Path to agents source directory
|
||||
"""
|
||||
package_root = Path(__file__).resolve().parent.parent
|
||||
|
||||
# Priority 1: agents/ in package
|
||||
package_agents_dir = package_root / "agents"
|
||||
if package_agents_dir.exists():
|
||||
return package_agents_dir
|
||||
|
||||
# Priority 2: plugins/superclaude/agents/ in project root
|
||||
repo_root = package_root.parent.parent
|
||||
plugins_agents_dir = repo_root / "plugins" / "superclaude" / "agents"
|
||||
if plugins_agents_dir.exists():
|
||||
return plugins_agents_dir
|
||||
|
||||
return package_agents_dir
|
||||
|
||||
|
||||
def install_agents(target_path: Path = None, force: bool = False) -> Tuple[bool, str]:
|
||||
"""
|
||||
Install SuperClaude agent files to ~/.claude/agents/
|
||||
|
||||
Args:
|
||||
target_path: Target installation directory (default: ~/.claude/agents)
|
||||
force: Force reinstall if agents exist
|
||||
|
||||
Returns:
|
||||
Tuple of (success: bool, message: str)
|
||||
"""
|
||||
if target_path is None:
|
||||
target_path = Path.home() / ".claude" / "agents"
|
||||
|
||||
agent_source = _get_agents_source()
|
||||
|
||||
if not agent_source or not agent_source.exists():
|
||||
return False, f"Agent source directory not found: {agent_source}"
|
||||
|
||||
target_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
agent_files = [f for f in agent_source.glob("*.md") if f.stem != "README"]
|
||||
|
||||
if not agent_files:
|
||||
return False, f"No agent files found in {agent_source}"
|
||||
|
||||
installed = []
|
||||
skipped = []
|
||||
failed = []
|
||||
|
||||
for agent_file in agent_files:
|
||||
target_file = target_path / agent_file.name
|
||||
agent_name = agent_file.stem
|
||||
|
||||
if target_file.exists() and not force:
|
||||
skipped.append(agent_name)
|
||||
continue
|
||||
|
||||
try:
|
||||
shutil.copy2(agent_file, target_file)
|
||||
installed.append(agent_name)
|
||||
except Exception as e:
|
||||
failed.append(f"{agent_name}: {e}")
|
||||
|
||||
messages = []
|
||||
|
||||
if installed:
|
||||
messages.append(f"✅ Installed {len(installed)} agents:")
|
||||
for name in installed:
|
||||
messages.append(f" - @{name}")
|
||||
|
||||
if skipped:
|
||||
messages.append(
|
||||
f"\n⚠️ Skipped {len(skipped)} existing agents (use --force to reinstall):"
|
||||
)
|
||||
for name in skipped:
|
||||
messages.append(f" - @{name}")
|
||||
|
||||
if failed:
|
||||
messages.append(f"\n❌ Failed to install {len(failed)} agents:")
|
||||
for fail in failed:
|
||||
messages.append(f" - {fail}")
|
||||
|
||||
if not installed and not skipped:
|
||||
return False, "No agents were installed"
|
||||
|
||||
messages.append(f"\n📁 Installation directory: {target_path}")
|
||||
|
||||
return len(failed) == 0, "\n".join(messages)
|
||||
|
||||
|
||||
def list_available_agents() -> List[str]:
|
||||
"""List all available agent files"""
|
||||
agent_source = _get_agents_source()
|
||||
if not agent_source.exists():
|
||||
return []
|
||||
|
||||
return sorted(
|
||||
f.stem for f in agent_source.glob("*.md") if f.stem != "README"
|
||||
)
|
||||
|
||||
@@ -5,21 +5,28 @@ Installs and manages MCP servers using the latest Claude Code API.
|
||||
Based on the installer logic from commit d4a17fc but adapted for modern Claude Code.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import platform
|
||||
import shlex
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
import click
|
||||
|
||||
# AIRIS MCP Gateway - Unified MCP solution (recommended)
|
||||
# NOTE: SHA-256 hashes should be updated when upgrading to a new pinned commit.
|
||||
# To update: download the file and run `sha256sum <file>` to get the new hash.
|
||||
AIRIS_GATEWAY = {
|
||||
"name": "airis-mcp-gateway",
|
||||
"description": "Unified MCP gateway with 60+ tools, HOT/COLD management, 98% token reduction",
|
||||
"transport": "sse",
|
||||
"endpoint": "http://localhost:9400/sse",
|
||||
"docker_compose_url": "https://raw.githubusercontent.com/agiletec-inc/airis-mcp-gateway/main/docker-compose.dist.yml",
|
||||
"docker_compose_sha256": None, # Set to pin integrity; None skips check
|
||||
"mcp_config_url": "https://raw.githubusercontent.com/agiletec-inc/airis-mcp-gateway/main/config/mcp-config.template.json",
|
||||
"mcp_config_sha256": None, # Set to pin integrity; None skips check
|
||||
"repository": "https://github.com/agiletec-inc/airis-mcp-gateway",
|
||||
}
|
||||
|
||||
@@ -93,7 +100,11 @@ MCP_SERVERS = {
|
||||
|
||||
def _run_command(cmd: List[str], **kwargs) -> subprocess.CompletedProcess:
|
||||
"""
|
||||
Run a command with proper cross-platform shell handling.
|
||||
Run a command safely without shell=True.
|
||||
|
||||
Uses list-based subprocess.run to avoid shell injection risks.
|
||||
Does not pass the full os.environ to child processes — only
|
||||
inherits the default environment.
|
||||
|
||||
Args:
|
||||
cmd: Command as list of strings
|
||||
@@ -109,18 +120,42 @@ def _run_command(cmd: List[str], **kwargs) -> subprocess.CompletedProcess:
|
||||
kwargs["errors"] = "replace" # Replace undecodable bytes instead of raising
|
||||
|
||||
if platform.system() == "Windows":
|
||||
# On Windows, wrap command in 'cmd /c' to properly handle commands like npx
|
||||
cmd = ["cmd", "/c"] + cmd
|
||||
return subprocess.run(cmd, **kwargs)
|
||||
else:
|
||||
# macOS/Linux: Use string format with proper shell to support aliases
|
||||
cmd_str = " ".join(shlex.quote(str(arg)) for arg in cmd)
|
||||
|
||||
# Use the user's shell to execute the command, supporting aliases
|
||||
user_shell = os.environ.get("SHELL", "/bin/bash")
|
||||
return subprocess.run(
|
||||
cmd_str, shell=True, env=os.environ, executable=user_shell, **kwargs
|
||||
return subprocess.run(cmd, **kwargs)
|
||||
|
||||
|
||||
def _verify_file_integrity(filepath: Path, expected_sha256: Optional[str]) -> bool:
|
||||
"""
|
||||
Verify a downloaded file's SHA-256 hash.
|
||||
|
||||
Args:
|
||||
filepath: Path to the file to verify
|
||||
expected_sha256: Expected SHA-256 hex digest, or None to skip verification
|
||||
|
||||
Returns:
|
||||
True if hash matches or verification is skipped, False on mismatch
|
||||
"""
|
||||
if expected_sha256 is None:
|
||||
return True
|
||||
|
||||
sha256 = hashlib.sha256()
|
||||
with open(filepath, "rb") as f:
|
||||
for chunk in iter(lambda: f.read(8192), b""):
|
||||
sha256.update(chunk)
|
||||
|
||||
actual = sha256.hexdigest()
|
||||
if actual != expected_sha256:
|
||||
click.echo(
|
||||
f" ❌ Integrity check failed!\n"
|
||||
f" Expected: {expected_sha256}\n"
|
||||
f" Got: {actual}",
|
||||
err=True,
|
||||
)
|
||||
return False
|
||||
|
||||
click.echo(" ✅ Integrity check passed (SHA-256)")
|
||||
return True
|
||||
|
||||
|
||||
def check_docker_available() -> bool:
|
||||
@@ -143,8 +178,6 @@ def install_airis_gateway(dry_run: bool = False) -> bool:
|
||||
Returns:
|
||||
True if successful, False otherwise
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
click.echo("\n🚀 Installing AIRIS MCP Gateway (Recommended)")
|
||||
click.echo(
|
||||
" This provides 60+ tools through a single endpoint with 98% token reduction.\n"
|
||||
@@ -167,6 +200,7 @@ def install_airis_gateway(dry_run: bool = False) -> bool:
|
||||
if dry_run:
|
||||
click.echo(f" [DRY RUN] Would create directory: {install_dir}")
|
||||
click.echo(" [DRY RUN] Would download docker-compose.yml")
|
||||
click.echo(" [DRY RUN] Would create .env file with default configuration")
|
||||
click.echo(" [DRY RUN] Would run: docker compose up -d")
|
||||
click.echo(" [DRY RUN] Would register with Claude Code")
|
||||
return True
|
||||
@@ -200,6 +234,108 @@ def install_airis_gateway(dry_run: bool = False) -> bool:
|
||||
click.echo(f" ❌ Error downloading: {e}", err=True)
|
||||
return False
|
||||
|
||||
# Verify integrity of downloaded docker-compose file
|
||||
if not _verify_file_integrity(
|
||||
compose_file, AIRIS_GATEWAY.get("docker_compose_sha256")
|
||||
):
|
||||
compose_file.unlink(missing_ok=True)
|
||||
return False
|
||||
|
||||
# Download mcp-config.json (backend server definitions for the gateway)
|
||||
mcp_config_file = install_dir / "mcp-config.json"
|
||||
if not mcp_config_file.exists():
|
||||
click.echo(" 📥 Downloading MCP server configuration...")
|
||||
try:
|
||||
result = _run_command(
|
||||
[
|
||||
"curl",
|
||||
"-fsSL",
|
||||
"-o",
|
||||
str(mcp_config_file),
|
||||
AIRIS_GATEWAY["mcp_config_url"],
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=60,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
click.echo(
|
||||
f" ⚠️ Failed to download mcp-config.json: {result.stderr}",
|
||||
err=True,
|
||||
)
|
||||
# Create a minimal default config so the gateway can start
|
||||
import json
|
||||
|
||||
default_config = {
|
||||
"mcpServers": {
|
||||
"memory": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-memory"],
|
||||
"env": {},
|
||||
"enabled": True,
|
||||
"mode": "hot",
|
||||
"description": "Session memory",
|
||||
}
|
||||
},
|
||||
"log": {"level": "info"},
|
||||
}
|
||||
mcp_config_file.write_text(json.dumps(default_config, indent=2))
|
||||
click.echo(" ✅ Created minimal default mcp-config.json")
|
||||
else:
|
||||
# Disable servers that require containers not in docker-compose.dist.yml
|
||||
import json
|
||||
|
||||
try:
|
||||
config = json.loads(mcp_config_file.read_text())
|
||||
servers_to_disable = ["airis-agent", "mindbase"]
|
||||
changed = False
|
||||
for server_name in servers_to_disable:
|
||||
if server_name in config.get("mcpServers", {}):
|
||||
config["mcpServers"][server_name]["enabled"] = False
|
||||
changed = True
|
||||
if changed:
|
||||
mcp_config_file.write_text(json.dumps(config, indent=2))
|
||||
click.echo(" ✅ MCP server configuration downloaded")
|
||||
except (json.JSONDecodeError, KeyError):
|
||||
click.echo(
|
||||
" ⚠️ Could not parse mcp-config.json, using as-is",
|
||||
err=True,
|
||||
)
|
||||
except Exception as e:
|
||||
click.echo(f" ❌ Error downloading mcp-config.json: {e}", err=True)
|
||||
# Create empty but valid config so Docker mount doesn't fail
|
||||
mcp_config_file.write_text('{"mcpServers": {}}')
|
||||
else:
|
||||
click.echo(" ✅ MCP server configuration already exists")
|
||||
|
||||
# Create .env file if it doesn't exist
|
||||
env_file = install_dir / ".env"
|
||||
if not env_file.exists():
|
||||
click.echo(" 📝 Creating .env file with default configuration...")
|
||||
workspace_dir = Path.home() / "github"
|
||||
env_content = f"""# AIRIS MCP Gateway Configuration
|
||||
# Edit this file to customize your setup
|
||||
|
||||
# Workspace directory (host path mounted into containers)
|
||||
HOST_WORKSPACE_DIR={workspace_dir}
|
||||
|
||||
# AIRIS mode (embedded = single-container gateway only)
|
||||
AIRIS_MODE=embedded
|
||||
|
||||
# Mindbase URL (if using mindbase MCP server)
|
||||
MINDBASE_URL=http://host.docker.internal:18003
|
||||
|
||||
# Tavily API key for web search (get from https://app.tavily.com)
|
||||
TAVILY_API_KEY=
|
||||
"""
|
||||
env_file.write_text(env_content)
|
||||
click.echo(f" ✅ Created .env file at {env_file}")
|
||||
click.echo(
|
||||
f" 💡 Edit {env_file} to customize settings (e.g., add TAVILY_API_KEY)"
|
||||
)
|
||||
else:
|
||||
click.echo(" ✅ .env file already exists")
|
||||
|
||||
# Start the gateway from the installation directory
|
||||
click.echo(" 🐳 Starting AIRIS MCP Gateway containers...")
|
||||
try:
|
||||
@@ -227,7 +363,38 @@ def install_airis_gateway(dry_run: bool = False) -> bool:
|
||||
|
||||
click.echo(" ✅ Gateway containers started")
|
||||
|
||||
# Wait for gateway to become healthy
|
||||
click.echo(" 🔍 Checking gateway health...")
|
||||
import time
|
||||
|
||||
gateway_healthy = False
|
||||
for attempt in range(1, 7):
|
||||
try:
|
||||
result = _run_command(
|
||||
["curl", "-sf", "http://localhost:9400/health"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
if result.returncode == 0:
|
||||
click.echo(" ✅ Gateway is healthy")
|
||||
gateway_healthy = True
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if attempt < 6:
|
||||
click.echo(f" ⏳ Waiting for gateway to start (attempt {attempt}/6)...")
|
||||
time.sleep(5)
|
||||
|
||||
if not gateway_healthy:
|
||||
click.echo(
|
||||
" ⚠️ Gateway may still be starting. Check with: curl http://localhost:9400/health",
|
||||
err=True,
|
||||
)
|
||||
|
||||
# Register with Claude Code
|
||||
# SSE transport takes the URL directly (not via npx mcp-remote)
|
||||
click.echo(" 📝 Registering with Claude Code...")
|
||||
try:
|
||||
cmd = [
|
||||
@@ -239,12 +406,7 @@ def install_airis_gateway(dry_run: bool = False) -> bool:
|
||||
"--transport",
|
||||
"sse",
|
||||
AIRIS_GATEWAY["name"],
|
||||
"--",
|
||||
"npx",
|
||||
"-y",
|
||||
"mcp-remote",
|
||||
AIRIS_GATEWAY["endpoint"],
|
||||
"--allow-http",
|
||||
]
|
||||
result = _run_command(cmd, capture_output=True, text=True, timeout=60)
|
||||
if result.returncode != 0:
|
||||
@@ -397,10 +559,11 @@ def install_mcp_server(
|
||||
)
|
||||
|
||||
if api_key:
|
||||
env_args = ["--env", f"{api_key_env}={api_key}"]
|
||||
# Each env var needs its own -e flag: -e KEY1=value1 -e KEY2=value2
|
||||
env_args = ["-e", f"{api_key_env}={api_key}"]
|
||||
|
||||
# Build installation command using modern Claude Code API
|
||||
# Format: claude mcp add --transport <transport> [--scope <scope>] [--env KEY=VALUE] <name> -- <command>
|
||||
# Format: claude mcp add --transport <transport> [--scope <scope>] [-e KEY=VALUE] <name> -- <command>
|
||||
|
||||
cmd = ["claude", "mcp", "add", "--transport", transport]
|
||||
|
||||
|
||||
@@ -9,9 +9,6 @@ from pathlib import Path
|
||||
|
||||
import click
|
||||
|
||||
# Add parent directory to path to import superclaude
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
|
||||
|
||||
from superclaude import __version__
|
||||
|
||||
|
||||
@@ -57,7 +54,9 @@ def install(target: str, force: bool, list_only: bool):
|
||||
superclaude install --target /custom/path
|
||||
"""
|
||||
from .install_commands import (
|
||||
install_agents,
|
||||
install_commands,
|
||||
list_available_agents,
|
||||
list_available_commands,
|
||||
list_installed_commands,
|
||||
)
|
||||
@@ -72,7 +71,12 @@ def install(target: str, force: bool, list_only: bool):
|
||||
status = "✅ installed" if cmd in installed else "⬜ not installed"
|
||||
click.echo(f" /{cmd:20} {status}")
|
||||
|
||||
click.echo(f"\nTotal: {len(available)} available, {len(installed)} installed")
|
||||
agents = list_available_agents()
|
||||
click.echo(f"\n📋 Available Agents: {len(agents)}")
|
||||
for agent in agents:
|
||||
click.echo(f" @{agent}")
|
||||
|
||||
click.echo(f"\nTotal: {len(available)} commands, {len(agents)} agents")
|
||||
return
|
||||
|
||||
# Install commands
|
||||
@@ -82,10 +86,17 @@ def install(target: str, force: bool, list_only: bool):
|
||||
click.echo()
|
||||
|
||||
success, message = install_commands(target_path=target_path, force=force)
|
||||
|
||||
click.echo(message)
|
||||
|
||||
if not success:
|
||||
# Also install agents to ~/.claude/agents/
|
||||
click.echo()
|
||||
click.echo("📦 Installing SuperClaude agents...")
|
||||
click.echo()
|
||||
|
||||
agent_success, agent_message = install_agents(force=force)
|
||||
click.echo(agent_message)
|
||||
|
||||
if not success or not agent_success:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
@@ -151,7 +162,7 @@ def update(target: str):
|
||||
superclaude update
|
||||
superclaude update --target /custom/path
|
||||
"""
|
||||
from .install_commands import install_commands
|
||||
from .install_commands import install_agents, install_commands
|
||||
|
||||
target_path = Path(target).expanduser()
|
||||
|
||||
@@ -159,10 +170,13 @@ def update(target: str):
|
||||
click.echo()
|
||||
|
||||
success, message = install_commands(target_path=target_path, force=True)
|
||||
|
||||
click.echo(message)
|
||||
|
||||
if not success:
|
||||
click.echo()
|
||||
agent_success, agent_message = install_agents(force=True)
|
||||
click.echo(agent_message)
|
||||
|
||||
if not success or not agent_success:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
|
||||
@@ -14,8 +14,8 @@ personas: [pm-agent]
|
||||
## Auto-Activation Triggers
|
||||
- **Session Start (MANDATORY)**: ALWAYS activates to restore context via Serena MCP memory
|
||||
- **All User Requests**: Default entry point for all interactions unless explicit sub-agent override
|
||||
- **State Questions**: "どこまで進んでた", "現状", "進捗" trigger context report
|
||||
- **Vague Requests**: "作りたい", "実装したい", "どうすれば" trigger discovery mode
|
||||
- **State Questions**: "where did we leave off", "current status", "progress" trigger context report
|
||||
- **Vague Requests**: "I want to build", "I want to implement", "how do I" trigger discovery mode
|
||||
- **Multi-Domain Tasks**: Cross-functional coordination requiring multiple specialists
|
||||
- **Complex Projects**: Systematic planning and PDCA cycle execution
|
||||
|
||||
@@ -43,10 +43,10 @@ personas: [pm-agent]
|
||||
- read_memory("next_actions") → What to do next
|
||||
|
||||
2. Report to User:
|
||||
"前回: [last session summary]
|
||||
進捗: [current progress status]
|
||||
今回: [planned next actions]
|
||||
課題: [blockers or issues]"
|
||||
"Previous: [last session summary]
|
||||
Progress: [current progress status]
|
||||
Next: [planned next actions]
|
||||
Blockers: [blockers or issues]"
|
||||
|
||||
3. Ready for Work:
|
||||
User can immediately continue from last checkpoint
|
||||
@@ -55,26 +55,26 @@ personas: [pm-agent]
|
||||
|
||||
### During Work (Continuous PDCA Cycle)
|
||||
```yaml
|
||||
1. Plan (仮説):
|
||||
1. Plan (Hypothesis):
|
||||
- write_memory("plan", goal_statement)
|
||||
- Create docs/temp/hypothesis-YYYY-MM-DD.md
|
||||
- Define what to implement and why
|
||||
|
||||
2. Do (実験):
|
||||
2. Do (Experiment):
|
||||
- TodoWrite for task tracking
|
||||
- write_memory("checkpoint", progress) every 30min
|
||||
- Update docs/temp/experiment-YYYY-MM-DD.md
|
||||
- Record試行錯誤, errors, solutions
|
||||
- Record trial-and-error, errors, solutions
|
||||
|
||||
3. Check (評価):
|
||||
3. Check (Evaluation):
|
||||
- think_about_task_adherence() → Self-evaluation
|
||||
- "何がうまくいった?何が失敗?"
|
||||
- "What went well? What failed?"
|
||||
- Update docs/temp/lessons-YYYY-MM-DD.md
|
||||
- Assess against goals
|
||||
|
||||
4. Act (改善):
|
||||
- Success → docs/patterns/[pattern-name].md (清書)
|
||||
- Failure → docs/mistakes/mistake-YYYY-MM-DD.md (防止策)
|
||||
4. Act (Improvement):
|
||||
- Success → docs/patterns/[pattern-name].md (formalized)
|
||||
- Failure → docs/mistakes/mistake-YYYY-MM-DD.md (prevention measures)
|
||||
- Update CLAUDE.md if global pattern
|
||||
- write_memory("summary", outcomes)
|
||||
```
|
||||
@@ -146,7 +146,7 @@ Testing Phase:
|
||||
|
||||
### Vague Feature Request Pattern
|
||||
```
|
||||
User: "アプリに認証機能作りたい"
|
||||
User: "I want to add authentication to the app"
|
||||
|
||||
PM Agent Workflow:
|
||||
1. Activate Brainstorming Mode
|
||||
@@ -297,19 +297,19 @@ Output: Frontend-optimized implementation
|
||||
Error Detection Protocol:
|
||||
1. Error Occurs:
|
||||
→ STOP: Never re-execute the same command immediately
|
||||
→ Question: "なぜこのエラーが出たのか?"
|
||||
→ Question: "Why did this error occur?"
|
||||
|
||||
2. Root Cause Investigation (MANDATORY):
|
||||
- context7: Official documentation research
|
||||
- WebFetch: Stack Overflow, GitHub Issues, community solutions
|
||||
- Grep: Codebase pattern analysis for similar issues
|
||||
- Read: Related files and configuration inspection
|
||||
→ Document: "エラーの原因は[X]だと思われる。なぜなら[証拠Y]"
|
||||
→ Document: "The cause of the error is likely [X], because [evidence Y]"
|
||||
|
||||
3. Hypothesis Formation:
|
||||
- Create docs/pdca/[feature]/hypothesis-error-fix.md
|
||||
- State: "原因は[X]。根拠: [Y]。解決策: [Z]"
|
||||
- Rationale: "[なぜこの方法なら解決するか]"
|
||||
- State: "Cause: [X]. Evidence: [Y]. Solution: [Z]"
|
||||
- Rationale: "[Why this approach will solve the problem]"
|
||||
|
||||
4. Solution Design (MUST BE DIFFERENT):
|
||||
- Previous Approach A failed → Design Approach B
|
||||
@@ -325,22 +325,22 @@ Error Detection Protocol:
|
||||
- Failure → Return to Step 2 with new hypothesis
|
||||
- Document: docs/pdca/[feature]/do.md (trial-and-error log)
|
||||
|
||||
Anti-Patterns (絶対禁止):
|
||||
❌ "エラーが出た。もう一回やってみよう"
|
||||
❌ "再試行: 1回目... 2回目... 3回目..."
|
||||
❌ "タイムアウトだから待ち時間を増やそう" (root cause無視)
|
||||
❌ "Warningあるけど動くからOK" (将来的な技術的負債)
|
||||
Anti-Patterns (strictly prohibited):
|
||||
❌ "Got an error. Let's just try again"
|
||||
❌ "Retry: attempt 1... attempt 2... attempt 3..."
|
||||
❌ "It timed out, so let's increase the wait time" (ignoring root cause)
|
||||
❌ "There are warnings but it works, so it's fine" (future technical debt)
|
||||
|
||||
Correct Patterns (必須):
|
||||
✅ "エラーが出た。公式ドキュメントで調査"
|
||||
✅ "原因: 環境変数未設定。なぜ必要?仕様を理解"
|
||||
✅ "解決策: .env追加 + 起動時バリデーション実装"
|
||||
✅ "学習: 次回から環境変数チェックを最初に実行"
|
||||
Correct Patterns (required):
|
||||
✅ "Got an error. Investigating via official documentation"
|
||||
✅ "Cause: environment variable not set. Why is it needed? Understanding the spec"
|
||||
✅ "Solution: add to .env + implement startup validation"
|
||||
✅ "Learning: run environment variable checks first from now on"
|
||||
```
|
||||
|
||||
### Warning/Error Investigation Culture
|
||||
|
||||
**Rule: 全ての警告・エラーに興味を持って調査する**
|
||||
**Rule: Investigate every warning and error with curiosity**
|
||||
|
||||
```yaml
|
||||
Zero Tolerance for Dismissal:
|
||||
@@ -372,7 +372,7 @@ Zero Tolerance for Dismissal:
|
||||
5. Learning: Deprecation = future breaking change
|
||||
6. Document: docs/pdca/[feature]/do.md
|
||||
|
||||
Example - Wrong Behavior (禁止):
|
||||
Example - Wrong Behavior (prohibited):
|
||||
Warning: "Deprecated API usage"
|
||||
PM Agent: "Probably fine, ignoring" ❌ NEVER DO THIS
|
||||
|
||||
@@ -396,17 +396,17 @@ session/:
|
||||
session/checkpoint # Progress snapshots (30-min intervals)
|
||||
|
||||
plan/:
|
||||
plan/[feature]/hypothesis # Plan phase: 仮説・設計
|
||||
plan/[feature]/hypothesis # Plan phase: hypothesis and design
|
||||
plan/[feature]/architecture # Architecture decisions
|
||||
plan/[feature]/rationale # Why this approach chosen
|
||||
|
||||
execution/:
|
||||
execution/[feature]/do # Do phase: 実験・試行錯誤
|
||||
execution/[feature]/do # Do phase: experimentation and trial-and-error
|
||||
execution/[feature]/errors # Error log with timestamps
|
||||
execution/[feature]/solutions # Solution attempts log
|
||||
|
||||
evaluation/:
|
||||
evaluation/[feature]/check # Check phase: 評価・分析
|
||||
evaluation/[feature]/check # Check phase: evaluation and analysis
|
||||
evaluation/[feature]/metrics # Quality metrics (coverage, performance)
|
||||
evaluation/[feature]/lessons # What worked, what failed
|
||||
|
||||
@@ -434,32 +434,32 @@ Example Usage:
|
||||
**Location: `docs/pdca/[feature-name]/`**
|
||||
|
||||
```yaml
|
||||
Structure (明確・わかりやすい):
|
||||
Structure (clear and intuitive):
|
||||
docs/pdca/[feature-name]/
|
||||
├── plan.md # Plan: 仮説・設計
|
||||
├── do.md # Do: 実験・試行錯誤
|
||||
├── check.md # Check: 評価・分析
|
||||
└── act.md # Act: 改善・次アクション
|
||||
├── plan.md # Plan: hypothesis and design
|
||||
├── do.md # Do: experimentation and trial-and-error
|
||||
├── check.md # Check: evaluation and analysis
|
||||
└── act.md # Act: improvement and next actions
|
||||
|
||||
Template - plan.md:
|
||||
# Plan: [Feature Name]
|
||||
|
||||
## Hypothesis
|
||||
[何を実装するか、なぜそのアプローチか]
|
||||
[What to implement and why this approach]
|
||||
|
||||
## Expected Outcomes (定量的)
|
||||
## Expected Outcomes (quantitative)
|
||||
- Test Coverage: 45% → 85%
|
||||
- Implementation Time: ~4 hours
|
||||
- Security: OWASP compliance
|
||||
|
||||
## Risks & Mitigation
|
||||
- [Risk 1] → [対策]
|
||||
- [Risk 2] → [対策]
|
||||
- [Risk 1] → [mitigation]
|
||||
- [Risk 2] → [mitigation]
|
||||
|
||||
Template - do.md:
|
||||
# Do: [Feature Name]
|
||||
|
||||
## Implementation Log (時系列)
|
||||
## Implementation Log (chronological)
|
||||
- 10:00 Started auth middleware implementation
|
||||
- 10:30 Error: JWTError - SUPABASE_JWT_SECRET undefined
|
||||
→ Investigation: context7 "Supabase JWT configuration"
|
||||
@@ -525,7 +525,7 @@ Lifecycle:
|
||||
### Implementation Documentation
|
||||
```yaml
|
||||
After each successful implementation:
|
||||
- Create docs/patterns/[feature-name].md (清書)
|
||||
- Create docs/patterns/[feature-name].md (formalized)
|
||||
- Document architecture decisions in ADR format
|
||||
- Update CLAUDE.md with new best practices
|
||||
- write_memory("learning/patterns/[name]", reusable_pattern)
|
||||
|
||||
@@ -19,7 +19,13 @@ Usage:
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
from .parallel import ExecutionPlan, ParallelExecutor, Task, should_parallelize
|
||||
from .parallel import (
|
||||
ExecutionPlan,
|
||||
ParallelExecutor,
|
||||
Task,
|
||||
TaskStatus,
|
||||
should_parallelize,
|
||||
)
|
||||
from .reflection import ConfidenceScore, ReflectionEngine, reflect_before_execution
|
||||
from .self_correction import RootCause, SelfCorrectionEngine, learn_from_failure
|
||||
|
||||
@@ -127,12 +133,14 @@ def intelligent_execute(
|
||||
try:
|
||||
results = executor.execute(plan)
|
||||
|
||||
# Check for failures
|
||||
failures = [
|
||||
(task_id, None) # Placeholder - need actual error
|
||||
for task_id, result in results.items()
|
||||
if result is None
|
||||
]
|
||||
# Check for failures - collect actual error info from tasks
|
||||
failures = []
|
||||
for group in plan.groups:
|
||||
for t in group.tasks:
|
||||
if t.status == TaskStatus.FAILED:
|
||||
failures.append((t.id, t.error))
|
||||
elif t.id in results and results[t.id] is None and t.error:
|
||||
failures.append((t.id, t.error))
|
||||
|
||||
if failures and auto_correct:
|
||||
# Phase 4: Self-Correction
|
||||
@@ -142,10 +150,20 @@ def intelligent_execute(
|
||||
correction_engine = SelfCorrectionEngine(repo_path)
|
||||
|
||||
for task_id, error in failures:
|
||||
error_msg = str(error) if error else "Operation failed with no error details"
|
||||
import traceback as tb_module
|
||||
|
||||
stack_trace = ""
|
||||
if error and error.__traceback__:
|
||||
stack_trace = "".join(
|
||||
tb_module.format_exception(type(error), error, error.__traceback__)
|
||||
)
|
||||
|
||||
failure_info = {
|
||||
"type": "execution_error",
|
||||
"error": "Operation returned None",
|
||||
"type": type(error).__name__ if error else "execution_error",
|
||||
"error": error_msg,
|
||||
"task_id": task_id,
|
||||
"stack_trace": stack_trace,
|
||||
}
|
||||
|
||||
root_cause = correction_engine.analyze_root_cause(task, failure_info)
|
||||
|
||||
@@ -61,7 +61,8 @@ class FailureEntry:
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict) -> "FailureEntry":
|
||||
"""Create from dict"""
|
||||
"""Create from dict (does not mutate input)"""
|
||||
data = dict(data) # Shallow copy to avoid mutating input
|
||||
root_cause_data = data.pop("root_cause")
|
||||
root_cause = RootCause(**root_cause_data)
|
||||
return cls(**data, root_cause=root_cause)
|
||||
|
||||
@@ -19,8 +19,9 @@ Required Checks:
|
||||
5. Root cause identified with high certainty
|
||||
"""
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
|
||||
class ConfidenceChecker:
|
||||
@@ -135,54 +136,86 @@ class ConfidenceChecker:
|
||||
Check for duplicate implementations
|
||||
|
||||
Before implementing, verify:
|
||||
- No existing similar functions/modules (Glob/Grep)
|
||||
- No existing similar functions/modules
|
||||
- No helper functions that solve the same problem
|
||||
- No libraries that provide this functionality
|
||||
|
||||
Returns True if no duplicates found (investigation complete)
|
||||
"""
|
||||
# This is a placeholder - actual implementation should:
|
||||
# 1. Search codebase with Glob/Grep for similar patterns
|
||||
# 2. Check project dependencies for existing solutions
|
||||
# 3. Verify no helper modules provide this functionality
|
||||
duplicate_check = context.get("duplicate_check_complete", False)
|
||||
return duplicate_check
|
||||
# Allow explicit override via context flag (for testing or pre-checked scenarios)
|
||||
if "duplicate_check_complete" in context:
|
||||
return context["duplicate_check_complete"]
|
||||
|
||||
# Search for duplicates in the project
|
||||
project_root = self._find_project_root(context)
|
||||
if not project_root:
|
||||
return False # Can't verify without project root
|
||||
|
||||
target_name = context.get("target_name", context.get("test_name", ""))
|
||||
if not target_name:
|
||||
return False
|
||||
|
||||
# Search for similarly named files/functions in the codebase
|
||||
duplicates = self._search_codebase(project_root, target_name)
|
||||
return len(duplicates) == 0
|
||||
|
||||
def _architecture_compliant(self, context: Dict[str, Any]) -> bool:
|
||||
"""
|
||||
Check architecture compliance
|
||||
|
||||
Verify solution uses existing tech stack:
|
||||
- Supabase project → Use Supabase APIs (not custom API)
|
||||
- Next.js project → Use Next.js patterns (not custom routing)
|
||||
- Turborepo → Use workspace patterns (not manual scripts)
|
||||
Verify solution uses existing tech stack by reading CLAUDE.md
|
||||
and checking that the proposed approach aligns with the project.
|
||||
|
||||
Returns True if solution aligns with project architecture
|
||||
"""
|
||||
# This is a placeholder - actual implementation should:
|
||||
# 1. Read CLAUDE.md for project tech stack
|
||||
# 2. Verify solution uses existing infrastructure
|
||||
# 3. Check not reinventing provided functionality
|
||||
architecture_check = context.get("architecture_check_complete", False)
|
||||
return architecture_check
|
||||
# Allow explicit override via context flag
|
||||
if "architecture_check_complete" in context:
|
||||
return context["architecture_check_complete"]
|
||||
|
||||
project_root = self._find_project_root(context)
|
||||
if not project_root:
|
||||
return False
|
||||
|
||||
# Check for architecture documentation
|
||||
arch_files = ["CLAUDE.md", "PLANNING.md", "ARCHITECTURE.md"]
|
||||
for arch_file in arch_files:
|
||||
if (project_root / arch_file).exists():
|
||||
return True
|
||||
|
||||
# If no architecture docs found, check for standard config files
|
||||
config_files = [
|
||||
"pyproject.toml", "package.json", "Cargo.toml",
|
||||
"go.mod", "pom.xml", "build.gradle",
|
||||
]
|
||||
return any((project_root / cf).exists() for cf in config_files)
|
||||
|
||||
def _has_oss_reference(self, context: Dict[str, Any]) -> bool:
|
||||
"""
|
||||
Check if working OSS implementations referenced
|
||||
|
||||
Search for:
|
||||
- Similar open-source solutions
|
||||
- Reference implementations in popular projects
|
||||
- Community best practices
|
||||
Validates that external references or documentation have been
|
||||
consulted before implementation.
|
||||
|
||||
Returns True if OSS reference found and analyzed
|
||||
"""
|
||||
# This is a placeholder - actual implementation should:
|
||||
# 1. Search GitHub for similar implementations
|
||||
# 2. Read popular OSS projects solving same problem
|
||||
# 3. Verify approach matches community patterns
|
||||
oss_check = context.get("oss_reference_complete", False)
|
||||
return oss_check
|
||||
# Allow explicit override via context flag
|
||||
if "oss_reference_complete" in context:
|
||||
return context["oss_reference_complete"]
|
||||
|
||||
# Check if context contains reference URLs or documentation links
|
||||
references = context.get("references", [])
|
||||
if references:
|
||||
return True
|
||||
|
||||
# Check if docs/research directory has relevant analysis
|
||||
project_root = self._find_project_root(context)
|
||||
if project_root and (project_root / "docs" / "research").exists():
|
||||
research_dir = project_root / "docs" / "research"
|
||||
research_files = list(research_dir.glob("*.md"))
|
||||
if research_files:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def _root_cause_identified(self, context: Dict[str, Any]) -> bool:
|
||||
"""
|
||||
@@ -195,12 +228,71 @@ class ConfidenceChecker:
|
||||
|
||||
Returns True if root cause clearly identified
|
||||
"""
|
||||
# This is a placeholder - actual implementation should:
|
||||
# 1. Verify problem analysis complete
|
||||
# 2. Check solution addresses root cause
|
||||
# 3. Confirm fix aligns with best practices
|
||||
root_cause_check = context.get("root_cause_identified", False)
|
||||
return root_cause_check
|
||||
# Allow explicit override via context flag
|
||||
if "root_cause_identified" in context:
|
||||
return context["root_cause_identified"]
|
||||
|
||||
# Check for root cause analysis in context
|
||||
root_cause = context.get("root_cause", "")
|
||||
if not root_cause:
|
||||
return False
|
||||
|
||||
# Validate root cause is specific (not vague)
|
||||
vague_indicators = ["maybe", "probably", "might", "possibly", "unclear", "unknown"]
|
||||
root_cause_lower = root_cause.lower()
|
||||
if any(indicator in root_cause_lower for indicator in vague_indicators):
|
||||
return False
|
||||
|
||||
# Root cause should have reasonable specificity (>10 chars)
|
||||
return len(root_cause.strip()) > 10
|
||||
|
||||
def _find_project_root(self, context: Dict[str, Any]) -> Optional[Path]:
|
||||
"""Find the project root directory from context"""
|
||||
# Check explicit project_root in context
|
||||
if "project_root" in context:
|
||||
root = Path(context["project_root"])
|
||||
if root.exists():
|
||||
return root
|
||||
|
||||
# Traverse up from test_file to find project root
|
||||
test_file = context.get("test_file")
|
||||
if not test_file:
|
||||
return None
|
||||
|
||||
current = Path(test_file).parent
|
||||
while current.parent != current:
|
||||
if (current / "pyproject.toml").exists() or (current / ".git").exists():
|
||||
return current
|
||||
current = current.parent
|
||||
return None
|
||||
|
||||
def _search_codebase(self, project_root: Path, target_name: str) -> List[Path]:
|
||||
"""
|
||||
Search for files/functions with similar names in the codebase
|
||||
|
||||
Returns list of paths to potential duplicates
|
||||
"""
|
||||
duplicates = []
|
||||
|
||||
# Normalize target name for search
|
||||
# Convert test_feature_name to feature_name
|
||||
search_name = re.sub(r"^test_", "", target_name)
|
||||
if not search_name:
|
||||
return []
|
||||
|
||||
# Search for Python files with similar names
|
||||
src_dirs = [project_root / "src", project_root / "lib", project_root]
|
||||
for src_dir in src_dirs:
|
||||
if not src_dir.exists():
|
||||
continue
|
||||
for py_file in src_dir.rglob("*.py"):
|
||||
# Skip test files and __pycache__
|
||||
if "test_" in py_file.name or "__pycache__" in str(py_file):
|
||||
continue
|
||||
if search_name.lower() in py_file.stem.lower():
|
||||
duplicates.append(py_file)
|
||||
|
||||
return duplicates
|
||||
|
||||
def _has_existing_patterns(self, context: Dict[str, Any]) -> bool:
|
||||
"""
|
||||
|
||||
@@ -165,14 +165,53 @@ class ReflexionPattern:
|
||||
"""
|
||||
Search for similar error in mindbase (semantic search)
|
||||
|
||||
Attempts to query the mindbase MCP server for semantically similar
|
||||
error patterns. Falls back gracefully if mindbase is unavailable.
|
||||
|
||||
Args:
|
||||
error_signature: Error signature to search
|
||||
|
||||
Returns:
|
||||
Solution dict if found, None if mindbase unavailable or no match
|
||||
"""
|
||||
# TODO: Implement mindbase integration
|
||||
# For now, return None (fallback to file search)
|
||||
import subprocess
|
||||
|
||||
try:
|
||||
# Query mindbase via its HTTP API (default port from AIRIS config)
|
||||
result = subprocess.run(
|
||||
[
|
||||
"curl", "-sf", "--max-time", "3",
|
||||
"-X", "POST",
|
||||
"http://localhost:18003/api/search",
|
||||
"-H", "Content-Type: application/json",
|
||||
"-d", json.dumps({"query": error_signature, "limit": 1}),
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
|
||||
if result.returncode != 0:
|
||||
return None
|
||||
|
||||
response = json.loads(result.stdout)
|
||||
results = response.get("results", [])
|
||||
|
||||
if results and results[0].get("score", 0) > 0.7:
|
||||
match = results[0]
|
||||
return {
|
||||
"solution": match.get("solution"),
|
||||
"root_cause": match.get("root_cause"),
|
||||
"prevention": match.get("prevention"),
|
||||
"source": "mindbase",
|
||||
"similarity": match.get("score"),
|
||||
}
|
||||
|
||||
except (subprocess.TimeoutExpired, subprocess.SubprocessError, json.JSONDecodeError):
|
||||
pass # Mindbase unavailable, fall through to local search
|
||||
except FileNotFoundError:
|
||||
pass # curl not available
|
||||
|
||||
return None
|
||||
|
||||
def _search_local_files(self, error_signature: str) -> Optional[Dict[str, Any]]:
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
"""
|
||||
Integration tests for the execution engine orchestrator
|
||||
|
||||
Tests intelligent_execute, quick_execute, and safe_execute functions
|
||||
that combine reflection, parallel execution, and self-correction.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from superclaude.execution import intelligent_execute, quick_execute, safe_execute
|
||||
|
||||
|
||||
class TestQuickExecute:
|
||||
"""Test quick_execute convenience function"""
|
||||
|
||||
def test_quick_execute_simple_ops(self):
|
||||
"""Quick execute should run simple operations and return results"""
|
||||
results = quick_execute([
|
||||
lambda: "result_a",
|
||||
lambda: "result_b",
|
||||
lambda: 42,
|
||||
])
|
||||
|
||||
assert results == ["result_a", "result_b", 42]
|
||||
|
||||
def test_quick_execute_empty(self):
|
||||
"""Quick execute with no operations should return empty list"""
|
||||
results = quick_execute([])
|
||||
assert results == []
|
||||
|
||||
def test_quick_execute_single(self):
|
||||
"""Quick execute with single operation"""
|
||||
results = quick_execute([lambda: "only"])
|
||||
assert results == ["only"]
|
||||
|
||||
|
||||
class TestIntelligentExecute:
|
||||
"""Test the intelligent_execute orchestrator"""
|
||||
|
||||
def test_execute_with_clear_task(self, tmp_path):
|
||||
"""Clear task with simple operations should succeed"""
|
||||
# Create PROJECT_INDEX.md so context check passes
|
||||
(tmp_path / "PROJECT_INDEX.md").write_text("# Index")
|
||||
(tmp_path / "docs" / "memory").mkdir(parents=True, exist_ok=True)
|
||||
|
||||
result = intelligent_execute(
|
||||
task="Create a new function called validate_email in validators.py",
|
||||
operations=[lambda: "validated"],
|
||||
context={
|
||||
"project_index": "loaded",
|
||||
"current_branch": "main",
|
||||
"git_status": "clean",
|
||||
},
|
||||
repo_path=tmp_path,
|
||||
)
|
||||
|
||||
assert result["status"] in ("success", "blocked")
|
||||
assert "confidence" in result
|
||||
|
||||
def test_execute_blocked_by_low_confidence(self, tmp_path):
|
||||
"""Vague task should be blocked by reflection engine"""
|
||||
(tmp_path / "docs" / "memory").mkdir(parents=True, exist_ok=True)
|
||||
|
||||
result = intelligent_execute(
|
||||
task="fix",
|
||||
operations=[lambda: "done"],
|
||||
repo_path=tmp_path,
|
||||
)
|
||||
|
||||
# Very short vague task may get blocked
|
||||
assert result["status"] in ("blocked", "success", "partial_failure")
|
||||
assert "confidence" in result
|
||||
|
||||
def test_execute_with_failing_operation(self, tmp_path):
|
||||
"""Failing operation should trigger self-correction"""
|
||||
(tmp_path / "PROJECT_INDEX.md").write_text("# Index")
|
||||
(tmp_path / "docs" / "memory").mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def failing():
|
||||
raise ValueError("Test failure")
|
||||
|
||||
result = intelligent_execute(
|
||||
task="Create validation endpoint in api/validate.py",
|
||||
operations=[lambda: "ok", failing],
|
||||
context={
|
||||
"project_index": "loaded",
|
||||
"current_branch": "main",
|
||||
"git_status": "clean",
|
||||
},
|
||||
repo_path=tmp_path,
|
||||
auto_correct=True,
|
||||
)
|
||||
|
||||
assert result["status"] in ("partial_failure", "blocked", "failed")
|
||||
|
||||
def test_execute_no_auto_correct(self, tmp_path):
|
||||
"""Disabling auto_correct should skip self-correction phase"""
|
||||
(tmp_path / "PROJECT_INDEX.md").write_text("# Index")
|
||||
(tmp_path / "docs" / "memory").mkdir(parents=True, exist_ok=True)
|
||||
|
||||
result = intelligent_execute(
|
||||
task="Create helper function in utils.py for date formatting",
|
||||
operations=[lambda: "done"],
|
||||
context={
|
||||
"project_index": "loaded",
|
||||
"current_branch": "main",
|
||||
"git_status": "clean",
|
||||
},
|
||||
repo_path=tmp_path,
|
||||
auto_correct=False,
|
||||
)
|
||||
|
||||
assert result["status"] in ("success", "blocked")
|
||||
|
||||
|
||||
class TestSafeExecute:
|
||||
"""Test safe_execute convenience function"""
|
||||
|
||||
def test_safe_execute_success(self, tmp_path):
|
||||
"""Safe execute should return result on success"""
|
||||
(tmp_path / "PROJECT_INDEX.md").write_text("# Index")
|
||||
(tmp_path / "docs" / "memory").mkdir(parents=True, exist_ok=True)
|
||||
|
||||
try:
|
||||
result = safe_execute(
|
||||
task="Create user validation function in validators.py",
|
||||
operation=lambda: "validated",
|
||||
context={
|
||||
"project_index": "loaded",
|
||||
"current_branch": "main",
|
||||
"git_status": "clean",
|
||||
},
|
||||
)
|
||||
# If it proceeds, should get result
|
||||
assert result is not None
|
||||
except RuntimeError:
|
||||
# If blocked by low confidence, that's also valid
|
||||
pass
|
||||
@@ -0,0 +1,284 @@
|
||||
"""
|
||||
Unit tests for ParallelExecutor
|
||||
|
||||
Tests automatic parallelization, dependency resolution,
|
||||
and concurrent execution capabilities.
|
||||
"""
|
||||
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from superclaude.execution.parallel import (
|
||||
ExecutionPlan,
|
||||
ParallelExecutor,
|
||||
ParallelGroup,
|
||||
Task,
|
||||
TaskStatus,
|
||||
parallel_file_operations,
|
||||
should_parallelize,
|
||||
)
|
||||
|
||||
|
||||
class TestTask:
|
||||
"""Test suite for Task dataclass"""
|
||||
|
||||
def test_task_creation(self):
|
||||
"""Test basic task creation"""
|
||||
task = Task(
|
||||
id="t1",
|
||||
description="Test task",
|
||||
execute=lambda: "result",
|
||||
depends_on=[],
|
||||
)
|
||||
assert task.id == "t1"
|
||||
assert task.status == TaskStatus.PENDING
|
||||
assert task.result is None
|
||||
assert task.error is None
|
||||
|
||||
def test_task_can_execute_no_deps(self):
|
||||
"""Task with no dependencies can always execute"""
|
||||
task = Task(id="t1", description="No deps", execute=lambda: None, depends_on=[])
|
||||
assert task.can_execute(set()) is True
|
||||
assert task.can_execute({"other"}) is True
|
||||
|
||||
def test_task_can_execute_with_deps_met(self):
|
||||
"""Task can execute when all dependencies are completed"""
|
||||
task = Task(
|
||||
id="t2", description="With deps", execute=lambda: None, depends_on=["t1"]
|
||||
)
|
||||
assert task.can_execute({"t1"}) is True
|
||||
assert task.can_execute({"t1", "t0"}) is True
|
||||
|
||||
def test_task_cannot_execute_deps_unmet(self):
|
||||
"""Task cannot execute when dependencies are not met"""
|
||||
task = Task(
|
||||
id="t2",
|
||||
description="With deps",
|
||||
execute=lambda: None,
|
||||
depends_on=["t1", "t3"],
|
||||
)
|
||||
assert task.can_execute(set()) is False
|
||||
assert task.can_execute({"t1"}) is False # t3 missing
|
||||
|
||||
def test_task_can_execute_all_deps_met(self):
|
||||
"""Task can execute when all multiple dependencies are met"""
|
||||
task = Task(
|
||||
id="t3",
|
||||
description="Multi deps",
|
||||
execute=lambda: None,
|
||||
depends_on=["t1", "t2"],
|
||||
)
|
||||
assert task.can_execute({"t1", "t2"}) is True
|
||||
|
||||
|
||||
class TestParallelExecutor:
|
||||
"""Test suite for ParallelExecutor class"""
|
||||
|
||||
def test_plan_independent_tasks(self):
|
||||
"""Independent tasks should be in a single parallel group"""
|
||||
executor = ParallelExecutor(max_workers=5)
|
||||
tasks = [
|
||||
Task(id=f"t{i}", description=f"Task {i}", execute=lambda: i, depends_on=[])
|
||||
for i in range(5)
|
||||
]
|
||||
|
||||
plan = executor.plan(tasks)
|
||||
|
||||
assert plan.total_tasks == 5
|
||||
assert len(plan.groups) == 1 # All independent = 1 group
|
||||
assert len(plan.groups[0].tasks) == 5
|
||||
|
||||
def test_plan_sequential_tasks(self):
|
||||
"""Tasks with chain dependencies should be in separate groups"""
|
||||
executor = ParallelExecutor()
|
||||
tasks = [
|
||||
Task(id="t0", description="First", execute=lambda: 0, depends_on=[]),
|
||||
Task(id="t1", description="Second", execute=lambda: 1, depends_on=["t0"]),
|
||||
Task(id="t2", description="Third", execute=lambda: 2, depends_on=["t1"]),
|
||||
]
|
||||
|
||||
plan = executor.plan(tasks)
|
||||
|
||||
assert plan.total_tasks == 3
|
||||
assert len(plan.groups) == 3 # Each depends on previous
|
||||
|
||||
def test_plan_mixed_dependencies(self):
|
||||
"""Wave-Checkpoint-Wave pattern should create correct groups"""
|
||||
executor = ParallelExecutor()
|
||||
tasks = [
|
||||
# Wave 1: independent reads
|
||||
Task(id="read1", description="Read 1", execute=lambda: "r1", depends_on=[]),
|
||||
Task(id="read2", description="Read 2", execute=lambda: "r2", depends_on=[]),
|
||||
Task(id="read3", description="Read 3", execute=lambda: "r3", depends_on=[]),
|
||||
# Wave 2: depends on all reads
|
||||
Task(
|
||||
id="analyze",
|
||||
description="Analyze",
|
||||
execute=lambda: "a",
|
||||
depends_on=["read1", "read2", "read3"],
|
||||
),
|
||||
# Wave 3: depends on analysis
|
||||
Task(
|
||||
id="report",
|
||||
description="Report",
|
||||
execute=lambda: "rp",
|
||||
depends_on=["analyze"],
|
||||
),
|
||||
]
|
||||
|
||||
plan = executor.plan(tasks)
|
||||
|
||||
assert len(plan.groups) == 3
|
||||
assert len(plan.groups[0].tasks) == 3 # 3 parallel reads
|
||||
assert len(plan.groups[1].tasks) == 1 # analyze
|
||||
assert len(plan.groups[2].tasks) == 1 # report
|
||||
|
||||
def test_plan_speedup_calculation(self):
|
||||
"""Speedup should be > 1 for parallelizable tasks"""
|
||||
executor = ParallelExecutor()
|
||||
tasks = [
|
||||
Task(id=f"t{i}", description=f"Task {i}", execute=lambda: i, depends_on=[])
|
||||
for i in range(10)
|
||||
]
|
||||
|
||||
plan = executor.plan(tasks)
|
||||
|
||||
assert plan.speedup >= 1.0
|
||||
assert plan.sequential_time_estimate > plan.parallel_time_estimate
|
||||
|
||||
def test_plan_circular_dependency_detection(self):
|
||||
"""Circular dependencies should raise ValueError"""
|
||||
executor = ParallelExecutor()
|
||||
tasks = [
|
||||
Task(id="a", description="A", execute=lambda: None, depends_on=["b"]),
|
||||
Task(id="b", description="B", execute=lambda: None, depends_on=["a"]),
|
||||
]
|
||||
|
||||
with pytest.raises(ValueError, match="Circular dependency"):
|
||||
executor.plan(tasks)
|
||||
|
||||
def test_execute_returns_results(self):
|
||||
"""Execute should return dict of task_id -> result"""
|
||||
executor = ParallelExecutor()
|
||||
tasks = [
|
||||
Task(id="t0", description="Return 42", execute=lambda: 42, depends_on=[]),
|
||||
Task(
|
||||
id="t1", description="Return hello", execute=lambda: "hello", depends_on=[]
|
||||
),
|
||||
]
|
||||
|
||||
plan = executor.plan(tasks)
|
||||
results = executor.execute(plan)
|
||||
|
||||
assert results["t0"] == 42
|
||||
assert results["t1"] == "hello"
|
||||
|
||||
def test_execute_handles_failures(self):
|
||||
"""Failed tasks should have None result and error set"""
|
||||
executor = ParallelExecutor()
|
||||
|
||||
def failing_task():
|
||||
raise RuntimeError("Task failed!")
|
||||
|
||||
tasks = [
|
||||
Task(id="good", description="Good", execute=lambda: "ok", depends_on=[]),
|
||||
Task(id="bad", description="Bad", execute=failing_task, depends_on=[]),
|
||||
]
|
||||
|
||||
plan = executor.plan(tasks)
|
||||
results = executor.execute(plan)
|
||||
|
||||
assert results["good"] == "ok"
|
||||
assert results["bad"] is None
|
||||
|
||||
# Check task error was recorded
|
||||
bad_task = [t for t in tasks if t.id == "bad"][0]
|
||||
assert bad_task.status == TaskStatus.FAILED
|
||||
assert bad_task.error is not None
|
||||
|
||||
def test_execute_respects_dependency_order(self):
|
||||
"""Dependent tasks should run after their dependencies"""
|
||||
execution_order = []
|
||||
|
||||
def make_task(name):
|
||||
def fn():
|
||||
execution_order.append(name)
|
||||
return name
|
||||
|
||||
return fn
|
||||
|
||||
executor = ParallelExecutor(max_workers=1) # Force sequential within groups
|
||||
tasks = [
|
||||
Task(id="first", description="First", execute=make_task("first"), depends_on=[]),
|
||||
Task(
|
||||
id="second",
|
||||
description="Second",
|
||||
execute=make_task("second"),
|
||||
depends_on=["first"],
|
||||
),
|
||||
]
|
||||
|
||||
plan = executor.plan(tasks)
|
||||
executor.execute(plan)
|
||||
|
||||
assert execution_order.index("first") < execution_order.index("second")
|
||||
|
||||
def test_execute_parallel_speedup(self):
|
||||
"""Parallel execution should be faster than sequential"""
|
||||
executor = ParallelExecutor(max_workers=5)
|
||||
|
||||
def slow_task(n):
|
||||
def fn():
|
||||
time.sleep(0.05)
|
||||
return n
|
||||
|
||||
return fn
|
||||
|
||||
tasks = [
|
||||
Task(
|
||||
id=f"t{i}",
|
||||
description=f"Task {i}",
|
||||
execute=slow_task(i),
|
||||
depends_on=[],
|
||||
)
|
||||
for i in range(5)
|
||||
]
|
||||
|
||||
plan = executor.plan(tasks)
|
||||
|
||||
start = time.time()
|
||||
results = executor.execute(plan)
|
||||
elapsed = time.time() - start
|
||||
|
||||
# 5 tasks x 0.05s = 0.25s sequential. Parallel should be ~0.05s
|
||||
assert elapsed < 0.20 # Allow generous margin
|
||||
assert len(results) == 5
|
||||
|
||||
|
||||
class TestConvenienceFunctions:
|
||||
"""Test convenience functions"""
|
||||
|
||||
def test_should_parallelize_above_threshold(self):
|
||||
"""Items above threshold should trigger parallelization"""
|
||||
assert should_parallelize([1, 2, 3]) is True
|
||||
assert should_parallelize([1, 2, 3, 4]) is True
|
||||
|
||||
def test_should_parallelize_below_threshold(self):
|
||||
"""Items below threshold should not trigger parallelization"""
|
||||
assert should_parallelize([1]) is False
|
||||
assert should_parallelize([1, 2]) is False
|
||||
|
||||
def test_should_parallelize_custom_threshold(self):
|
||||
"""Custom threshold should be respected"""
|
||||
assert should_parallelize([1, 2], threshold=2) is True
|
||||
assert should_parallelize([1], threshold=2) is False
|
||||
|
||||
def test_parallel_file_operations(self):
|
||||
"""parallel_file_operations should apply operation to all files"""
|
||||
results = parallel_file_operations(
|
||||
["a.py", "b.py", "c.py"],
|
||||
lambda f: f.upper(),
|
||||
)
|
||||
|
||||
assert results == ["A.PY", "B.PY", "C.PY"]
|
||||
@@ -0,0 +1,204 @@
|
||||
"""
|
||||
Unit tests for ReflectionEngine
|
||||
|
||||
Tests the 3-stage pre-execution confidence assessment:
|
||||
1. Requirement clarity analysis
|
||||
2. Past mistake pattern detection
|
||||
3. Context sufficiency validation
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from superclaude.execution.reflection import (
|
||||
ConfidenceScore,
|
||||
ReflectionEngine,
|
||||
ReflectionResult,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def reflection_engine(tmp_path):
|
||||
"""Create a ReflectionEngine with temporary repo path"""
|
||||
return ReflectionEngine(tmp_path)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def engine_with_mistakes(tmp_path):
|
||||
"""Create a ReflectionEngine with past mistakes in memory"""
|
||||
memory_dir = tmp_path / "docs" / "memory"
|
||||
memory_dir.mkdir(parents=True)
|
||||
|
||||
reflexion_data = {
|
||||
"mistakes": [
|
||||
{
|
||||
"task": "fix user authentication login flow",
|
||||
"mistake": "Used wrong token validation method",
|
||||
},
|
||||
{
|
||||
"task": "create database migration script",
|
||||
"mistake": "Forgot to handle nullable columns",
|
||||
},
|
||||
],
|
||||
"patterns": [],
|
||||
"prevention_rules": [],
|
||||
}
|
||||
|
||||
(memory_dir / "reflexion.json").write_text(json.dumps(reflexion_data))
|
||||
return ReflectionEngine(tmp_path)
|
||||
|
||||
|
||||
class TestReflectionResult:
|
||||
"""Test ReflectionResult dataclass"""
|
||||
|
||||
def test_repr_high_score(self):
|
||||
"""High score should show green checkmark"""
|
||||
result = ReflectionResult(
|
||||
stage="Test", score=0.9, evidence=["good"], concerns=[]
|
||||
)
|
||||
assert "✅" in repr(result)
|
||||
|
||||
def test_repr_medium_score(self):
|
||||
"""Medium score should show warning"""
|
||||
result = ReflectionResult(
|
||||
stage="Test", score=0.6, evidence=[], concerns=["concern"]
|
||||
)
|
||||
assert "⚠️" in repr(result)
|
||||
|
||||
def test_repr_low_score(self):
|
||||
"""Low score should show red X"""
|
||||
result = ReflectionResult(
|
||||
stage="Test", score=0.2, evidence=[], concerns=["bad"]
|
||||
)
|
||||
assert "❌" in repr(result)
|
||||
|
||||
|
||||
class TestReflectionEngine:
|
||||
"""Test suite for ReflectionEngine class"""
|
||||
|
||||
def test_reflect_specific_task(self, reflection_engine):
|
||||
"""Specific task description should get higher clarity score"""
|
||||
result = reflection_engine.reflect(
|
||||
"Create a new REST API endpoint for /users/{id} in users.py",
|
||||
context={"project_index": True, "current_branch": "main", "git_status": "clean"},
|
||||
)
|
||||
|
||||
assert result.requirement_clarity.score > 0.5
|
||||
assert result.should_proceed is True or result.confidence > 0.0
|
||||
|
||||
def test_reflect_vague_task(self, reflection_engine):
|
||||
"""Vague task description should get lower clarity score"""
|
||||
result = reflection_engine.reflect("improve something")
|
||||
|
||||
assert result.requirement_clarity.score < 0.7
|
||||
assert any("vague" in c.lower() for c in result.requirement_clarity.concerns)
|
||||
|
||||
def test_reflect_short_task(self, reflection_engine):
|
||||
"""Very short task should be flagged"""
|
||||
result = reflection_engine.reflect("fix it")
|
||||
|
||||
assert result.requirement_clarity.score < 0.7
|
||||
assert any("brief" in c.lower() for c in result.requirement_clarity.concerns)
|
||||
|
||||
def test_reflect_no_context(self, reflection_engine):
|
||||
"""Missing context should lower context readiness score"""
|
||||
result = reflection_engine.reflect(
|
||||
"Create user authentication function in auth.py"
|
||||
)
|
||||
|
||||
assert result.context_ready.score < 0.7
|
||||
assert any("context" in c.lower() for c in result.context_ready.concerns)
|
||||
|
||||
def test_reflect_full_context(self, reflection_engine):
|
||||
"""Full context should give high context readiness"""
|
||||
# Create PROJECT_INDEX.md to satisfy freshness check
|
||||
(reflection_engine.repo_path / "PROJECT_INDEX.md").write_text("# Index")
|
||||
|
||||
result = reflection_engine.reflect(
|
||||
"Add validation to user registration",
|
||||
context={
|
||||
"project_index": "loaded",
|
||||
"current_branch": "feature/auth",
|
||||
"git_status": "clean",
|
||||
},
|
||||
)
|
||||
|
||||
assert result.context_ready.score >= 0.7
|
||||
|
||||
def test_reflect_no_past_mistakes(self, reflection_engine):
|
||||
"""No reflexion file should give high mistake check score"""
|
||||
result = reflection_engine.reflect("Create new feature")
|
||||
|
||||
assert result.mistake_check.score == 1.0
|
||||
assert any("no past" in e.lower() for e in result.mistake_check.evidence)
|
||||
|
||||
def test_reflect_with_similar_mistakes(self, engine_with_mistakes):
|
||||
"""Similar past mistakes should lower the score"""
|
||||
result = engine_with_mistakes.reflect(
|
||||
"fix user authentication token validation"
|
||||
)
|
||||
|
||||
assert result.mistake_check.score < 1.0
|
||||
assert any("similar" in c.lower() for c in result.mistake_check.concerns)
|
||||
|
||||
def test_confidence_threshold(self, reflection_engine):
|
||||
"""Confidence below 70% should block execution"""
|
||||
result = reflection_engine.reflect("maybe improve something")
|
||||
|
||||
if result.confidence < 0.7:
|
||||
assert result.should_proceed is False
|
||||
|
||||
def test_confidence_above_threshold(self, reflection_engine):
|
||||
"""Confidence above 70% should allow execution"""
|
||||
(reflection_engine.repo_path / "PROJECT_INDEX.md").write_text("# Index")
|
||||
|
||||
result = reflection_engine.reflect(
|
||||
"Create a new REST API endpoint for /users/{id} in users.py",
|
||||
context={
|
||||
"project_index": "loaded",
|
||||
"current_branch": "main",
|
||||
"git_status": "clean",
|
||||
},
|
||||
)
|
||||
|
||||
if result.confidence >= 0.7:
|
||||
assert result.should_proceed is True
|
||||
|
||||
def test_record_reflection(self, reflection_engine):
|
||||
"""Recording reflection should persist to file"""
|
||||
confidence = ConfidenceScore(
|
||||
requirement_clarity=ReflectionResult("Clarity", 0.8, ["ok"], []),
|
||||
mistake_check=ReflectionResult("Mistakes", 1.0, ["none"], []),
|
||||
context_ready=ReflectionResult("Context", 0.7, ["loaded"], []),
|
||||
confidence=0.85,
|
||||
should_proceed=True,
|
||||
blockers=[],
|
||||
recommendations=[],
|
||||
)
|
||||
|
||||
reflection_engine.record_reflection("test task", confidence, "proceed")
|
||||
|
||||
log_file = reflection_engine.memory_path / "reflection_log.json"
|
||||
assert log_file.exists()
|
||||
|
||||
data = json.loads(log_file.read_text())
|
||||
assert len(data["reflections"]) == 1
|
||||
assert data["reflections"][0]["task"] == "test task"
|
||||
assert data["reflections"][0]["confidence"] == 0.85
|
||||
|
||||
def test_weights_sum_to_one(self, reflection_engine):
|
||||
"""Weight values should sum to 1.0"""
|
||||
total = sum(reflection_engine.WEIGHTS.values())
|
||||
assert abs(total - 1.0) < 0.001
|
||||
|
||||
def test_clarity_specific_verbs_boost(self, reflection_engine):
|
||||
"""Specific action verbs should boost clarity score"""
|
||||
result_specific = reflection_engine._reflect_clarity(
|
||||
"Create user registration endpoint", None
|
||||
)
|
||||
result_vague = reflection_engine._reflect_clarity(
|
||||
"improve the system", None
|
||||
)
|
||||
|
||||
assert result_specific.score > result_vague.score
|
||||
@@ -0,0 +1,286 @@
|
||||
"""
|
||||
Unit tests for SelfCorrectionEngine
|
||||
|
||||
Tests failure detection, root cause analysis, prevention rule
|
||||
generation, and reflexion-based learning.
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from superclaude.execution.self_correction import (
|
||||
FailureEntry,
|
||||
RootCause,
|
||||
SelfCorrectionEngine,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def correction_engine(tmp_path):
|
||||
"""Create a SelfCorrectionEngine with temporary repo path"""
|
||||
return SelfCorrectionEngine(tmp_path)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def engine_with_history(tmp_path):
|
||||
"""Create engine with existing failure history"""
|
||||
engine = SelfCorrectionEngine(tmp_path)
|
||||
|
||||
# Add a past failure
|
||||
root_cause = RootCause(
|
||||
category="validation",
|
||||
description="Missing input validation",
|
||||
evidence=["No null check"],
|
||||
prevention_rule="ALWAYS validate inputs before processing",
|
||||
validation_tests=["Check input is not None"],
|
||||
)
|
||||
|
||||
entry = FailureEntry(
|
||||
id="abc12345",
|
||||
timestamp="2026-01-01T00:00:00",
|
||||
task="create user registration form",
|
||||
failure_type="validation",
|
||||
error_message="TypeError: cannot read property of null",
|
||||
root_cause=root_cause,
|
||||
fixed=True,
|
||||
fix_description="Added null check",
|
||||
)
|
||||
|
||||
with open(engine.reflexion_file) as f:
|
||||
data = json.load(f)
|
||||
|
||||
data["mistakes"].append(entry.to_dict())
|
||||
data["prevention_rules"].append(root_cause.prevention_rule)
|
||||
|
||||
with open(engine.reflexion_file, "w") as f:
|
||||
json.dump(data, f, indent=2)
|
||||
|
||||
return engine
|
||||
|
||||
|
||||
class TestRootCause:
|
||||
"""Test RootCause dataclass"""
|
||||
|
||||
def test_root_cause_creation(self):
|
||||
"""Test basic RootCause creation"""
|
||||
rc = RootCause(
|
||||
category="logic",
|
||||
description="Off-by-one error",
|
||||
evidence=["Loop bound incorrect"],
|
||||
prevention_rule="ALWAYS verify loop boundaries",
|
||||
validation_tests=["Test boundary conditions"],
|
||||
)
|
||||
assert rc.category == "logic"
|
||||
assert "logic" in repr(rc).lower() or "Logic" in repr(rc)
|
||||
|
||||
def test_root_cause_repr(self):
|
||||
"""RootCause repr should show key info"""
|
||||
rc = RootCause(
|
||||
category="type",
|
||||
description="Wrong type passed",
|
||||
evidence=["Expected int, got str"],
|
||||
prevention_rule="Add type hints",
|
||||
validation_tests=["test1", "test2"],
|
||||
)
|
||||
text = repr(rc)
|
||||
assert "type" in text.lower()
|
||||
assert "2 validation" in text
|
||||
|
||||
|
||||
class TestFailureEntry:
|
||||
"""Test FailureEntry dataclass"""
|
||||
|
||||
def test_to_dict_roundtrip(self):
|
||||
"""FailureEntry should survive dict serialization roundtrip"""
|
||||
rc = RootCause(
|
||||
category="dependency",
|
||||
description="Missing module",
|
||||
evidence=["ImportError"],
|
||||
prevention_rule="Check deps",
|
||||
validation_tests=["Verify import"],
|
||||
)
|
||||
entry = FailureEntry(
|
||||
id="test123",
|
||||
timestamp="2026-01-01T00:00:00",
|
||||
task="install package",
|
||||
failure_type="dependency",
|
||||
error_message="ModuleNotFoundError",
|
||||
root_cause=rc,
|
||||
fixed=False,
|
||||
)
|
||||
|
||||
d = entry.to_dict()
|
||||
restored = FailureEntry.from_dict(d)
|
||||
|
||||
assert restored.id == entry.id
|
||||
assert restored.task == entry.task
|
||||
assert restored.root_cause.category == "dependency"
|
||||
|
||||
|
||||
class TestSelfCorrectionEngine:
|
||||
"""Test suite for SelfCorrectionEngine"""
|
||||
|
||||
def test_init_creates_reflexion_file(self, correction_engine):
|
||||
"""Engine should create reflexion.json on init"""
|
||||
assert correction_engine.reflexion_file.exists()
|
||||
|
||||
data = json.loads(correction_engine.reflexion_file.read_text())
|
||||
assert data["version"] == "1.0"
|
||||
assert data["mistakes"] == []
|
||||
assert data["prevention_rules"] == []
|
||||
|
||||
def test_detect_failure_failed(self, correction_engine):
|
||||
"""Should detect 'failed' status"""
|
||||
assert correction_engine.detect_failure({"status": "failed"}) is True
|
||||
|
||||
def test_detect_failure_error(self, correction_engine):
|
||||
"""Should detect 'error' status"""
|
||||
assert correction_engine.detect_failure({"status": "error"}) is True
|
||||
|
||||
def test_detect_failure_success(self, correction_engine):
|
||||
"""Should not detect success as failure"""
|
||||
assert correction_engine.detect_failure({"status": "success"}) is False
|
||||
|
||||
def test_detect_failure_unknown(self, correction_engine):
|
||||
"""Should not detect unknown status as failure"""
|
||||
assert correction_engine.detect_failure({"status": "unknown"}) is False
|
||||
|
||||
def test_categorize_validation(self, correction_engine):
|
||||
"""Validation errors should be categorized correctly"""
|
||||
result = correction_engine._categorize_failure("invalid input format", "")
|
||||
assert result == "validation"
|
||||
|
||||
def test_categorize_dependency(self, correction_engine):
|
||||
"""Dependency errors should be categorized correctly"""
|
||||
result = correction_engine._categorize_failure(
|
||||
"ModuleNotFoundError: No module named 'foo'", ""
|
||||
)
|
||||
assert result == "dependency"
|
||||
|
||||
def test_categorize_logic(self, correction_engine):
|
||||
"""Logic errors should be categorized correctly"""
|
||||
result = correction_engine._categorize_failure(
|
||||
"AssertionError: expected 5, actual 3", ""
|
||||
)
|
||||
assert result == "logic"
|
||||
|
||||
def test_categorize_type(self, correction_engine):
|
||||
"""Type errors should be categorized correctly"""
|
||||
result = correction_engine._categorize_failure("TypeError: int is not str", "")
|
||||
assert result == "type"
|
||||
|
||||
def test_categorize_unknown(self, correction_engine):
|
||||
"""Uncategorizable errors should be 'unknown'"""
|
||||
result = correction_engine._categorize_failure("Something weird happened", "")
|
||||
assert result == "unknown"
|
||||
|
||||
def test_analyze_root_cause(self, correction_engine):
|
||||
"""Should produce a RootCause with all fields populated"""
|
||||
failure = {"error": "invalid input: expected integer", "stack_trace": ""}
|
||||
|
||||
root_cause = correction_engine.analyze_root_cause("validate user input", failure)
|
||||
|
||||
assert isinstance(root_cause, RootCause)
|
||||
assert root_cause.category == "validation"
|
||||
assert root_cause.prevention_rule != ""
|
||||
assert len(root_cause.validation_tests) > 0
|
||||
|
||||
def test_learn_and_prevent_new_failure(self, correction_engine):
|
||||
"""New failure should be stored in reflexion memory"""
|
||||
failure = {"type": "logic", "error": "Expected True, got False"}
|
||||
root_cause = RootCause(
|
||||
category="logic",
|
||||
description="Assertion failed",
|
||||
evidence=["Wrong return value"],
|
||||
prevention_rule="ALWAYS verify return values",
|
||||
validation_tests=["Check assertion"],
|
||||
)
|
||||
|
||||
correction_engine.learn_and_prevent("test logic check", failure, root_cause)
|
||||
|
||||
data = json.loads(correction_engine.reflexion_file.read_text())
|
||||
assert len(data["mistakes"]) == 1
|
||||
assert "ALWAYS verify return values" in data["prevention_rules"]
|
||||
|
||||
def test_learn_and_prevent_recurring_failure(self, correction_engine):
|
||||
"""Same failure twice should increment recurrence count"""
|
||||
failure = {"type": "logic", "error": "Same error message"}
|
||||
root_cause = RootCause(
|
||||
category="logic",
|
||||
description="Same error",
|
||||
evidence=["Same"],
|
||||
prevention_rule="Fix it",
|
||||
validation_tests=["Test"],
|
||||
)
|
||||
|
||||
# Record twice with same task+error (same hash)
|
||||
correction_engine.learn_and_prevent("same task", failure, root_cause)
|
||||
correction_engine.learn_and_prevent("same task", failure, root_cause)
|
||||
|
||||
data = json.loads(correction_engine.reflexion_file.read_text())
|
||||
assert len(data["mistakes"]) == 1 # Not duplicated
|
||||
assert data["mistakes"][0]["recurrence_count"] == 1
|
||||
|
||||
def test_find_similar_failures(self, engine_with_history):
|
||||
"""Should find past failures with keyword overlap"""
|
||||
similar = engine_with_history._find_similar_failures(
|
||||
"create user registration endpoint",
|
||||
"null pointer error",
|
||||
)
|
||||
assert len(similar) >= 1
|
||||
|
||||
def test_find_no_similar_failures(self, engine_with_history):
|
||||
"""Unrelated task should find no similar failures"""
|
||||
similar = engine_with_history._find_similar_failures(
|
||||
"deploy kubernetes cluster",
|
||||
"pod scheduling error",
|
||||
)
|
||||
assert len(similar) == 0
|
||||
|
||||
def test_get_prevention_rules(self, engine_with_history):
|
||||
"""Should return stored prevention rules"""
|
||||
rules = engine_with_history.get_prevention_rules()
|
||||
assert len(rules) >= 1
|
||||
assert "validate" in rules[0].lower()
|
||||
|
||||
def test_check_against_past_mistakes(self, engine_with_history):
|
||||
"""Should find relevant past failures for similar task"""
|
||||
relevant = engine_with_history.check_against_past_mistakes(
|
||||
"update user registration form"
|
||||
)
|
||||
assert len(relevant) >= 1
|
||||
|
||||
def test_check_against_past_mistakes_no_match(self, engine_with_history):
|
||||
"""Unrelated task should have no relevant past failures"""
|
||||
relevant = engine_with_history.check_against_past_mistakes(
|
||||
"configure nginx reverse proxy"
|
||||
)
|
||||
assert len(relevant) == 0
|
||||
|
||||
def test_generate_prevention_rule_with_similar(self, correction_engine):
|
||||
"""Prevention rule should note recurrence when similar failures exist"""
|
||||
similar = [
|
||||
FailureEntry(
|
||||
id="x",
|
||||
timestamp="",
|
||||
task="t",
|
||||
failure_type="v",
|
||||
error_message="e",
|
||||
root_cause=RootCause("v", "d", [], "r", []),
|
||||
fixed=False,
|
||||
)
|
||||
]
|
||||
rule = correction_engine._generate_prevention_rule("validation", "err", similar)
|
||||
assert "1 times before" in rule
|
||||
|
||||
def test_generate_validation_tests_known_category(self, correction_engine):
|
||||
"""Known categories should return specific tests"""
|
||||
tests = correction_engine._generate_validation_tests("validation", "err")
|
||||
assert len(tests) == 3
|
||||
assert any("None" in t for t in tests)
|
||||
|
||||
def test_generate_validation_tests_unknown_category(self, correction_engine):
|
||||
"""Unknown category should return generic tests"""
|
||||
tests = correction_engine._generate_validation_tests("exotic", "err")
|
||||
assert len(tests) >= 1
|
||||
Reference in New Issue
Block a user