SuperClaude/setup/utils/updater.py
kazuki nakai 050d5ea2ab
refactor: PEP8 compliance - directory rename and code formatting (#425)
* fix(orchestration): add WebFetch auto-trigger for infrastructure configuration

Problem: Infrastructure configuration changes (e.g., Traefik port settings)
were being made based on assumptions without consulting official documentation,
violating the 'Evidence > assumptions' principle in PRINCIPLES.md.

Solution:
- Added Infrastructure Configuration Validation section to MODE_Orchestration.md
- Auto-triggers WebFetch for infrastructure tools (Traefik, nginx, Docker, etc.)
- Enforces MODE_DeepResearch activation for investigation
- BLOCKS assumption-based configuration changes

Testing: Verified WebFetch successfully retrieves Traefik official docs (port 80 default)

This prevents production outages from infrastructure misconfiguration by ensuring
all technical recommendations are backed by official documentation.

* feat: Add PM Agent (Project Manager Agent) for seamless orchestration

Introduces PM Agent as the default orchestration layer that coordinates
all sub-agents and manages workflows automatically.

Key Features:
- Default orchestration: All user interactions handled by PM Agent
- Auto-delegation: Intelligent sub-agent selection based on task analysis
- Docker Gateway integration: Zero-token baseline with dynamic MCP loading
- Self-improvement loop: Automatic documentation of patterns and mistakes
- Optional override: Users can specify sub-agents explicitly if desired

Architecture:
- Agent spec: SuperClaude/Agents/pm-agent.md
- Command: SuperClaude/Commands/pm.md
- Updated docs: README.md (15→16 agents), agents.md (new Orchestration category)

User Experience:
- Default: PM Agent handles everything (seamless, no manual routing)
- Optional: Explicit --agent flag for direct sub-agent access
- Both modes available simultaneously (no user downside)

Implementation Status:
-  Specification complete
-  Documentation complete
-  Prototype implementation needed
-  Docker Gateway integration needed
-  Testing and validation needed

Refs: kazukinakai/docker-mcp-gateway (IRIS MCP Gateway integration)

* feat: Add Agent Orchestration rules for PM Agent default activation

Implements PM Agent as the default orchestration layer in RULES.md.

Key Changes:
- New 'Agent Orchestration' section (CRITICAL priority)
- PM Agent receives ALL user requests by default
- Manual override with @agent-[name] bypasses PM Agent
- Agent Selection Priority clearly defined:
  1. Manual override → Direct routing
  2. Default → PM Agent → Auto-delegation
  3. Delegation based on keywords, file types, complexity, context

User Experience:
- Default: PM Agent handles everything (seamless)
- Override: @agent-[name] for direct specialist access
- Transparent: PM Agent reports delegation decisions

This establishes PM Agent as the orchestration layer while
respecting existing auto-activation patterns and manual overrides.

Next Steps:
- Local testing in agiletec project
- Iteration based on actual behavior
- Documentation updates as needed

* refactor(pm-agent): redesign as self-improvement meta-layer

Problem Resolution:
PM Agent's initial design competed with existing auto-activation for task routing,
creating confusion about orchestration responsibilities and adding unnecessary complexity.

Design Change:
Redefined PM Agent as a meta-layer agent that operates AFTER specialist agents
complete tasks, focusing on:
- Post-implementation documentation and pattern recording
- Immediate mistake analysis with prevention checklists
- Monthly documentation maintenance and noise reduction
- Pattern extraction and knowledge synthesis

Two-Layer Orchestration System:
1. Task Execution Layer: Existing auto-activation handles task routing (unchanged)
2. Self-Improvement Layer: PM Agent meta-layer handles documentation (new)

Files Modified:
- SuperClaude/Agents/pm-agent.md: Complete rewrite with meta-layer design
  - Category: orchestration → meta
  - Triggers: All user interactions → Post-implementation, mistakes, monthly
  - Behavioral Mindset: Continuous learning system
  - Self-Improvement Workflow: BEFORE/DURING/AFTER/MISTAKE RECOVERY/MAINTENANCE

- SuperClaude/Core/RULES.md: Agent Orchestration section updated
  - Split into Task Execution Layer + Self-Improvement Layer
  - Added orchestration flow diagram
  - Clarified PM Agent activates AFTER task completion

- README.md: Updated PM Agent description
  - "orchestrates all interactions" → "ensures continuous learning"

- Docs/User-Guide/agents.md: PM Agent section rewritten
  - Section: Orchestration Agent → Meta-Layer Agent
  - Expertise: Project orchestration → Self-improvement workflow executor
  - Examples: Task coordination → Post-implementation documentation

- PR_DOCUMENTATION.md: Comprehensive PR documentation added
  - Summary, motivation, changes, testing, breaking changes
  - Two-layer orchestration system diagram
  - Verification checklist

Integration Validated:
Tested with agiletec project's self-improvement-workflow.md:
 PM Agent aligns with existing BEFORE/DURING/AFTER/MISTAKE RECOVERY phases
 Complements (not competes with) existing workflow
 agiletec workflow defines WHAT, PM Agent defines WHO executes it

Breaking Changes: None
- Existing auto-activation continues unchanged
- Specialist agents unaffected
- User workflows remain the same
- New capability: Automatic documentation and knowledge maintenance

Value Proposition:
Transforms SuperClaude into a continuously learning system that accumulates
knowledge, prevents recurring mistakes, and maintains fresh documentation
without manual intervention.

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

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

* docs: add Claude Code conversation history management research

Research covering .jsonl file structure, performance impact, and retention policies.

Content:
- Claude Code .jsonl file format and message types
- Performance issues from GitHub (memory leaks, conversation compaction)
- Retention policies (consumer vs enterprise)
- Rotation recommendations based on actual data
- File history snapshot tracking mechanics

Source: Moved from agiletec project (research applicable to all Claude Code projects)

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

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

* feat: add Development documentation structure

Phase 1: Documentation Structure complete

- Add Docs/Development/ directory for development documentation
- Add ARCHITECTURE.md - System architecture with PM Agent meta-layer
- Add ROADMAP.md - 5-phase development plan with checkboxes
- Add TASKS.md - Daily task tracking with progress indicators
- Add PROJECT_STATUS.md - Current status dashboard and metrics
- Add pm-agent-integration.md - Implementation guide for PM Agent mode

This establishes comprehensive documentation foundation for:
- System architecture understanding
- Development planning and tracking
- Implementation guidance
- Progress visibility

Related: #pm-agent-mode #documentation #phase-1

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

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

* feat: PM Agent session lifecycle and PDCA implementation

Phase 2: PM Agent Mode Integration (Design Phase)

Commands/pm.md updates:
- Add "Always-Active Foundation Layer" concept
- Add Session Lifecycle (Session Start/During Work/Session End)
- Add PDCA Cycle (Plan/Do/Check/Act) automation
- Add Serena MCP Memory Integration (list/read/write_memory)
- Document auto-activation triggers

Agents/pm-agent.md updates:
- Add Session Start Protocol (MANDATORY auto-activation)
- Add During Work PDCA Cycle with example workflows
- Add Session End Protocol with state preservation
- Add PDCA Self-Evaluation Pattern
- Add Documentation Strategy (temp → patterns/mistakes)
- Add Memory Operations Reference

Key Features:
- Session start auto-activation for context restoration
- 30-minute checkpoint saves during work
- Self-evaluation with think_about_* operations
- Systematic documentation lifecycle
- Knowledge evolution to CLAUDE.md

Implementation Status:
-  Design complete (Commands/pm.md, Agents/pm-agent.md)
-  Implementation pending (Core components)
-  Serena MCP integration pending

Salvaged from mistaken development in ~/.claude directory

Related: #pm-agent-mode #session-lifecycle #pdca-cycle #phase-2

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

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

* fix: disable Serena MCP auto-browser launch

Disable web dashboard and GUI log window auto-launch in Serena MCP server
to prevent intrusive browser popups on startup. Users can still manually
access the dashboard at http://localhost:24282/dashboard/ if needed.

Changes:
- Add CLI flags to Serena run command:
  - --enable-web-dashboard false
  - --enable-gui-log-window false
- Ensures Git-tracked configuration (no reliance on ~/.serena/serena_config.yml)
- Aligns with AIRIS MCP Gateway integration approach

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

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

* refactor: rename directories to lowercase for PEP8 compliance

- Rename superclaude/Agents -> superclaude/agents
- Rename superclaude/Commands -> superclaude/commands
- Rename superclaude/Core -> superclaude/core
- Rename superclaude/Examples -> superclaude/examples
- Rename superclaude/MCP -> superclaude/mcp
- Rename superclaude/Modes -> superclaude/modes

This change follows Python PEP8 naming conventions for package directories.

* style: fix PEP8 violations and update package name to lowercase

Changes:
- Format all Python files with black (43 files reformatted)
- Update package name from 'SuperClaude' to 'superclaude' in pyproject.toml
- Fix import statements to use lowercase package name
- Add missing imports (timedelta, __version__)
- Remove old SuperClaude.egg-info directory

PEP8 violations reduced from 2672 to 701 (mostly E501 line length due to black's 88 char vs flake8's 79 char limit).

* docs: add PM Agent development documentation

Add comprehensive PM Agent development documentation:
- PM Agent ideal workflow (7-phase autonomous cycle)
- Project structure understanding (Git vs installed environment)
- Installation flow understanding (CommandsComponent behavior)
- Task management system (current-tasks.md)

Purpose: Eliminate repeated explanations and enable autonomous PDCA cycles

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

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

* feat(pm-agent): add self-correcting execution and warning investigation culture

## Changes

### superclaude/commands/pm.md
- Add "Self-Correcting Execution" section with root cause analysis protocol
- Add "Warning/Error Investigation Culture" section enforcing zero-tolerance for dismissal
- Define error detection protocol: STOP → Investigate → Hypothesis → Different Solution → Execute
- Document anti-patterns (retry without understanding) and correct patterns (research-first)

### docs/Development/hypothesis-pm-autonomous-enhancement-2025-10-14.md
- Add PDCA workflow hypothesis document for PM Agent autonomous enhancement

## Rationale

PM Agent must never retry failed operations without understanding root causes.
All warnings and errors require investigation via context7/WebFetch/documentation
to ensure production-quality code and prevent technical debt accumulation.

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

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

* feat(installer): add airis-mcp-gateway MCP server option

## Changes

- Add airis-mcp-gateway to MCP server options in installer
- Configuration: GitHub-based installation via uvx
- Repository: https://github.com/oraios/airis-mcp-gateway
- Purpose: Dynamic MCP Gateway for zero-token baseline and on-demand tool loading

## Implementation

Added to setup/components/mcp.py self.mcp_servers dictionary with:
- install_method: github
- install_command: uvx test installation
- run_command: uvx runtime execution
- required: False (optional server)

🤖 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>
2025-10-14 08:47:09 +05:30

330 lines
9.6 KiB
Python

"""
Auto-update checker for SuperClaude Framework
Checks PyPI for newer versions and offers automatic updates
"""
import os
import sys
import json
import time
import subprocess
from pathlib import Path
from typing import Optional, Tuple
from packaging import version
import urllib.request
import urllib.error
from datetime import datetime, timedelta
from .ui import display_info, display_warning, display_success, Colors
from .logger import get_logger
from .paths import get_home_directory
class UpdateChecker:
"""Handles automatic update checking for SuperClaude"""
PYPI_URL = "https://pypi.org/pypi/superclaude/json"
CACHE_FILE = get_home_directory() / ".claude" / ".update_check"
CHECK_INTERVAL = 86400 # 24 hours in seconds
TIMEOUT = 2 # seconds
def __init__(self, current_version: str):
"""
Initialize update checker
Args:
current_version: Current installed version
"""
self.current_version = current_version
self.logger = get_logger()
def should_check_update(self, force: bool = False) -> bool:
"""
Determine if we should check for updates based on last check time
Args:
force: Force check regardless of last check time
Returns:
True if update check should be performed
"""
if force:
return True
if not self.CACHE_FILE.exists():
return True
try:
with open(self.CACHE_FILE, "r") as f:
data = json.load(f)
last_check = data.get("last_check", 0)
# Check if 24 hours have passed
if time.time() - last_check > self.CHECK_INTERVAL:
return True
except (json.JSONDecodeError, KeyError):
return True
return False
def save_check_timestamp(self):
"""Save the current timestamp as last check time"""
self.CACHE_FILE.parent.mkdir(parents=True, exist_ok=True)
data = {}
if self.CACHE_FILE.exists():
try:
with open(self.CACHE_FILE, "r") as f:
data = json.load(f)
except:
pass
data["last_check"] = time.time()
with open(self.CACHE_FILE, "w") as f:
json.dump(data, f)
def get_latest_version(self) -> Optional[str]:
"""
Query PyPI for the latest version of SuperClaude
Returns:
Latest version string or None if check fails
"""
try:
# Create request with timeout
req = urllib.request.Request(
self.PYPI_URL, headers={"User-Agent": "superclaude-Updater"}
)
# Set timeout for the request
with urllib.request.urlopen(req, timeout=self.TIMEOUT) as response:
data = json.loads(response.read().decode())
latest = data.get("info", {}).get("version")
if self.logger:
self.logger.debug(f"Latest PyPI version: {latest}")
return latest
except (
urllib.error.URLError,
urllib.error.HTTPError,
json.JSONDecodeError,
) as e:
if self.logger:
self.logger.debug(f"Failed to check PyPI: {e}")
return None
except Exception as e:
if self.logger:
self.logger.debug(f"Unexpected error checking updates: {e}")
return None
def compare_versions(self, latest: str) -> bool:
"""
Compare current version with latest version
Args:
latest: Latest version string
Returns:
True if update is available
"""
try:
return version.parse(latest) > version.parse(self.current_version)
except Exception:
return False
def detect_installation_method(self) -> str:
"""
Detect how SuperClaude was installed (pip, pipx, etc.)
Returns:
Installation method string
"""
# Check pipx first
try:
result = subprocess.run(
["pipx", "list"], capture_output=True, text=True, timeout=2
)
if "superclaude" in result.stdout or "superclaude" in result.stdout:
return "pipx"
except:
pass
# Check if pip installation exists
try:
result = subprocess.run(
[sys.executable, "-m", "pip", "show", "superclaude"],
capture_output=True,
text=True,
timeout=2,
)
if result.returncode == 0:
# Check if it's a user installation
if "--user" in result.stdout or get_home_directory() in Path(
result.stdout
):
return "pip-user"
return "pip"
except:
pass
return "unknown"
def get_update_command(self) -> str:
"""
Get the appropriate update command based on installation method
Returns:
Update command string
"""
method = self.detect_installation_method()
commands = {
"pipx": "pipx upgrade SuperClaude",
"pip-user": "pip install --upgrade --user SuperClaude",
"pip": "pip install --upgrade SuperClaude",
"unknown": "pip install --upgrade SuperClaude",
}
return commands.get(method, commands["unknown"])
def show_update_banner(self, latest: str, auto_update: bool = False) -> bool:
"""
Display update available banner
Args:
latest: Latest version available
auto_update: Whether to auto-update without prompting
Returns:
True if user wants to update
"""
update_cmd = self.get_update_command()
# Display banner
print(
f"\n{Colors.CYAN}+================================================+{Colors.RESET}"
)
print(
f"{Colors.CYAN}{Colors.YELLOW} 🚀 Update Available: {self.current_version}{latest} {Colors.CYAN}{Colors.RESET}"
)
print(
f"{Colors.CYAN}{Colors.GREEN} Run: {update_cmd:<30} {Colors.CYAN}{Colors.RESET}"
)
print(
f"{Colors.CYAN}+================================================+{Colors.RESET}\n"
)
if auto_update:
return True
# Check if running in non-interactive mode
if not sys.stdin.isatty():
return False
# Prompt user
try:
response = (
input(
f"{Colors.YELLOW}Would you like to update now? (y/N): {Colors.RESET}"
)
.strip()
.lower()
)
return response in ["y", "yes"]
except (EOFError, KeyboardInterrupt):
return False
def perform_update(self) -> bool:
"""
Execute the update command
Returns:
True if update succeeded
"""
update_cmd = self.get_update_command()
print(f"{Colors.CYAN}🔄 Updating superclaude...{Colors.RESET}")
try:
result = subprocess.run(update_cmd.split(), capture_output=False, text=True)
if result.returncode == 0:
display_success("Update completed successfully!")
print(
f"{Colors.YELLOW}Please restart SuperClaude to use the new version.{Colors.RESET}"
)
return True
else:
display_warning("Update failed. Please run manually:")
print(f" {update_cmd}")
return False
except Exception as e:
display_warning(f"Could not auto-update: {e}")
print(f"Please run manually: {update_cmd}")
return False
def check_and_notify(self, force: bool = False, auto_update: bool = False) -> bool:
"""
Main method to check for updates and notify user
Args:
force: Force check regardless of last check time
auto_update: Automatically update if available
Returns:
True if update was performed
"""
# Check if we should skip based on environment variable
if os.getenv("SUPERCLAUDE_NO_UPDATE_CHECK", "").lower() in ["true", "1", "yes"]:
return False
# Check if auto-update is enabled via environment
if os.getenv("SUPERCLAUDE_AUTO_UPDATE", "").lower() in ["true", "1", "yes"]:
auto_update = True
# Check if enough time has passed
if not self.should_check_update(force):
return False
# Get latest version
latest = self.get_latest_version()
if not latest:
return False
# Save timestamp
self.save_check_timestamp()
# Compare versions
if not self.compare_versions(latest):
return False
# Show banner and potentially update
if self.show_update_banner(latest, auto_update):
return self.perform_update()
return False
def check_for_updates(current_version: str = None, **kwargs) -> bool:
"""
Convenience function to check for updates
Args:
current_version: Current installed version (defaults to reading from setup)
**kwargs: Additional arguments passed to check_and_notify
Returns:
True if update was performed
"""
if current_version is None:
from setup import __version__
current_version = __version__
checker = UpdateChecker(current_version)
return checker.check_and_notify(**kwargs)