refactor: PM Agent complete independence from external MCP servers (#439)

* refactor: PM Agent complete independence from external MCP servers

## Summary
Implement graceful degradation to ensure PM Agent operates fully without
any MCP server dependencies. MCP servers now serve as optional enhancements
rather than required components.

## Changes

### Responsibility Separation (NEW)
- **PM Agent**: Development workflow orchestration (PDCA cycle, task management)
- **mindbase**: Memory management (long-term, freshness, error learning)
- **Built-in memory**: Session-internal context (volatile)

### 3-Layer Memory Architecture with Fallbacks
1. **Built-in Memory** [OPTIONAL]: Session context via MCP memory server
2. **mindbase** [OPTIONAL]: Long-term semantic search via airis-mcp-gateway
3. **Local Files** [ALWAYS]: Core functionality in docs/memory/

### Graceful Degradation Implementation
- All MCP operations marked with [ALWAYS] or [OPTIONAL]
- Explicit IF/ELSE fallback logic for every MCP call
- Dual storage: Always write to local files + optionally to mindbase
- Smart lookup: Semantic search (if available) → Text search (always works)

### Key Fallback Strategies

**Session Start**:
- mindbase available: search_conversations() for semantic context
- mindbase unavailable: Grep docs/memory/*.jsonl for text-based lookup

**Error Detection**:
- mindbase available: Semantic search for similar past errors
- mindbase unavailable: Grep docs/mistakes/ + solutions_learned.jsonl

**Knowledge Capture**:
- Always: echo >> docs/memory/patterns_learned.jsonl (persistent)
- Optional: mindbase.store() for semantic search enhancement

## Benefits
-  Zero external dependencies (100% functionality without MCP)
-  Enhanced capabilities when MCPs available (semantic search, freshness)
-  No functionality loss, only reduced search intelligence
-  Transparent degradation (no error messages, automatic fallback)

## Related Research
- Serena MCP investigation: Exposes tools (not resources), memory = markdown files
- mindbase superiority: PostgreSQL + pgvector > Serena memory features
- Best practices alignment: /Users/kazuki/github/airis-mcp-gateway/docs/mcp-best-practices.md

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* chore: add PR template and pre-commit config

- Add structured PR template with Git workflow checklist
- Add pre-commit hooks for secret detection and Conventional Commits
- Enforce code quality gates (YAML/JSON/Markdown lint, shellcheck)

NOTE: Execute pre-commit inside Docker container to avoid host pollution:
  docker compose exec workspace uv tool install pre-commit
  docker compose exec workspace pre-commit run --all-files

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* docs: update PM Agent context with token efficiency architecture

- Add Layer 0 Bootstrap (150 tokens, 95% reduction)
- Document Intent Classification System (5 complexity levels)
- Add Progressive Loading strategy (5-layer)
- Document mindbase integration incentive (38% savings)
- Update with 2025-10-17 redesign details

* refactor: PM Agent command with progressive loading

- Replace auto-loading with User Request First philosophy
- Add 5-layer progressive context loading
- Implement intent classification system
- Add workflow metrics collection (.jsonl)
- Document graceful degradation strategy

* fix: installer improvements

Update installer logic for better reliability

* docs: add comprehensive development documentation

- Add architecture overview
- Add PM Agent improvements analysis
- Add parallel execution architecture
- Add CLI install improvements
- Add code style guide
- Add project overview
- Add install process analysis

* docs: add research documentation

Add LLM agent token efficiency research and analysis

* docs: add suggested commands reference

* docs: add session logs and testing documentation

- Add session analysis logs
- Add testing documentation

* feat: migrate CLI to typer + rich for modern UX

## What Changed

### New CLI Architecture (typer + rich)
- Created `superclaude/cli/` module with modern typer-based CLI
- Replaced custom UI utilities with rich native features
- Added type-safe command structure with automatic validation

### Commands Implemented
- **install**: Interactive installation with rich UI (progress, panels)
- **doctor**: System diagnostics with rich table output
- **config**: API key management with format validation

### Technical Improvements
- Dependencies: Added typer>=0.9.0, rich>=13.0.0, click>=8.0.0
- Entry Point: Updated pyproject.toml to use `superclaude.cli.app:cli_main`
- Tests: Added comprehensive smoke tests (11 passed)

### User Experience Enhancements
- Rich formatted help messages with panels and tables
- Automatic input validation with retry loops
- Clear error messages with actionable suggestions
- Non-interactive mode support for CI/CD

## Testing

```bash
uv run superclaude --help     # ✓ Works
uv run superclaude doctor     # ✓ Rich table output
uv run superclaude config show # ✓ API key management
pytest tests/test_cli_smoke.py # ✓ 11 passed, 1 skipped
```

## Migration Path

-  P0: Foundation complete (typer + rich + smoke tests)
- 🔜 P1: Pydantic validation models (next sprint)
- 🔜 P2: Enhanced error messages (next sprint)
- 🔜 P3: API key retry loops (next sprint)

## Performance Impact

- **Code Reduction**: Prepared for -300 lines (custom UI → rich)
- **Type Safety**: Automatic validation from type hints
- **Maintainability**: Framework primitives vs custom code

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: consolidate documentation directories

Merged claudedocs/ into docs/research/ for consistent documentation structure.

Changes:
- Moved all claudedocs/*.md files to docs/research/
- Updated all path references in documentation (EN/KR)
- Updated RULES.md and research.md command templates
- Removed claudedocs/ directory
- Removed ClaudeDocs/ from .gitignore

Benefits:
- Single source of truth for all research reports
- PEP8-compliant lowercase directory naming
- Clearer documentation organization
- Prevents future claudedocs/ directory creation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* perf: reduce /sc:pm command output from 1652 to 15 lines

- Remove 1637 lines of documentation from command file
- Keep only minimal bootstrap message
- 99% token reduction on command execution
- Detailed specs remain in superclaude/agents/pm-agent.md

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* perf: split PM Agent into execution workflows and guide

- Reduce pm-agent.md from 735 to 429 lines (42% reduction)
- Move philosophy/examples to docs/agents/pm-agent-guide.md
- Execution workflows (PDCA, file ops) stay in pm-agent.md
- Guide (examples, quality standards) read once when needed

Token savings:
- Agent loading: ~6K → ~3.5K tokens (42% reduction)
- Total with pm.md: 71% overall reduction

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: consolidate PM Agent optimization and pending changes

PM Agent optimization (already committed separately):
- superclaude/commands/pm.md: 1652→14 lines
- superclaude/agents/pm-agent.md: 735→429 lines
- docs/agents/pm-agent-guide.md: new guide file

Other pending changes:
- setup: framework_docs, mcp, logger, remove ui.py
- superclaude: __main__, cli/app, cli/commands/install
- tests: test_ui updates
- scripts: workflow metrics analysis tools
- docs/memory: session state updates

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: simplify MCP installer to unified gateway with legacy mode

## Changes

### MCP Component (setup/components/mcp.py)
- Simplified to single airis-mcp-gateway by default
- Added legacy mode for individual official servers (sequential-thinking, context7, magic, playwright)
- Dynamic prerequisites based on mode:
  - Default: uv + claude CLI only
  - Legacy: node (18+) + npm + claude CLI
- Removed redundant server definitions

### CLI Integration
- Added --legacy flag to setup/cli/commands/install.py
- Added --legacy flag to superclaude/cli/commands/install.py
- Config passes legacy_mode to component installer

## Benefits
-  Simpler: 1 gateway vs 9+ individual servers
-  Lighter: No Node.js/npm required (default mode)
-  Unified: All tools in one gateway (sequential-thinking, context7, magic, playwright, serena, morphllm, tavily, chrome-devtools, git, puppeteer)
-  Flexible: --legacy flag for official servers if needed

## Usage
```bash
superclaude install              # Default: airis-mcp-gateway (推奨)
superclaude install --legacy     # Legacy: individual official servers
```

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: rename CoreComponent to FrameworkDocsComponent and add PM token tracking

## Changes

### Component Renaming (setup/components/)
- Renamed CoreComponent → FrameworkDocsComponent for clarity
- Updated all imports in __init__.py, agents.py, commands.py, mcp_docs.py, modes.py
- Better reflects the actual purpose (framework documentation files)

### PM Agent Enhancement (superclaude/commands/pm.md)
- Added token usage tracking instructions
- PM Agent now reports:
  1. Current token usage from system warnings
  2. Percentage used (e.g., "27% used" for 54K/200K)
  3. Status zone: 🟢 <75% | 🟡 75-85% | 🔴 >85%
- Helps prevent token exhaustion during long sessions

### UI Utilities (setup/utils/ui.py)
- Added new UI utility module for installer
- Provides consistent user interface components

## Benefits
-  Clearer component naming (FrameworkDocs vs Core)
-  PM Agent token awareness for efficiency
-  Better visual feedback with status zones

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(pm-agent): minimize output verbosity (471→284 lines, 40% reduction)

**Problem**: PM Agent generated excessive output with redundant explanations
- "System Status Report" with decorative formatting
- Repeated "Common Tasks" lists user already knows
- Verbose session start/end protocols
- Duplicate file operations documentation

**Solution**: Compress without losing functionality
- Session Start: Reduced to symbol-only status (🟢 branch | nM nD | token%)
- Session End: Compressed to essential actions only
- File Operations: Consolidated from 2 sections to 1 line reference
- Self-Improvement: 5 phases → 1 unified workflow
- Output Rules: Explicit constraints to prevent Claude over-explanation

**Quality Preservation**:
-  All core functions retained (PDCA, memory, patterns, mistakes)
-  PARALLEL Read/Write preserved (performance critical)
-  Workflow unchanged (session lifecycle intact)
-  Added output constraints (prevents verbose generation)

**Reduction Method**:
- Deleted: Explanatory text, examples, redundant sections
- Retained: Action definitions, file paths, core workflows
- Added: Explicit output constraints to enforce minimalism

**Token Impact**: 40% reduction in agent documentation size
**Before**: Verbose multi-section report with task lists
**After**: Single line status: 🟢 integration | 15M 17D | 36%

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: consolidate MCP integration to unified gateway

**Changes**:
- Remove individual MCP server docs (superclaude/mcp/*.md)
- Remove MCP server configs (superclaude/mcp/configs/*.json)
- Delete MCP docs component (setup/components/mcp_docs.py)
- Simplify installer (setup/core/installer.py)
- Update components for unified gateway approach

**Rationale**:
- Unified gateway (airis-mcp-gateway) provides all MCP servers
- Individual docs/configs no longer needed (managed centrally)
- Reduces maintenance burden and file count
- Simplifies installation process

**Files Removed**: 17 MCP files (docs + configs)
**Installer Changes**: Removed legacy MCP installation logic

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* chore: update version and component metadata

- Bump version (pyproject.toml, setup/__init__.py)
- Update CLAUDE.md import service references
- Reflect component structure changes

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: kazuki <kazuki@kazukinoMacBook-Air.local>
Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
kazuki nakai
2025-10-17 09:13:06 +09:00
committed by GitHub
parent 5bc82dbe30
commit 882a0d8356
90 changed files with 12060 additions and 3773 deletions

View File

@@ -1,17 +1,15 @@
"""Component implementations for SuperClaude installation system"""
from .core import CoreComponent
from .framework_docs import FrameworkDocsComponent
from .commands import CommandsComponent
from .mcp import MCPComponent
from .agents import AgentsComponent
from .modes import ModesComponent
from .mcp_docs import MCPDocsComponent
__all__ = [
"CoreComponent",
"FrameworkDocsComponent",
"CommandsComponent",
"MCPComponent",
"AgentsComponent",
"ModesComponent",
"MCPDocsComponent",
]

View File

@@ -25,6 +25,13 @@ class AgentsComponent(Component):
"category": "agents",
}
def is_reinstallable(self) -> bool:
"""
Agents should always be synced to latest version.
SuperClaude agent files always overwrite existing files.
"""
return True
def get_metadata_modifications(self) -> Dict[str, Any]:
"""Get metadata modifications for agents"""
return {
@@ -64,14 +71,14 @@ class AgentsComponent(Component):
self.settings_manager.update_metadata(metadata_mods)
self.logger.info("Updated metadata with agents configuration")
# Add component registration
# Add component registration (with file list for sync)
self.settings_manager.add_component_registration(
"agents",
{
"version": __version__,
"category": "agents",
"agents_count": len(self.component_files),
"agents_list": self.component_files,
"files": list(self.component_files), # Track for sync/deletion
},
)
@@ -126,60 +133,54 @@ class AgentsComponent(Component):
def get_dependencies(self) -> List[str]:
"""Get component dependencies"""
return ["core"]
return ["framework_docs"]
def update(self, config: Dict[str, Any]) -> bool:
"""Update agents component"""
"""
Sync agents component (overwrite + delete obsolete files).
No backup needed - SuperClaude source files are always authoritative.
"""
try:
self.logger.info("Updating SuperClaude agents component...")
self.logger.info("Syncing SuperClaude agents component...")
# Check current version
current_version = self.settings_manager.get_component_version("agents")
target_version = self.get_metadata()["version"]
if current_version == target_version:
self.logger.info(
f"Agents component already at version {target_version}"
)
return True
self.logger.info(
f"Updating agents component from {current_version} to {target_version}"
# Get previously installed files from metadata
metadata = self.settings_manager.load_metadata()
previous_files = set(
metadata.get("components", {}).get("agents", {}).get("files", [])
)
# Create backup of existing agents
backup_files = []
for filename in self.component_files:
# Get current files from source
current_files = set(self.component_files)
# Files to delete (were installed before, but no longer in source)
files_to_delete = previous_files - current_files
# Delete obsolete files
deleted_count = 0
for filename in files_to_delete:
file_path = self.install_component_subdir / filename
if file_path.exists():
backup_path = self.file_manager.backup_file(file_path)
if backup_path:
backup_files.append(backup_path)
self.logger.debug(f"Backed up agent: {filename}")
# Perform installation (will overwrite existing files)
if self._install(config):
self.logger.success(
f"Agents component updated to version {target_version}"
)
return True
else:
# Restore backups on failure
self.logger.error("Agents update failed, restoring backups...")
for backup_path in backup_files:
try:
original_path = (
self.install_component_subdir
/ backup_path.name.replace(".backup", "")
)
self.file_manager.copy_file(backup_path, original_path)
self.logger.debug(f"Restored {original_path.name}")
file_path.unlink()
deleted_count += 1
self.logger.info(f"Deleted obsolete agent: {filename}")
except Exception as e:
self.logger.warning(f"Could not restore {backup_path}: {e}")
return False
self.logger.warning(f"Could not delete {filename}: {e}")
# Install/overwrite current files (no backup)
success = self._install(config)
if success:
self.logger.success(
f"Agents synced: {len(current_files)} files, {deleted_count} obsolete files removed"
)
else:
self.logger.error("Agents sync failed")
return success
except Exception as e:
self.logger.exception(f"Unexpected error during agents update: {e}")
self.logger.exception(f"Unexpected error during agents sync: {e}")
return False
def _get_source_dir(self) -> Path:

View File

@@ -14,6 +14,15 @@ class CommandsComponent(Component):
def __init__(self, install_dir: Optional[Path] = None):
"""Initialize commands component"""
if install_dir is None:
install_dir = Path.home() / ".claude"
# Commands are installed directly to ~/.claude/commands/sc/
# not under superclaude/ subdirectory (Claude Code official location)
if "superclaude" in str(install_dir):
# ~/.claude/superclaude -> ~/.claude
install_dir = install_dir.parent
super().__init__(install_dir, Path("commands/sc"))
def get_metadata(self) -> Dict[str, str]:
@@ -25,6 +34,13 @@ class CommandsComponent(Component):
"category": "commands",
}
def is_reinstallable(self) -> bool:
"""
Commands should always be synced to latest version.
SuperClaude command files always overwrite existing files.
"""
return True
def get_metadata_modifications(self) -> Dict[str, Any]:
"""Get metadata modifications for commands component"""
return {
@@ -54,13 +70,14 @@ class CommandsComponent(Component):
self.settings_manager.update_metadata(metadata_mods)
self.logger.info("Updated metadata with commands configuration")
# Add component registration to metadata
# Add component registration to metadata (with file list for sync)
self.settings_manager.add_component_registration(
"commands",
{
"version": __version__,
"category": "commands",
"files_count": len(self.component_files),
"files": list(self.component_files), # Track for sync/deletion
},
)
self.logger.info("Updated metadata with commands component registration")
@@ -68,6 +85,16 @@ class CommandsComponent(Component):
self.logger.error(f"Failed to update metadata: {e}")
return False
# Clean up old commands directory in superclaude/ (from previous versions)
try:
old_superclaude_commands = Path.home() / ".claude" / "superclaude" / "commands"
if old_superclaude_commands.exists():
import shutil
shutil.rmtree(old_superclaude_commands)
self.logger.info("Removed old commands directory from superclaude/")
except Exception as e:
self.logger.debug(f"Could not remove old commands directory: {e}")
return True
def uninstall(self) -> bool:
@@ -153,69 +180,66 @@ class CommandsComponent(Component):
def get_dependencies(self) -> List[str]:
"""Get dependencies"""
return ["core"]
return ["framework_docs"]
def update(self, config: Dict[str, Any]) -> bool:
"""Update commands component"""
"""
Sync commands component (overwrite + delete obsolete files).
No backup needed - SuperClaude source files are always authoritative.
"""
try:
self.logger.info("Updating SuperClaude commands component...")
self.logger.info("Syncing SuperClaude commands component...")
# Check current version
current_version = self.settings_manager.get_component_version("commands")
target_version = self.get_metadata()["version"]
if current_version == target_version:
self.logger.info(
f"Commands component already at version {target_version}"
)
return True
self.logger.info(
f"Updating commands component from {current_version} to {target_version}"
# Get previously installed files from metadata
metadata = self.settings_manager.load_metadata()
previous_files = set(
metadata.get("components", {}).get("commands", {}).get("files", [])
)
# Create backup of existing command files
# Get current files from source
current_files = set(self.component_files)
# Files to delete (were installed before, but no longer in source)
files_to_delete = previous_files - current_files
# Delete obsolete files
deleted_count = 0
commands_dir = self.install_dir / "commands" / "sc"
backup_files = []
for filename in files_to_delete:
file_path = commands_dir / filename
if file_path.exists():
try:
file_path.unlink()
deleted_count += 1
self.logger.info(f"Deleted obsolete command: {filename}")
except Exception as e:
self.logger.warning(f"Could not delete {filename}: {e}")
if commands_dir.exists():
for filename in self.component_files:
file_path = commands_dir / filename
if file_path.exists():
backup_path = self.file_manager.backup_file(file_path)
if backup_path:
backup_files.append(backup_path)
self.logger.debug(f"Backed up {filename}")
# Perform installation (overwrites existing files)
# Install/overwrite current files (no backup)
success = self.install(config)
if success:
# Remove backup files on successful update
for backup_path in backup_files:
try:
backup_path.unlink()
except Exception:
pass # Ignore cleanup errors
# Update metadata with current file list
self.settings_manager.add_component_registration(
"commands",
{
"version": __version__,
"category": "commands",
"files_count": len(current_files),
"files": list(current_files), # Track installed files
},
)
self.logger.success(
f"Commands component updated to version {target_version}"
f"Commands synced: {len(current_files)} files, {deleted_count} obsolete files removed"
)
else:
# Restore from backup on failure
self.logger.warning("Update failed, restoring from backup...")
for backup_path in backup_files:
try:
original_path = backup_path.with_suffix("")
backup_path.rename(original_path)
self.logger.debug(f"Restored {original_path.name}")
except Exception as e:
self.logger.error(f"Could not restore {backup_path}: {e}")
self.logger.error("Commands sync failed")
return success
except Exception as e:
self.logger.exception(f"Unexpected error during commands update: {e}")
self.logger.exception(f"Unexpected error during commands sync: {e}")
return False
def validate_installation(self) -> Tuple[bool, List[str]]:

View File

@@ -1,5 +1,6 @@
"""
Core component for SuperClaude framework files installation
Framework documentation component for SuperClaude
Manages core framework documentation files (CLAUDE.md, FLAGS.md, PRINCIPLES.md, etc.)
"""
from typing import Dict, List, Tuple, Optional, Any
@@ -11,22 +12,29 @@ from ..services.claude_md import CLAUDEMdService
from setup import __version__
class CoreComponent(Component):
"""Core SuperClaude framework files component"""
class FrameworkDocsComponent(Component):
"""SuperClaude framework documentation files component"""
def __init__(self, install_dir: Optional[Path] = None):
"""Initialize core component"""
"""Initialize framework docs component"""
super().__init__(install_dir)
def get_metadata(self) -> Dict[str, str]:
"""Get component metadata"""
return {
"name": "core",
"name": "framework_docs",
"version": __version__,
"description": "SuperClaude framework documentation and core files",
"category": "core",
"description": "SuperClaude framework documentation (CLAUDE.md, FLAGS.md, PRINCIPLES.md, RULES.md, etc.)",
"category": "documentation",
}
def is_reinstallable(self) -> bool:
"""
Framework docs should always be updated to latest version.
SuperClaude-related documentation should always overwrite existing files.
"""
return True
def get_metadata_modifications(self) -> Dict[str, Any]:
"""Get metadata modifications for SuperClaude"""
return {
@@ -35,7 +43,7 @@ class CoreComponent(Component):
"name": "superclaude",
"description": "AI-enhanced development framework for Claude Code",
"installation_type": "global",
"components": ["core"],
"components": ["framework_docs"],
},
"superclaude": {
"enabled": True,
@@ -46,8 +54,8 @@ class CoreComponent(Component):
}
def _install(self, config: Dict[str, Any]) -> bool:
"""Install core component"""
self.logger.info("Installing SuperClaude core framework files...")
"""Install framework docs component"""
self.logger.info("Installing SuperClaude framework documentation...")
return super()._install(config)
@@ -58,17 +66,18 @@ class CoreComponent(Component):
self.settings_manager.update_metadata(metadata_mods)
self.logger.info("Updated metadata with framework configuration")
# Add component registration to metadata
# Add component registration to metadata (with file list for sync)
self.settings_manager.add_component_registration(
"core",
"framework_docs",
{
"version": __version__,
"category": "core",
"category": "documentation",
"files_count": len(self.component_files),
"files": list(self.component_files), # Track for sync/deletion
},
)
self.logger.info("Updated metadata with core component registration")
self.logger.info("Updated metadata with framework docs component registration")
# Migrate any existing SuperClaude data from settings.json
if self.settings_manager.migrate_superclaude_data():
@@ -86,23 +95,23 @@ class CoreComponent(Component):
if not self.file_manager.ensure_directory(dir_path):
self.logger.warning(f"Could not create directory: {dir_path}")
# Update CLAUDE.md with core framework imports
# Update CLAUDE.md with framework documentation imports
try:
manager = CLAUDEMdService(self.install_dir)
manager.add_imports(self.component_files, category="Core Framework")
self.logger.info("Updated CLAUDE.md with core framework imports")
manager.add_imports(self.component_files, category="Framework Documentation")
self.logger.info("Updated CLAUDE.md with framework documentation imports")
except Exception as e:
self.logger.warning(
f"Failed to update CLAUDE.md with core framework imports: {e}"
f"Failed to update CLAUDE.md with framework documentation imports: {e}"
)
# Don't fail the whole installation for this
return True
def uninstall(self) -> bool:
"""Uninstall core component"""
"""Uninstall framework docs component"""
try:
self.logger.info("Uninstalling SuperClaude core component...")
self.logger.info("Uninstalling SuperClaude framework docs component...")
# Remove framework files
removed_count = 0
@@ -114,10 +123,10 @@ class CoreComponent(Component):
else:
self.logger.warning(f"Could not remove {filename}")
# Update metadata to remove core component
# Update metadata to remove framework docs component
try:
if self.settings_manager.is_component_installed("core"):
self.settings_manager.remove_component_registration("core")
if self.settings_manager.is_component_installed("framework_docs"):
self.settings_manager.remove_component_registration("framework_docs")
metadata_mods = self.get_metadata_modifications()
metadata = self.settings_manager.load_metadata()
for key in metadata_mods.keys():
@@ -125,83 +134,86 @@ class CoreComponent(Component):
del metadata[key]
self.settings_manager.save_metadata(metadata)
self.logger.info("Removed core component from metadata")
self.logger.info("Removed framework docs component from metadata")
except Exception as e:
self.logger.warning(f"Could not update metadata: {e}")
self.logger.success(
f"Core component uninstalled ({removed_count} files removed)"
f"Framework docs component uninstalled ({removed_count} files removed)"
)
return True
except Exception as e:
self.logger.exception(f"Unexpected error during core uninstallation: {e}")
self.logger.exception(f"Unexpected error during framework docs uninstallation: {e}")
return False
def get_dependencies(self) -> List[str]:
"""Get component dependencies (core has none)"""
"""Get component dependencies (framework docs has none)"""
return []
def update(self, config: Dict[str, Any]) -> bool:
"""Update core component"""
"""
Sync framework docs component (overwrite + delete obsolete files).
No backup needed - SuperClaude source files are always authoritative.
"""
try:
self.logger.info("Updating SuperClaude core component...")
self.logger.info("Syncing SuperClaude framework docs component...")
# Check current version
current_version = self.settings_manager.get_component_version("core")
target_version = self.get_metadata()["version"]
if current_version == target_version:
self.logger.info(f"Core component already at version {target_version}")
return True
self.logger.info(
f"Updating core component from {current_version} to {target_version}"
# Get previously installed files from metadata
metadata = self.settings_manager.load_metadata()
previous_files = set(
metadata.get("components", {})
.get("framework_docs", {})
.get("files", [])
)
# Create backup of existing files
backup_files = []
for filename in self.component_files:
# Get current files from source
current_files = set(self.component_files)
# Files to delete (were installed before, but no longer in source)
files_to_delete = previous_files - current_files
# Delete obsolete files
deleted_count = 0
for filename in files_to_delete:
file_path = self.install_dir / filename
if file_path.exists():
backup_path = self.file_manager.backup_file(file_path)
if backup_path:
backup_files.append(backup_path)
self.logger.debug(f"Backed up {filename}")
try:
file_path.unlink()
deleted_count += 1
self.logger.info(f"Deleted obsolete file: {filename}")
except Exception as e:
self.logger.warning(f"Could not delete {filename}: {e}")
# Perform installation (overwrites existing files)
# Install/overwrite current files (no backup)
success = self.install(config)
if success:
# Remove backup files on successful update
for backup_path in backup_files:
try:
backup_path.unlink()
except Exception:
pass # Ignore cleanup errors
# Update metadata with current file list
self.settings_manager.add_component_registration(
"framework_docs",
{
"version": __version__,
"category": "documentation",
"files_count": len(current_files),
"files": list(current_files), # Track installed files
},
)
self.logger.success(
f"Core component updated to version {target_version}"
f"Framework docs synced: {len(current_files)} files, {deleted_count} obsolete files removed"
)
else:
# Restore from backup on failure
self.logger.warning("Update failed, restoring from backup...")
for backup_path in backup_files:
try:
original_path = backup_path.with_suffix("")
shutil.move(str(backup_path), str(original_path))
self.logger.debug(f"Restored {original_path.name}")
except Exception as e:
self.logger.error(f"Could not restore {backup_path}: {e}")
self.logger.error("Framework docs sync failed")
return success
except Exception as e:
self.logger.exception(f"Unexpected error during core update: {e}")
self.logger.exception(f"Unexpected error during framework docs sync: {e}")
return False
def validate_installation(self) -> Tuple[bool, List[str]]:
"""Validate core component installation"""
"""Validate framework docs component installation"""
errors = []
# Check if all framework files exist
@@ -213,11 +225,11 @@ class CoreComponent(Component):
errors.append(f"Framework file is not a regular file: {filename}")
# Check metadata registration
if not self.settings_manager.is_component_installed("core"):
errors.append("Core component not registered in metadata")
if not self.settings_manager.is_component_installed("framework_docs"):
errors.append("Framework docs component not registered in metadata")
else:
# Check version matches
installed_version = self.settings_manager.get_component_version("core")
installed_version = self.settings_manager.get_component_version("framework_docs")
expected_version = self.get_metadata()["version"]
if installed_version != expected_version:
errors.append(
@@ -240,9 +252,9 @@ class CoreComponent(Component):
return len(errors) == 0, errors
def _get_source_dir(self):
"""Get source directory for framework files"""
# Assume we're in superclaude/setup/components/core.py
# and framework files are in superclaude/superclaude/Core/
"""Get source directory for framework documentation files"""
# Assume we're in superclaude/setup/components/framework_docs.py
# and framework files are in superclaude/superclaude/core/
project_root = Path(__file__).parent.parent.parent
return project_root / "superclaude" / "core"

View File

@@ -13,7 +13,6 @@ from typing import Any, Dict, List, Optional, Tuple
from setup import __version__
from ..core.base import Component
from ..utils.ui import display_info, display_warning
class MCPComponent(Component):
@@ -25,7 +24,20 @@ class MCPComponent(Component):
self.installed_servers_in_session: List[str] = []
# Define MCP servers to install
self.mcp_servers = {
# Default: airis-mcp-gateway (unified gateway with all tools)
# Legacy mode (--legacy flag): individual official servers
self.mcp_servers_default = {
"airis-mcp-gateway": {
"name": "airis-mcp-gateway",
"description": "Unified MCP Gateway with all tools (sequential-thinking, context7, magic, playwright, serena, morphllm, tavily, chrome-devtools, git, puppeteer)",
"install_method": "github",
"install_command": "uvx --from git+https://github.com/oraios/airis-mcp-gateway airis-mcp-gateway --help",
"run_command": "uvx --from git+https://github.com/oraios/airis-mcp-gateway airis-mcp-gateway",
"required": True,
},
}
self.mcp_servers_legacy = {
"sequential-thinking": {
"name": "sequential-thinking",
"description": "Multi-step problem solving and systematic analysis",
@@ -52,54 +64,17 @@ class MCPComponent(Component):
"npm_package": "@playwright/mcp@latest",
"required": False,
},
"serena": {
"name": "serena",
"description": "Semantic code analysis and intelligent editing",
"install_method": "github",
"install_command": "uvx --from git+https://github.com/oraios/serena serena --help",
"run_command": "uvx --from git+https://github.com/oraios/serena serena start-mcp-server --context ide-assistant --enable-web-dashboard false --enable-gui-log-window false",
"required": False,
},
"morphllm-fast-apply": {
"name": "morphllm-fast-apply",
"description": "Fast Apply capability for context-aware code modifications",
"npm_package": "@morph-llm/morph-fast-apply",
"required": False,
"api_key_env": "MORPH_API_KEY",
"api_key_description": "Morph API key for Fast Apply",
},
"tavily": {
"name": "tavily",
"description": "Web search and real-time information retrieval for deep research",
"install_method": "npm",
"install_command": "npx -y tavily-mcp@0.1.2",
"required": False,
"api_key_env": "TAVILY_API_KEY",
"api_key_description": "Tavily API key for web search (get from https://app.tavily.com)",
},
"chrome-devtools": {
"name": "chrome-devtools",
"description": "Chrome DevTools debugging and performance analysis",
"install_method": "npm",
"install_command": "npx -y chrome-devtools-mcp@latest",
"required": False,
},
"airis-mcp-gateway": {
"name": "airis-mcp-gateway",
"description": "Dynamic MCP Gateway for zero-token baseline and on-demand tool loading",
"install_method": "github",
"install_command": "uvx --from git+https://github.com/oraios/airis-mcp-gateway airis-mcp-gateway --help",
"run_command": "uvx --from git+https://github.com/oraios/airis-mcp-gateway airis-mcp-gateway",
"required": False,
},
}
# Default to unified gateway
self.mcp_servers = self.mcp_servers_default
def get_metadata(self) -> Dict[str, str]:
"""Get component metadata"""
return {
"name": "mcp",
"version": __version__,
"description": "MCP server integration (Context7, Sequential, Magic, Playwright)",
"description": "Unified MCP Gateway (airis-mcp-gateway) with all integrated tools",
"category": "integration",
}
@@ -137,33 +112,13 @@ class MCPComponent(Component):
def validate_prerequisites(
self, installSubPath: Optional[Path] = None
) -> Tuple[bool, List[str]]:
"""Check prerequisites"""
"""Check prerequisites (varies based on legacy mode)"""
errors = []
# Check if Node.js is available
try:
result = self._run_command_cross_platform(
["node", "--version"], capture_output=True, text=True, timeout=10
)
if result.returncode != 0:
errors.append("Node.js not found - required for MCP servers")
else:
version = result.stdout.strip()
self.logger.debug(f"Found Node.js {version}")
# Check which server set we're using
is_legacy = self.mcp_servers == self.mcp_servers_legacy
# Check version (require 18+)
try:
version_num = int(version.lstrip("v").split(".")[0])
if version_num < 18:
errors.append(
f"Node.js version {version} found, but version 18+ required"
)
except:
self.logger.warning(f"Could not parse Node.js version: {version}")
except (subprocess.TimeoutExpired, FileNotFoundError):
errors.append("Node.js not found - required for MCP servers")
# Check if Claude CLI is available
# Check if Claude CLI is available (always required)
try:
result = self._run_command_cross_platform(
["claude", "--version"], capture_output=True, text=True, timeout=10
@@ -178,35 +133,53 @@ class MCPComponent(Component):
except (subprocess.TimeoutExpired, FileNotFoundError):
errors.append("Claude CLI not found - required for MCP server management")
# Check if npm is available
try:
result = self._run_command_cross_platform(
["npm", "--version"], capture_output=True, text=True, timeout=10
)
if result.returncode != 0:
errors.append("npm not found - required for MCP server installation")
else:
version = result.stdout.strip()
self.logger.debug(f"Found npm {version}")
except (subprocess.TimeoutExpired, FileNotFoundError):
errors.append("npm not found - required for MCP server installation")
# Check if uv is available (required for Serena)
try:
result = self._run_command_cross_platform(
["uv", "--version"], capture_output=True, text=True, timeout=10
)
if result.returncode != 0:
self.logger.warning(
"uv not found - required for Serena MCP server installation"
if is_legacy:
# Legacy mode: requires Node.js and npm for official servers
try:
result = self._run_command_cross_platform(
["node", "--version"], capture_output=True, text=True, timeout=10
)
else:
version = result.stdout.strip()
self.logger.debug(f"Found uv {version}")
except (subprocess.TimeoutExpired, FileNotFoundError):
self.logger.warning(
"uv not found - required for Serena MCP server installation"
)
if result.returncode != 0:
errors.append("Node.js not found - required for legacy MCP servers")
else:
version = result.stdout.strip()
self.logger.debug(f"Found Node.js {version}")
# Check version (require 18+)
try:
version_num = int(version.lstrip("v").split(".")[0])
if version_num < 18:
errors.append(
f"Node.js version {version} found, but version 18+ required"
)
except:
self.logger.warning(f"Could not parse Node.js version: {version}")
except (subprocess.TimeoutExpired, FileNotFoundError):
errors.append("Node.js not found - required for legacy MCP servers")
try:
result = self._run_command_cross_platform(
["npm", "--version"], capture_output=True, text=True, timeout=10
)
if result.returncode != 0:
errors.append("npm not found - required for legacy MCP server installation")
else:
version = result.stdout.strip()
self.logger.debug(f"Found npm {version}")
except (subprocess.TimeoutExpired, FileNotFoundError):
errors.append("npm not found - required for legacy MCP server installation")
else:
# Default mode: requires uv for airis-mcp-gateway
try:
result = self._run_command_cross_platform(
["uv", "--version"], capture_output=True, text=True, timeout=10
)
if result.returncode != 0:
errors.append("uv not found - required for airis-mcp-gateway installation")
else:
version = result.stdout.strip()
self.logger.debug(f"Found uv {version}")
except (subprocess.TimeoutExpired, FileNotFoundError):
errors.append("uv not found - required for airis-mcp-gateway installation")
return len(errors) == 0, errors
@@ -594,15 +567,9 @@ class MCPComponent(Component):
# Map common variations to our standard names
name_mappings = {
"context7": "context7",
"sequential-thinking": "sequential-thinking",
"sequential": "sequential-thinking",
"magic": "magic",
"playwright": "playwright",
"serena": "serena",
"morphllm": "morphllm-fast-apply",
"morphllm-fast-apply": "morphllm-fast-apply",
"morph": "morphllm-fast-apply",
"airis-mcp-gateway": "airis-mcp-gateway",
"airis": "airis-mcp-gateway",
"gateway": "airis-mcp-gateway",
}
return name_mappings.get(server_name)
@@ -672,15 +639,15 @@ class MCPComponent(Component):
)
if not config.get("dry_run", False):
display_info(f"MCP server '{server_name}' requires an API key")
display_info(f"Environment variable: {api_key_env}")
display_info(f"Description: {api_key_desc}")
self.logger.info(f"MCP server '{server_name}' requires an API key")
self.logger.info(f"Environment variable: {api_key_env}")
self.logger.info(f"Description: {api_key_desc}")
# Check if API key is already set
import os
if not os.getenv(api_key_env):
display_warning(
self.logger.warning(
f"API key {api_key_env} not found in environment"
)
self.logger.warning(
@@ -799,7 +766,15 @@ class MCPComponent(Component):
def _install(self, config: Dict[str, Any]) -> bool:
"""Install MCP component with auto-detection of existing servers"""
self.logger.info("Installing SuperClaude MCP servers...")
# Check for legacy mode flag
use_legacy = config.get("legacy_mode", False) or config.get("official_servers", False)
if use_legacy:
self.logger.info("Installing individual official MCP servers (legacy mode)...")
self.mcp_servers = self.mcp_servers_legacy
else:
self.logger.info("Installing unified MCP gateway (airis-mcp-gateway)...")
self.mcp_servers = self.mcp_servers_default
# Validate prerequisites
success, errors = self.validate_prerequisites()
@@ -966,7 +941,7 @@ class MCPComponent(Component):
def get_dependencies(self) -> List[str]:
"""Get dependencies"""
return ["core"]
return ["framework_docs"]
def update(self, config: Dict[str, Any]) -> bool:
"""Update MCP component"""
@@ -1096,9 +1071,21 @@ class MCPComponent(Component):
return {
"component": self.get_metadata()["name"],
"version": self.get_metadata()["version"],
"servers_count": len(self.mcp_servers),
"mcp_servers": list(self.mcp_servers.keys()),
"servers_count": 1, # Only airis-mcp-gateway
"mcp_servers": ["airis-mcp-gateway"],
"included_tools": [
"sequential-thinking",
"context7",
"magic",
"playwright",
"serena",
"morphllm",
"tavily",
"chrome-devtools",
"git",
"puppeteer",
],
"estimated_size": self.get_size_estimate(),
"dependencies": self.get_dependencies(),
"required_tools": ["node", "npm", "claude"],
"required_tools": ["uv", "claude"],
}

View File

@@ -1,374 +0,0 @@
"""
MCP Documentation component for SuperClaude MCP server documentation
"""
from typing import Dict, List, Tuple, Optional, Any
from pathlib import Path
from ..core.base import Component
from setup import __version__
from ..services.claude_md import CLAUDEMdService
class MCPDocsComponent(Component):
"""MCP documentation component - installs docs for selected MCP servers"""
def __init__(self, install_dir: Optional[Path] = None):
"""Initialize MCP docs component"""
# Initialize attributes before calling parent constructor
# because parent calls _discover_component_files() which needs these
self.selected_servers: List[str] = []
# Map server names to documentation files
self.server_docs_map = {
"context7": "MCP_Context7.md",
"sequential": "MCP_Sequential.md",
"sequential-thinking": "MCP_Sequential.md", # Handle both naming conventions
"magic": "MCP_Magic.md",
"playwright": "MCP_Playwright.md",
"serena": "MCP_Serena.md",
"morphllm": "MCP_Morphllm.md",
"morphllm-fast-apply": "MCP_Morphllm.md", # Handle both naming conventions
"tavily": "MCP_Tavily.md",
}
super().__init__(install_dir, Path(""))
def get_metadata(self) -> Dict[str, str]:
"""Get component metadata"""
return {
"name": "mcp_docs",
"version": __version__,
"description": "MCP server documentation and usage guides",
"category": "documentation",
}
def is_reinstallable(self) -> bool:
"""
Allow mcp_docs to be reinstalled to handle different server selections.
This enables users to add or change MCP server documentation.
"""
return True
def set_selected_servers(self, selected_servers: List[str]) -> None:
"""Set which MCP servers were selected for documentation installation"""
self.selected_servers = selected_servers
self.logger.debug(f"MCP docs will be installed for: {selected_servers}")
def get_files_to_install(self) -> List[Tuple[Path, Path]]:
"""
Return list of files to install based on selected MCP servers
Returns:
List of tuples (source_path, target_path)
"""
source_dir = self._get_source_dir()
files = []
if source_dir and self.selected_servers:
for server_name in self.selected_servers:
if server_name in self.server_docs_map:
doc_file = self.server_docs_map[server_name]
source = source_dir / doc_file
target = self.install_dir / doc_file
if source.exists():
files.append((source, target))
self.logger.debug(
f"Will install documentation for {server_name}: {doc_file}"
)
else:
self.logger.warning(
f"Documentation file not found for {server_name}: {doc_file}"
)
return files
def _discover_component_files(self) -> List[str]:
"""
Override parent method to dynamically discover files based on selected servers
"""
files = []
# Check if selected_servers is not empty
if self.selected_servers:
for server_name in self.selected_servers:
if server_name in self.server_docs_map:
files.append(self.server_docs_map[server_name])
return files
def _detect_existing_mcp_servers_from_config(self) -> List[str]:
"""Detect existing MCP servers from Claude Desktop config"""
detected_servers = []
try:
# Try to find Claude Desktop config file
config_paths = [
self.install_dir / "claude_desktop_config.json",
Path.home() / ".claude" / "claude_desktop_config.json",
Path.home() / ".claude.json", # Claude CLI config
Path.home()
/ "AppData"
/ "Roaming"
/ "Claude"
/ "claude_desktop_config.json", # Windows
Path.home()
/ "Library"
/ "Application Support"
/ "Claude"
/ "claude_desktop_config.json", # macOS
]
config_file = None
for path in config_paths:
if path.exists():
config_file = path
break
if not config_file:
self.logger.debug("No Claude Desktop config file found")
return detected_servers
import json
with open(config_file, "r") as f:
config = json.load(f)
# Extract MCP server names from mcpServers section
mcp_servers = config.get("mcpServers", {})
for server_name in mcp_servers.keys():
# Map common name variations to our doc file names
normalized_name = self._normalize_server_name(server_name)
if normalized_name and normalized_name in self.server_docs_map:
detected_servers.append(normalized_name)
if detected_servers:
self.logger.info(
f"Detected existing MCP servers from config: {detected_servers}"
)
except Exception as e:
self.logger.warning(f"Could not read Claude Desktop config: {e}")
return detected_servers
def _normalize_server_name(self, server_name: str) -> Optional[str]:
"""Normalize server name to match our documentation mapping"""
if not server_name:
return None
server_name = server_name.lower().strip()
# Map common variations to our server_docs_map keys
name_mappings = {
"context7": "context7",
"sequential-thinking": "sequential-thinking",
"sequential": "sequential-thinking",
"magic": "magic",
"playwright": "playwright",
"serena": "serena",
"morphllm": "morphllm",
"morphllm-fast-apply": "morphllm",
"morph": "morphllm",
}
return name_mappings.get(server_name)
def _install(self, config: Dict[str, Any]) -> bool:
"""Install MCP documentation component with auto-detection"""
self.logger.info("Installing MCP server documentation...")
# Auto-detect existing servers
self.logger.info("Auto-detecting existing MCP servers for documentation...")
detected_servers = self._detect_existing_mcp_servers_from_config()
# Get selected servers from config
selected_servers = config.get("selected_mcp_servers", [])
# Get previously documented servers from metadata
previous_servers = self.settings_manager.get_metadata_setting(
"components.mcp_docs.servers_documented", []
)
# Merge all server lists
all_servers = list(set(detected_servers + selected_servers + previous_servers))
# Filter to only servers we have documentation for
valid_servers = [s for s in all_servers if s in self.server_docs_map]
if not valid_servers:
self.logger.info(
"No MCP servers detected or selected for documentation installation"
)
# Still proceed to update metadata
self.set_selected_servers([])
self.component_files = []
return self._post_install()
self.logger.info(
f"Installing documentation for MCP servers: {', '.join(valid_servers)}"
)
if detected_servers:
self.logger.info(f" - Detected from config: {detected_servers}")
if selected_servers:
self.logger.info(f" - Newly selected: {selected_servers}")
if previous_servers:
self.logger.info(f" - Previously documented: {previous_servers}")
# Set the servers for which we'll install documentation
self.set_selected_servers(valid_servers)
self.component_files = self._discover_component_files()
# Validate installation
success, errors = self.validate_prerequisites()
if not success:
for error in errors:
self.logger.error(error)
return False
# Get files to install
files_to_install = self.get_files_to_install()
if not files_to_install:
self.logger.warning("No MCP documentation files found to install")
return False
# Copy documentation files
success_count = 0
successfully_copied_files = []
for source, target in files_to_install:
self.logger.debug(f"Copying {source.name} to {target}")
if self.file_manager.copy_file(source, target):
success_count += 1
successfully_copied_files.append(source.name)
self.logger.debug(f"Successfully copied {source.name}")
else:
self.logger.error(f"Failed to copy {source.name}")
if success_count != len(files_to_install):
self.logger.error(
f"Only {success_count}/{len(files_to_install)} documentation files copied successfully"
)
return False
# Update component_files to only include successfully copied files
self.component_files = successfully_copied_files
self.logger.success(
f"MCP documentation installed successfully ({success_count} files for {len(valid_servers)} servers)"
)
return self._post_install()
def _post_install(self) -> bool:
"""Post-installation tasks"""
try:
# Update metadata
metadata_mods = {
"components": {
"mcp_docs": {
"version": __version__,
"installed": True,
"files_count": len(self.component_files),
"servers_documented": self.selected_servers,
}
}
}
self.settings_manager.update_metadata(metadata_mods)
self.logger.info("Updated metadata with MCP docs component registration")
# Update CLAUDE.md with MCP documentation imports
try:
manager = CLAUDEMdService(self.install_dir)
manager.add_imports(self.component_files, category="MCP Documentation")
self.logger.info("Updated CLAUDE.md with MCP documentation imports")
except Exception as e:
self.logger.warning(
f"Failed to update CLAUDE.md with MCP documentation imports: {e}"
)
# Don't fail the whole installation for this
return True
except Exception as e:
self.logger.error(f"Failed to update metadata: {e}")
return False
def uninstall(self) -> bool:
"""Uninstall MCP documentation component"""
try:
self.logger.info("Uninstalling MCP documentation component...")
# Remove all MCP documentation files
removed_count = 0
source_dir = self._get_source_dir()
if source_dir and source_dir.exists():
# Remove all possible MCP doc files
for doc_file in self.server_docs_map.values():
file_path = self.install_component_subdir / doc_file
if self.file_manager.remove_file(file_path):
removed_count += 1
self.logger.debug(f"Removed {doc_file}")
# Remove mcp directory if empty
try:
if self.install_component_subdir.exists():
remaining_files = list(self.install_component_subdir.iterdir())
if not remaining_files:
self.install_component_subdir.rmdir()
self.logger.debug("Removed empty mcp directory")
except Exception as e:
self.logger.warning(f"Could not remove mcp directory: {e}")
# Update settings.json
try:
if self.settings_manager.is_component_installed("mcp_docs"):
self.settings_manager.remove_component_registration("mcp_docs")
self.logger.info("Removed MCP docs component from settings.json")
except Exception as e:
self.logger.warning(f"Could not update settings.json: {e}")
self.logger.success(
f"MCP documentation uninstalled ({removed_count} files removed)"
)
return True
except Exception as e:
self.logger.exception(
f"Unexpected error during MCP docs uninstallation: {e}"
)
return False
def get_dependencies(self) -> List[str]:
"""Get dependencies"""
return ["core"]
def _get_source_dir(self) -> Optional[Path]:
"""Get source directory for MCP documentation files"""
# Assume we're in superclaude/setup/components/mcp_docs.py
# and MCP docs are in superclaude/superclaude/MCP/
project_root = Path(__file__).parent.parent.parent
mcp_dir = project_root / "superclaude" / "mcp"
# Return None if directory doesn't exist to prevent warning
if not mcp_dir.exists():
return None
return mcp_dir
def get_size_estimate(self) -> int:
"""Get estimated installation size"""
source_dir = self._get_source_dir()
total_size = 0
if source_dir and source_dir.exists() and self.selected_servers:
for server_name in self.selected_servers:
if server_name in self.server_docs_map:
doc_file = self.server_docs_map[server_name]
file_path = source_dir / doc_file
if file_path.exists():
total_size += file_path.stat().st_size
# Minimum size estimate
total_size = max(total_size, 10240) # At least 10KB
return total_size

View File

@@ -26,6 +26,13 @@ class ModesComponent(Component):
"category": "modes",
}
def is_reinstallable(self) -> bool:
"""
Modes should always be synced to latest version.
SuperClaude mode files always overwrite existing files.
"""
return True
def _install(self, config: Dict[str, Any]) -> bool:
"""Install modes component"""
self.logger.info("Installing SuperClaude behavioral modes...")
@@ -77,6 +84,7 @@ class ModesComponent(Component):
"version": __version__,
"installed": True,
"files_count": len(self.component_files),
"files": list(self.component_files), # Track for sync/deletion
}
}
}
@@ -140,7 +148,68 @@ class ModesComponent(Component):
def get_dependencies(self) -> List[str]:
"""Get dependencies"""
return ["core"]
return ["framework_docs"]
def update(self, config: Dict[str, Any]) -> bool:
"""
Sync modes component (overwrite + delete obsolete files).
No backup needed - SuperClaude source files are always authoritative.
"""
try:
self.logger.info("Syncing SuperClaude modes component...")
# Get previously installed files from metadata
metadata = self.settings_manager.load_metadata()
previous_files = set(
metadata.get("components", {}).get("modes", {}).get("files", [])
)
# Get current files from source
current_files = set(self.component_files)
# Files to delete (were installed before, but no longer in source)
files_to_delete = previous_files - current_files
# Delete obsolete files
deleted_count = 0
for filename in files_to_delete:
file_path = self.install_dir / filename
if file_path.exists():
try:
file_path.unlink()
deleted_count += 1
self.logger.info(f"Deleted obsolete mode: {filename}")
except Exception as e:
self.logger.warning(f"Could not delete {filename}: {e}")
# Install/overwrite current files (no backup)
success = self.install(config)
if success:
# Update metadata with current file list
metadata_mods = {
"components": {
"modes": {
"version": __version__,
"installed": True,
"files_count": len(current_files),
"files": list(current_files), # Track installed files
}
}
}
self.settings_manager.update_metadata(metadata_mods)
self.logger.success(
f"Modes synced: {len(current_files)} files, {deleted_count} obsolete files removed"
)
else:
self.logger.error("Modes sync failed")
return success
except Exception as e:
self.logger.exception(f"Unexpected error during modes sync: {e}")
return False
def _get_source_dir(self) -> Optional[Path]:
"""Get source directory for mode files"""