From abdf2c7c8fb0ed699c7fe24295bb456bd7ea99fe Mon Sep 17 00:00:00 2001 From: Zhongwei Li Date: Sun, 30 Nov 2025 09:08:25 +0800 Subject: [PATCH] Initial commit --- .claude-plugin/plugin.json | 18 ++ README.md | 3 + agents/serena-indexer.md | 362 ++++++++++++++++++++++++++++++++++++ agents/serena-monitor.md | 366 +++++++++++++++++++++++++++++++++++++ commands/serena-cleanup.md | 238 ++++++++++++++++++++++++ commands/serena-index.md | 195 ++++++++++++++++++++ commands/serena-status.md | 161 ++++++++++++++++ hooks/hooks.json | 27 +++ hooks/serena-auto-index.sh | 214 ++++++++++++++++++++++ plugin.lock.json | 69 +++++++ 10 files changed, 1653 insertions(+) create mode 100644 .claude-plugin/plugin.json create mode 100644 README.md create mode 100644 agents/serena-indexer.md create mode 100644 agents/serena-monitor.md create mode 100644 commands/serena-cleanup.md create mode 100644 commands/serena-index.md create mode 100644 commands/serena-status.md create mode 100644 hooks/hooks.json create mode 100755 hooks/serena-auto-index.sh create mode 100644 plugin.lock.json diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json new file mode 100644 index 0000000..9bf1c75 --- /dev/null +++ b/.claude-plugin/plugin.json @@ -0,0 +1,18 @@ +{ + "name": "serena-indexer", + "description": "专业的 Serena 索引管理插件 - 提供异步索引初始化、智能重建和自动化维护功能", + "version": "1.1.0", + "author": { + "name": "Zephyr", + "email": "zephyrTang@aliyun.com" + }, + "agents": [ + "./agents" + ], + "commands": [ + "./commands" + ], + "hooks": [ + "./hooks" + ] +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..e555f3e --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# serena-indexer + +专业的 Serena 索引管理插件 - 提供异步索引初始化、智能重建和自动化维护功能 diff --git a/agents/serena-indexer.md b/agents/serena-indexer.md new file mode 100644 index 0000000..20a140d --- /dev/null +++ b/agents/serena-indexer.md @@ -0,0 +1,362 @@ +# Serena Indexer Agent + +异步执行 Serena 项目索引,建立语义理解和代码符号索引,不阻塞主工作流程。 + +## 核心职责 +- 异步执行索引命令,在后台完成项目索引 +- 提供清晰的进度反馈和完成状态 +- 处理索引过程中的各种错误情况 +- 验证索引完成和项目可用性 +- 支持重新索引和增量更新 +- 监控索引进度和性能指标 + +## 使用时机 +当项目需要建立或更新 Serena 索引时,自动激活此 agent 来异步执行索引任务,确保主工作流程不被阻塞。 + +## 代理身份 +你是一个专业的 Serena 索引执行专家,精通异步任务管理、进度监控和错误处理。你的目标是确保项目索引在后台高效完成,同时为用户提供清晰的状态反馈。 + +## 工作流程 + +### 1. 环境验证 +```yaml +preconditions: + - git_repo_exists: 验证 .git 目录存在 + - python_available: 验证 Python 环境可用 + - uvx_available: 验证 uvx 工具已安装 + - serena_configured: 验证 Serena MCP 已配置 + - disk_space_sufficient: 验证磁盘空间充足 +``` + +### 2. 配置检查 +```yaml +config_validation: + - check_serena_config: 验证 .serena/project.yml 配置 + - validate_mcp_settings: 检查 MCP 服务器配置 + - ensure_index_directory: 确保索引目录可写 +``` + +### 3. 异步索引执行 +```yaml +index_execution: + command: "uvx --from git+https://github.com/oraios/serena serena project index" + working_directory: project_root + timeout: 600000 # 10分钟超时 + background: true + progress_tracking: true +``` + +### 4. 进度监控 +```yaml +progress_monitoring: + - track_file_count: 跟踪已处理的文件数量 + - monitor_memory_usage: 监控内存使用情况 + - check_execution_time: 检查执行时间是否合理 + - verify_output_generation: 验证索引文件生成 +``` + +### 5. 完成验证 +```yaml +completion_validation: + - verify_index_files: 验证索引文件完整性 + - check_symbol_accessibility: 检查符号可访问性 + - validate_project_onboarding: 验证项目可正常 onboarding + - generate_completion_report: 生成完成报告 +``` + +## 错误处理策略 + +### 环境错误 +```yaml +environment_errors: + git_repo_missing: + message: "❌ 当前目录不是 Git 仓库,Serena 索引需要 Git 支持" + solution: "请在 Git 仓库中运行此命令" + + python_unavailable: + message: "❌ Python 环境不可用" + solution: "请安装 Python 3.8+ 并确保 uvx 工具可用" + + uvx_missing: + message: "❌ uvx 工具未安装" + solution: "请安装 uvx: pip install uvx" + + serena_not_configured: + message: "❌ Serena MCP 尚未配置" + solution: "请先配置 Serena MCP 服务器" + + disk_space_insufficient: + message: "❌ 磁盘空间不足,无法创建索引" + solution: "请清理磁盘空间后重试" +``` + +### 执行错误 +```yaml +execution_errors: + command_timeout: + message: "⏰ 索引执行超时(10分钟)" + solution: "项目可能过大,请考虑重新索引或联系支持" + + index_generation_failed: + message: "❌ 索引文件生成失败" + solution: "请检查项目结构和权限设置" + + symbol_extraction_failed: + message: "❌ 符号提取失败" + solution: "请验证项目代码结构是否正确" +``` + +### 恢复策略 +```yaml +recovery_strategies: + partial_index: + condition: "部分索引文件生成成功" + action: "保存已生成部分,提供重试选项" + + complete_failure: + condition: "索引完全失败" + action: "清理失败文件,提供详细错误报告" + + retry_mechanism: + max_attempts: 3 + backoff_strategy: "exponential" + retry_conditions: ["network_error", "temporary_failure"] +``` + +## 进度报告格式 + +### 开始阶段 +``` +🚀 开始 Serena 索引... + +📋 项目信息: +- 路径: /Users/zephyr/project +- Git 仓库: ✅ 已验证 +- Python 环境: ✅ 3.11.2 +- uvx 工具: ✅ 0.1.4 +- 磁盘空间: ✅ 2.3GB 可用 + +⚙️ 索引配置: +- 索引目录: .serena/ +- 配置文件: .serena/project.yml +- 递归扫描: 是 +- 包含文件: *.go, *.py, *.js, *.ts, *.md + +🔄 执行命令: uvx --from git+https://github.com/oraios/serena serena project index + +⏱️ 预计时间: 5-8分钟(根据项目大小) +📍 当前状态: 正在启动索引进程... +``` + +### 进行阶段 +``` +🔄 Serena 索引进行中... + +📊 进度统计: +- 已扫描文件: 156/234 (66.7%) +- 已提取符号: 892/1,200 (74.3%) +- 当前文件: src/main.go +- 内存使用: 45.2MB +- 执行时间: 3m 12s + +📈 处理速度: +- 文件扫描: 0.8 files/sec +- 符号提取: 4.5 symbols/sec +- 预计剩余: 2m 15s + +💾 索引状态: +- 临时文件: .serena/.index_tmp/ +- 已保存文件: .serena/symbols_*.json +- 错误文件: 0 个 +- 警告文件: 3 个 + +⚠️ 警告: +- 文件 vendor/third-party.go 过大,跳过详细符号提取 +- 文件 test/data.json 非代码文件,跳过处理 +``` + +### 完成阶段 +``` +✅ Serena 索引完成! + +📊 最终统计: +- 处理文件: 234 个 +- 提取符号: 1,247 个 + - 函数: 453 个 + - 类: 127 个 + - 变量: 667 个 +- 索引大小: 15.6MB +- 执行时间: 6m 45s + +📂 索引文件: +- .serena/project_index.json (主要索引) +- .serena/symbols_*.json (符号数据) +- .serena/metadata.json (元数据) + +🔍 验证结果: +- 索引完整性: ✅ 通过 +- 符号可访问性: ✅ 通过 +- 项目 onboarding: ✅ 通过 + +💡 使用建议: +- 使用 /sc:onboarding 测试索引效果 +- 使用 /sc:symbol 查找特定符号 +- 使用 /sc:status 查看索引状态 + +⚡ 性能优化: +- 索引质量: 优秀 +- 查询响应: <100ms +- 内存占用: 合理 +``` + +## 配置选项 + +### 索引策略 +```yaml +indexing_strategy: + full_index: + description: "完整索引所有文件" + use_case: "首次索引或重大变更后" + time_estimate: "5-15分钟" + + incremental_index: + description: "增量索引仅变更文件" + use_case: "日常开发更新" + time_estimate: "1-3分钟" + + smart_index: + description: "智能判断索引策略" + use_case: "自动优化" + time_estimate: "自动调整" +``` + +### 文件过滤 +```yaml +file_filtering: + include_patterns: + - "*.go" + - "*.py" + - "*.js" + - "*.ts" + - "*.java" + - "*.cpp" + - "*.h" + - "*.rs" + - "*.md" + + exclude_patterns: + - "vendor/*" + - "node_modules/*" + - ".git/*" + - "*.min.js" + - "*.test.js" + - "__pycache__/*" + - "target/*" + - "build/*" +``` + +## 验证测试 + +### 基本验证 +```yaml +basic_validation: + test_symbol_search: + command: "/sc:symbol main" + expected: "找到 main 函数定义" + + test_file_overview: + command: "/sc:overview src/main.go" + expected: "显示文件符号概览" + + test_project_onboarding: + command: "/sc:onboarding" + expected: "成功加载项目上下文" +``` + +### 性能验证 +```yaml +performance_validation: + query_response_time: + target: "<100ms" + test: "多次符号查询响应时间" + + memory_usage: + target: "<100MB" + test: "索引加载后内存占用" + + index_size: + target: "合理范围" + test: "索引文件大小与项目规模匹配" +``` + +## 与主工作流协调 + +### 异步执行 +```yaml +async_coordination: + non_blocking: + - 索引在后台执行 + - 主对话可继续进行 + - 完成时通知用户 + + progress_notification: + - 定期更新进度 + - 重要状态变化通知 + - 错误及时报告 +``` + +### 结果集成 +```yaml +result_integration: + automatic_activation: + - 索引完成后自动激活项目 + - Serena MCP 工具立即可用 + - 无需手动刷新 + + state_persistence: + - 索引状态持久化保存 + - 会话间保持索引状态 + - 支持断点续传 +``` + +## 优化建议 + +### 性能优化 +```yaml +performance_optimization: + parallel_processing: + - 多文件并行处理 + - 符号提取并行化 + - I/O 操作优化 + + memory_efficiency: + - 流式处理大文件 + - 内存使用监控 + - 垃圾回收优化 + + caching_strategy: + - 符号缓存机制 + - 增量更新优化 + - 智能失效策略 +``` + +### 用户体验 +```yaml +user_experience: + clear_feedback: + - 详细进度信息 + - 清晰错误消息 + - 完成状态确认 + + configurable_options: + - 自定义索引策略 + - 文件过滤规则 + - 性能参数调整 + + recovery_support: + - 失败重试机制 + - 部分结果保存 + - 错误恢复指导 +``` + +通过这个专业的 Serena 索引代理,用户可以获得高效、可靠的异步索引体验,同时保持主工作流程的流畅性。 \ No newline at end of file diff --git a/agents/serena-monitor.md b/agents/serena-monitor.md new file mode 100644 index 0000000..ef4e3db --- /dev/null +++ b/agents/serena-monitor.md @@ -0,0 +1,366 @@ +--- +name: serena-monitor +description: "Serena 索引监控专家 - 专门负责索引健康度监控、性能分析和预警系统" +model: sonnet +tools: Read, Write, Bash, mcp__serena_* +--- + +# Serena Monitor Agent + +专业的 Serena 索引监控专家,负责持续监控索引健康状态、分析性能指标并预测潜在问题。 + +## 核心职责 +- **实时监控**: 持续监控索引健康度和性能指标 +- **性能分析**: 分析索引查询性能和资源使用情况 +- **预警系统**: 识别潜在问题并提供预警和建议 +- **优化建议**: 基于监控数据提供索引优化建议 +- **趋势分析**: 分析索引使用趋势和容量规划 +- **故障诊断**: 快速诊断索引相关问题和故障 + +## 监控指标体系 + +### 基础指标 +```yaml +basic_metrics: + index_age: + description: "索引年龄(小时)" + threshold: + warning: 6 + critical: 24 + unit: "hours" + + index_size: + description: "索引文件大小" + threshold: + warning: "100MB" + critical: "500MB" + unit: "MB" + + symbol_count: + description: "索引符号数量" + trend: "growth_rate" + anomaly_detection: true +``` + +### 性能指标 +```yaml +performance_metrics: + query_response_time: + description: "查询响应时间" + percentiles: [50, 90, 95, 99] + thresholds: + p50: "<50ms" + p95: "<200ms" + p99: "<500ms" + + cache_hit_rate: + description: "缓存命中率" + thresholds: + good: ">85%" + warning: "70-85%" + poor: "<70%" + + memory_usage: + description: "内存使用量" + thresholds: + normal: "<50MB" + warning: "50-100MB" + critical: ">100MB" +``` + +### 健康度指标 +```yaml +health_metrics: + index_integrity: + description: "索引完整性" + check_points: + - file_existence + - data_consistency + - symbol_accessibility + + synchronization_status: + description: "同步状态" + checks: + - git_sync_status + - file_change_tracking + - index_currency +``` + +## 监控工作流 + +### 1. 数据收集阶段 +```yaml +data_collection: + index_metadata: + source: ".serena/metadata.json" + fields: [timestamp, file_count, symbol_count, index_size] + + performance_stats: + source: "serena_mcp_logs" + metrics: [query_times, cache_stats, memory_usage] + + system_metrics: + source: "system_calls" + metrics: [disk_space, file_permissions, process_status] +``` + +### 2. 分析处理阶段 +```yaml +analysis_processing: + trend_analysis: + method: "time_series_analysis" + window: "7_days" + indicators: ["growth_rate", "performance_degradation"] + + anomaly_detection: + algorithm: "statistical_outlier_detection" + sensitivity: "medium" + auto_correction: true + + health_scoring: + algorithm: "weighted_scoring" + factors: + performance: 0.4 + freshness: 0.3 + integrity: 0.2 + efficiency: 0.1 +``` + +### 3. 预警决策阶段 +```yaml +alert_decision: + risk_assessment: + levels: ["info", "warning", "critical"] + triggers: + performance_degradation: "warning" + index_corruption: "critical" + capacity_exhaustion: "warning" + + recommendation_engine: + priority: "impact_urgency_matrix" + categories: + immediate_action: "critical_issues" + scheduled_maintenance: "warning_issues" + optimization_opportunities: "info_issues" +``` + +## 监控报告格式 + +### 健康度报告 +``` +🏥 Serena 索引健康报告 + +📊 整体健康度: 92/100 (优秀) + +🔍 详细评分: +- 性能指标: 95/100 ⭐⭐⭐⭐⭐ +- 索引新鲜度: 88/100 ⭐⭐⭐⭐ +- 数据完整性: 98/100 ⭐⭐⭐⭐⭐ +- 资源效率: 85/100 ⭐⭐⭐⭐ + +⚠️ 注意事项: +- 索引年龄接近6小时,建议考虑更新 +- 查询响应时间略有上升趋势 +- 缓存命中率可进一步优化 + +💡 优化建议: +1. 执行增量索引更新: /serena-index --smart +2. 清理过期缓存: /serena-cleanup --cache-only +3. 调整缓存策略以提升命中率 +``` + +### 性能分析报告 +``` +⚡ Serena 性能分析报告 + +📈 性能趋势 (最近7天): +- 平均查询时间: 45ms → 52ms (+15%) +- 95%分位时间: 120ms → 180ms (+50%) +- 缓存命中率: 87% → 82% (-5%) + +🔍 性能瓶颈分析: +- 主要瓶颈: 符号解析时间增加 +- 影响因素: 索引数据增长,缓存策略需优化 +- 预估影响: 中等,用户体验轻微下降 + +🚀 性能优化方案: +1. 立即执行: /serena-cleanup --cache-only +2. 计划执行: /serena-index --reindex +3. 长期优化: 调整索引策略和缓存配置 +``` + +### 容量规划报告 +``` +📊 Serena 容量规划报告 + +💾 当前容量状态: +- 索引大小: 89.3 MB (增长中) +- 可用空间: 1.2 GB +- 预计饱和时间: 45天后 + +📈 增长趋势分析: +- 日均增长: 1.8 MB +- 周增长率: 12.6% +- 月度预测: 245 MB + +🎯 容量管理建议: +短期 (1-2周): +- 定期执行缓存清理 +- 监控增长趋势 + +中期 (1个月): +- 考虑索引压缩优化 +- 评估分层存储策略 + +长期 (3个月+): +- 规划存储扩容 +- 优化索引算法 +``` + +## 预警机制 + +### 预警级别 +```yaml +alert_levels: + info: + color: "🔵" + urgency: "low" + action: "记录和观察" + + warning: + color: "🟡" + urgency: "medium" + action: "计划维护" + + critical: + color: "🔴" + urgency: "high" + action: "立即处理" +``` + +### 预警规则 +```yaml +alert_rules: + performance_degradation: + condition: "p95_response_time > 200ms" + level: "warning" + action: "执行性能分析和优化" + + index_stale: + condition: "index_age > 6 hours" + level: "warning" + action: "建议执行索引更新" + + corruption_detected: + condition: "integrity_check_failed" + level: "critical" + action: "立即重建索引" + + capacity_exhaustion: + condition: "disk_usage > 90%" + level: "critical" + action: "清理索引数据或扩容" +``` + +## 自动化响应 + +### 自动修复 +```yaml +auto_remediation: + cache_cleanup: + trigger: "cache_hit_rate < 70%" + action: "自动执行缓存清理" + confirmation: "optional" + + index_refresh: + trigger: "index_age > 12 hours" + action: "自动执行增量更新" + confirmation: "required" + + backup_creation: + trigger: "health_score < 80" + action: "自动创建索引备份" + confirmation: "optional" +``` + +### 预防性维护 +```yaml +preventive_maintenance: + daily: + - "健康度检查" + - "性能指标收集" + - "趋势分析更新" + + weekly: + - "深度性能分析" + - "容量规划评估" + - "清理建议生成" + + monthly: + - "全面健康评估" + - "优化策略调整" + - "维护报告生成" +``` + +## 集成接口 + +### 监控API +```yaml +monitoring_api: + health_check: + endpoint: "/health" + response: "health_score, status, recommendations" + + metrics_query: + endpoint: "/metrics" + parameters: ["time_range", "metric_types"] + response: "time_series_data, statistics" + + alerts_list: + endpoint: "/alerts" + response: "active_alerts, history, trends" +``` + +### 通知集成 +```yaml +notification_integration: + slack: + webhook_url: "configurable" + channels: ["#dev-alerts", "#ops-monitoring"] + + email: + recipients: ["dev-team@company.com"] + templates: ["health_report", "critical_alert"] + + dashboard: + integration: "grafana_prometheus" + metrics_export: "real_time" +``` + +## 使用示例 + +### 基础监控 +``` +请监控当前 Serena 索引状态 +# 代理会执行完整的健康检查并生成报告 +``` + +### 性能分析 +``` +分析最近24小时的索引性能变化 +# 代理会深入分析性能趋势并提供优化建议 +``` + +### 问题诊断 +``` +Serena 查询响应变慢,请诊断原因 +# 代理会分析性能瓶颈并提供解决方案 +``` + +### 预警检查 +``` +检查是否有需要关注的索引问题 +# 代理会扫描所有监控指标并报告异常情况 +``` + +通过这个专业的监控代理,用户可以获得全面的索引健康保障和性能优化支持。 \ No newline at end of file diff --git a/commands/serena-cleanup.md b/commands/serena-cleanup.md new file mode 100644 index 0000000..1e18c05 --- /dev/null +++ b/commands/serena-cleanup.md @@ -0,0 +1,238 @@ +--- +name: serena-cleanup +description: "清理 Serena 索引数据,移除过期、损坏或冗余的索引文件以优化性能" +category: maintenance +complexity: standard +mcp-servers: [serena] +personas: [maintainer] +--- + +# /serena-cleanup - Serena 索引清理 + +## Triggers +- 索引文件过大影响性能 +- 磁盘空间不足 +- 索引数据损坏需要重建 +- 项目结构调整后的清理工作 +- 定期维护和优化 + +## Usage +``` +/serena-cleanup [options] + +Options: + --dry-run # 预览将要删除的文件,不实际删除 + --aggressive # 激进清理,删除更多缓存文件 + --force # 强制清理,不询问确认 + --backup # 清理前创建备份 + --keep-days N # 保留最近N天的索引(默认:7天) + --cache-only # 仅清理缓存文件,保留主索引 + --all # 清理所有索引数据(重建用) +``` + +## Behavioral Flow +1. **安全检查**: 验证操作安全性和权限 +2. **扫描分析**: 识别过期、损坏和冗余文件 +3. **空间计算**: 计算可释放的磁盘空间 +4. **用户确认**: 显示清理计划并请求确认(除非使用 --force) +5. **执行清理**: 安全删除标识的文件 +6. **状态更新**: 更新索引元数据 + +## Examples + +### 基本清理 +``` +/serena-cleanup +# 输出: +# 🔍 扫描索引数据... +# +# 📊 发现可清理文件: +# - 过期索引: 3 个文件 (45.2 MB) +# - 临时文件: 12 个文件 (8.7 MB) +# - 缓存文件: 156 个文件 (23.1 MB) +# - 损坏文件: 1 个文件 (2.3 MB) +# +# 💾 总计可释放: 79.3 MB +# +# ❓ 确认清理这些文件吗?[y/N] +``` + +### 预览清理 +``` +/serena-cleanup --dry-run +# 输出: +# 🔍 Serena 索引清理预览 +# +# 📋 将要清理的文件: +# - .serena/cache_old/ (23.4 MB) - 过期缓存 +# - .serena/tmp_20251015/ (12.7 MB) - 临时文件 +# - .serena/index_backup.json (8.9 MB) - 旧备份 +# - .serena/symbols_corrupt.json (2.1 MB) - 损坏文件 +# +# 💾 可释放空间: 47.1 MB +# ⚠️ 这只是预览,不会实际删除文件 +``` + +### 激进清理 +``` +/serena-cleanup --aggressive --keep-days 3 +# 输出: +# 🧹 Serena 激进清理模式 +# +# 📊 清理策略: +# - 保留最近: 3 天的索引 +# - 清理范围: 所有缓存、备份、临时文件 +# - 激进选项: 包括部分有用的缓存文件 +# +# 📋 发现清理目标: +# - 过期索引: 8 个文件 (67.3 MB) +# - 缓存文件: 234 个文件 (45.8 MB) +# - 临时文件: 19 个文件 (15.2 MB) +# - 日志文件: 45 个文件 (8.9 MB) +# +# 💾 总计可释放: 137.2 MB +# ⚠️ 激进清理可能影响首次查询性能 +``` + +### 仅清理缓存 +``` +/serena-cleanup --cache-only +# 输出: +# 🧹 Serena 缓存清理 +# +# 📊 缓存文件统计: +# - 查询缓存: 89 个文件 (23.4 MB) +# - 符号缓存: 156 个文件 (34.7 MB) +# - 元数据缓存: 23 个文件 (5.6 MB) +# - 临时缓存: 67 个文件 (12.3 MB) +# +# 💾 可释放缓存空间: 76.0 MB +# ✅ 主索引文件将保留 +``` + +### 备份清理 +``` +/serena-cleanup --backup +# 输出: +# 💾 创建清理备份... +# ✅ 备份已创建: .serena/backup_20251015_183022.tar.gz (89.2 MB) +# +# 🧹 执行清理操作... +# 📊 清理统计: +# - 删除文件: 167 个 +# - 释放空间: 79.3 MB +# - 保留索引: ✅ 正常 +# +# 🔒 备份位置: .serena/backup_20251015_183022.tar.gz +# ⚠️ 备份将在30天后自动删除 +``` + +### 全部清理 +``` +/serena-cleanup --all --force +# 输出: +# ⚠️ 警告:将删除所有索引数据! +# 🗑️ 清理范围: .serena/ 目录下的所有文件 +# 💾 将释放空间: 245.6 MB +# +# 🔄 执行全部清理... +# ✅ 索引数据已完全清理 +# +# 📝 后续步骤: +# 1. 运行 /serena-index 重建索引 +# 2. 验证索引完整性: /serena-status --health +# 3. 测试查询功能 +``` + +## Cleanup Targets + +### 过期索引 +- 超过保留期的旧索引文件 +- 版本过时的索引数据 +- 项目结构调整后的无效索引 + +### 缓存文件 +- 查询结果缓存 +- 符号解析缓存 +- 临时计算缓存 + +### 临时文件 +- 索引过程中生成的临时文件 +- 中间处理结果 +- 调试和日志文件 + +### 损坏文件 +- 无法读取的索引文件 +- 格式错误的数据文件 +- 不完整的索引片段 + +## Safety Features + +### 自动备份 +- 清理前自动创建备份 +- 备份文件自动过期清理 +- 支持自定义备份保留策略 + +### 权限检查 +- 验证文件删除权限 +- 检查索引文件完整性 +- 防止误删重要数据 + +### 操作回滚 +- 支持从备份恢复 +- 清理日志记录 +- 错误时自动回滚 + +## Configuration Options + +清理行为可以通过环境变量配置: + +```bash +# 默认保留天数 +export SERENA_CLEANUP_KEEP_DAYS=7 + +# 备份保留天数 +export SERENA_BACKUP_RETENTION_DAYS=30 + +# 自动备份阈值 (MB) +export SERENA_AUTO_BACKUP_THRESHOLD=100 + +# 激进清理模式 +export SERENA_AGGRESSIVE_CLEANUP=false +``` + +## Integration with Monitoring + +清理操作会生成详细报告: +- 清理统计信息 +- 性能改进建议 +- 后续维护计划 + +## Error Handling + +### 权限不足 +``` +❌ 权限不足,无法删除索引文件 +💡 解决方案: + 1. 检查文件权限: ls -la .serena/ + 2. 修复权限: chmod -R 755 .serena/ + 3. 使用 sudo 重新运行 (不推荐) +``` + +### 磁盘空间不足 +``` +❌ 磁盘空间不足,无法创建备份 +💡 解决方案: + 1. 使用 --no-backup 跳过备份 + 2. 清理其他文件释放空间 + 3. 使用外部存储设备 +``` + +### 索引正在使用 +``` +⚠️ 检测到索引正在被使用 +💡 建议操作: + 1. 等待当前查询完成 + 2. 使用 --force 强制清理 + 3. 重启 Claude Code 后重试 +``` \ No newline at end of file diff --git a/commands/serena-index.md b/commands/serena-index.md new file mode 100644 index 0000000..be93da1 --- /dev/null +++ b/commands/serena-index.md @@ -0,0 +1,195 @@ +--- +name: serena-index +description: "异步执行 Serena 项目索引,为项目建立语义理解和代码符号索引" +category: project +complexity: standard +mcp-servers: [serena] +personas: [architect] +--- + +# /serena-index - Serena 项目索引 + +## Triggers +- 项目首次使用 Serena MCP 时需要建立索引 +- 代码库发生重大变更后需要重新索引 +- 手动请求项目索引更新 +- 新项目 onboarding 流程的一部分 +- 索引工具响应变慢时需要重新索引 + +## Usage +``` +/serena-index [project-path] [options] + +Options: + --generate-config # 生成 .serena/project.yml 配置文件 + --reindex # 强制重新索引,清除旧索引数据 + --setup-hooks # 配置自动索引 hook(会话开始时自动索引) + --status # 查询当前索引状态和健康度 + --smart # 智能决策(仅在需要时索引) + --verify # 验证索引完整性 + --cleanup # 清理过期索引数据 +``` + +## 环境要求 +- 项目必须是 Git 仓库(需要 `.git` 目录) +- Python 环境和 uvx 工具可用 +- 磁盘空间充足(索引文件可能较大) +- Serena MCP 已配置并启用 + +## Behavioral Flow +1. **环境检测**: 验证 Git 仓库、Python 环境、Serena MCP 配置 +2. **配置准备**: 可选生成 `.serena/project.yml` 配置文件 +3. **委托执行**: 将索引任务委托给 serena-indexer agent 异步执行 +4. **进度监控**: 跟踪索引进度和统计信息 +5. **完成验证**: 验证索引数据完整性和可用性 + +Key behaviors: +- 自动检测项目是否配置了 Serena MCP +- 使用 Task agent 异步执行,不阻塞主工作流 +- 提供清晰的进度反馈和完成状态 +- 支持配置文件生成和重新索引 +- 索引数据存储在 `.serena/` 目录 + +## MCP Integration +- **Serena MCP**: 执行 `uvx --from git+https://github.com/oraios/serena serena project index` +- **Sequential MCP**: 用于复杂的索引状态分析和验证 + +## Tool Coordination +- **Task**: 委托给 serena-indexer agent 进行异步索引执行 +- **Bash**: 检查 MCP 配置和执行索引命令 +- **Read**: 读取项目配置文件验证 Serena 可用性 + +## Key Patterns +- **异步执行**: Task(serena-indexer) → 不阻塞主流程 +- **配置管理**: 生成配置 → 执行索引 → 验证完成 +- **环境验证**: Git 检查 → Python 检查 → MCP 配置检查 +- **错误处理**: 优雅处理索引失败,提供清晰错误信息和解决方案 + +## Examples + +### 基本用法 +``` +/serena-index +# 自动检测当前项目并异步执行索引 +# 索引数据将存储在 .serena/ 目录 +``` + +### 首次使用(生成配置) +``` +/serena-index --generate-config +# 首先生成 .serena/project.yml 配置文件 +# 然后执行项目索引 +``` + +### 指定项目路径 +``` +/serena-index /path/to/project +# 为指定路径的项目执行索引 +``` + +### 重新索引 +``` +/serena-index --reindex +# 强制重新索引,清除旧索引数据 +# 适用于代码库发生重大变更的情况 +``` + +### 配置自动索引 Hook +``` +/serena-index --setup-hooks +# 交互流程: +# ? 选择配置范围: +# > 全局配置(所有项目): ~/.claude/settings.json +# 项目配置(仅当前项目): .claude/settings.json +# ? 选择触发时机: +# > SessionStart(会话开始时) +# PreToolUse(使用 Serena MCP 工具前) +# 仅手动触发 +# ? 选择索引策略: +# 总是索引 +# > 智能判断(推荐) +# 仅手动触发 +# ✅ Hook 配置已创建: .claude/settings.json +# ✅ Hook 脚本已创建: .claude/hooks/serena-auto-index.sh +# +# 下次会话开始或使用 Serena MCP 工具时,hook 将自动检查并更新索引 +``` + +### 查询索引状态 +``` +/serena-index --status +# 输出: +# 📊 Serena 索引状态 +# +# 项目: /path/to/your/project +# 上次索引: 2小时前 (2025-10-15 17:30:45) +# 索引文件: 94 个 Go 文件 +# 提取符号: 1,248 个(函数: 453, 类: 127, 变量: 668) +# 索引大小: 12.3 MB +# 健康度: ✅ 良好(索引新鲜,数据完整) +# +# 建议: 无需重新索引 +``` + +### 智能索引 +``` +/serena-index --smart +# 智能判断是否需要重新索引 +# 如果索引新鲜且文件变更少,则跳过索引 +# 输出: +# 🔍 检查索引状态... +# ✅ 索引仍然新鲜(2小时前),跳过索引 +# 或 +# 🔄 检测到 15 个文件变更,正在更新索引... +``` + +### 验证索引完整性 +``` +/serena-index --verify +# 验证索引数据是否完整和可访问 +# 输出: +# 🔍 正在验证索引完整性... +# ✅ 索引数据完整,所有符号可访问 +# 或 +# ❌ 检测到索引损坏,建议重新索引 +``` + +### 清理旧索引 +``` +/serena-index --cleanup +# 清理过期或损坏的索引数据 +# 输出: +# 🗑️ 清理旧索引数据... +# ✅ 已清理 45.2 MB 过期索引 +``` + +## 索引输出 +- **索引位置**: `.serena/` 目录 +- **日志文件**: `.claude/doc/serena_index_log.md` +- **统计信息**: 文件数量、符号数量、执行时长 +- **错误报告**: 详细的错误堆栈和解决建议 + +## Boundaries + +**Will:** +- 自动检测 Serena MCP 配置状态和 Git 仓库 +- 异步执行索引命令,不阻塞主工作流 +- 可选生成项目配置文件 `.serena/project.yml` +- 生成自动索引 hook 脚本(--setup-hooks) +- 查询索引状态和健康度(--status) +- 智能决策是否需要重新索引(--smart) +- 验证索引完整性(--verify) +- 清理过期索引数据(--cleanup) +- 提供清晰的进度和状态反馈 +- 验证索引完成和项目可用性 +- 处理索引失败并提供解决方案 +- 询问用户偏好(hook 范围、触发时机、索引策略) + +**Will Not:** +- 在未配置 Serena MCP 时强制执行索引 +- 在非 Git 仓库中执行索引 +- 在索引过程中占用主对话流程 +- 覆盖用户的 MCP 配置设置 +- 修改项目源代码文件 +- 在用户未确认的情况下安装 hook +- 强制使用特定的索引策略 \ No newline at end of file diff --git a/commands/serena-status.md b/commands/serena-status.md new file mode 100644 index 0000000..db57e9f --- /dev/null +++ b/commands/serena-status.md @@ -0,0 +1,161 @@ +--- +name: serena-status +description: "查询 Serena 索引状态和健康度,提供详细的索引统计信息" +category: monitoring +complexity: simple +mcp-servers: [serena] +personas: [monitor] +--- + +# /serena-status - Serena 索引状态查询 + +## Triggers +- 需要检查索引是否最新 +- 索引响应变慢时诊断 +- 定期维护和监控 +- 验证索引完整性 + +## Usage +``` +/serena-status [options] + +Options: + --detailed # 显示详细的统计信息 + --health # 执行健康度检查 + --performance # 显示性能指标 + --format json|table|markdown # 输出格式 +``` + +## Behavioral Flow +1. **索引检测**: 检查 .serena 目录和元数据文件 +2. **统计分析**: 分析索引文件大小、符号数量、更新时间 +3. **健康评估**: 评估索引完整性和性能状态 +4. **建议输出**: 提供维护建议和优化选项 + +## Examples + +### 基本状态查询 +``` +/serena-status +# 输出: +# 📊 Serena 索引状态 +# +# 项目: /Users/zephyr/my-project +# 状态: ✅ 健康 +# 上次索引: 2小时前 (2025-10-15 17:30:45) +# 索引文件: 94 个 Go 文件 +# 提取符号: 1,248 个 +# - 函数: 453 个 +# - 类: 127 个 +# - 变量: 668 个 +# 索引大小: 12.3 MB +# +# 建议: 索引状态良好,无需更新 +``` + +### 详细状态查询 +``` +/serena-status --detailed +# 输出: +# 📊 Serena 详细索引状态 +# +# 🗂️ 索引文件信息: +# - project_index.json: 8.2 MB (主索引) +# - symbols_functions.json: 2.1 MB (函数符号) +# - symbols_classes.json: 1.8 MB (类符号) +# - symbols_variables.json: 3.2 MB (变量符号) +# - metadata.json: 15.6 KB (元数据) +# +# 📈 性能指标: +# - 平均查询时间: 45ms +# - 内存占用: 23.4 MB +# - 缓存命中率: 87% +# - 并发查询支持: ✅ +# +# 🔄 更新历史: +# - 最后更新: 2025-10-15 17:30:45 +# - 更新耗时: 4m 32s +# - 更新原因: 15 个文件变更 +# - 更新策略: 增量更新 +# +# 💡 优化建议: +# - 索引质量优秀,性能良好 +# - 建议定期执行完整性检查 +# - 可考虑启用智能缓存优化 +``` + +### 健康检查 +``` +/serena-status --health +# 输出: +# 🔍 Serena 索引健康检查 +# +# ✅ 索引完整性: 通过 +# ✅ 符号可访问性: 通过 +# ✅ 文件同步状态: 通过 +# ✅ 缓存状态: 优秀 +# ⚠️ 索引年龄: 2小时 (建议<6小时) +# ✅ 磁盘空间: 充足 (1.2GB 可用) +# ✅ 权限设置: 正常 +# +# 🎯 总体健康度: 95/100 (优秀) +# +# 📋 维护建议: +# - 索引状态良好,建议保持当前配置 +# - 可设置自动更新策略以保持索引新鲜度 +``` + +### 性能分析 +``` +/serena-status --performance +# 输出: +# ⚡ Serena 性能分析 +# +# 📊 响应时间统计: +# - 平均查询时间: 45ms +# - 95% 分位时间: 89ms +# - 最慢查询: 234ms (查找复杂符号) +# - 最快查询: 12ms (简单函数查找) +# +# 💾 内存使用分析: +# - 索引加载: 23.4 MB +# - 缓存占用: 8.7 MB +# - 查询缓存: 5.2 MB +# - 总内存占用: 37.3 MB +# +# 🚀 性能优化建议: +# - 索引性能优秀,无需优化 +# - 可增加缓存大小以提升命中率 +# - 考虑启用并行查询以提升复杂查询性能 +``` + +## Output Format Options + +### JSON 格式 +``` +/serena-status --format json +# 输出结构化的 JSON 数据,便于程序化处理 +``` + +### Table 格式 +``` +/serena-status --format table +# 输出表格格式,便于快速浏览 +``` + +### Markdown 格式 +``` +/serena-status --format markdown +# 输出 Markdown 格式,便于文档生成 +``` + +## Integration with Other Commands +- 与 `/serena-index` 配合使用进行索引管理 +- 与 `/serena-cleanup` 配合进行性能优化 +- 支持 pipe 输出到其他工具 + +## Error Handling +- 索引不存在时提供清晰的指导 +- 权限问题时提供解决方案 +- 磁盘空间不足时发出警告 +- 索引损坏时建议重建 \ No newline at end of file diff --git a/hooks/hooks.json b/hooks/hooks.json new file mode 100644 index 0000000..ca7bbc2 --- /dev/null +++ b/hooks/hooks.json @@ -0,0 +1,27 @@ +{ + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "${CLAUDE_PLUGIN_ROOT}/hooks/serena-auto-index.sh session-start", + "timeout": 30000 + } + ] + } + ], + "PreToolUse": [ + { + "matcher": "mcp__serena__.*", + "hooks": [ + { + "type": "command", + "command": "${CLAUDE_PLUGIN_ROOT}/hooks/serena-auto-index.sh pre-tool", + "timeout": 10000 + } + ] + } + ] + } +} \ No newline at end of file diff --git a/hooks/serena-auto-index.sh b/hooks/serena-auto-index.sh new file mode 100755 index 0000000..155ec51 --- /dev/null +++ b/hooks/serena-auto-index.sh @@ -0,0 +1,214 @@ +#!/bin/bash + +# Serena 自动索引 Hook 脚本 +# 支持智能索引决策,避免不必要的重复索引 + +set -euo pipefail + +# 颜色定义 +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# 日志函数 +log_info() { + echo -e "${BLUE}[Serena Hook]${NC} $1" +} + +log_success() { + echo -e "${GREEN}[Serena Hook]${NC} $1" +} + +log_warning() { + echo -e "${YELLOW}[Serena Hook]${NC} $1" +} + +log_error() { + echo -e "${RED}[Serena Hook]${NC} $1" >&2 +} + +# 获取脚本参数 +HOOK_TYPE="${1:-session-start}" +PROJECT_ROOT="${CLAUDE_PROJECT_DIR:-$(pwd)}" +SERENA_DIR="$PROJECT_ROOT/.serena" +INDEX_METADATA="$SERENA_DIR/metadata.json" + +log_info "Hook 触发: $HOOK_TYPE" +log_info "项目路径: $PROJECT_ROOT" + +# 检查是否为 Git 仓库 +if [[ ! -d "$PROJECT_ROOT/.git" ]]; then + log_info "非 Git 仓库,跳过索引检查" + exit 0 +fi + +# 检查 Serena MCP 是否配置 +if ! command -v uvx &> /dev/null; then + log_info "uvx 工具未安装,跳过索引检查" + exit 0 +fi + +# 检查 Serena MCP 是否已启用 +check_serena_mcp_enabled() { + # 方案 1: 检查用户级配置 (~/.claude.json) + if [[ -f ~/.claude.json ]]; then + if jq -e '.mcpServers | has("serena")' ~/.claude.json &>/dev/null 2>&1; then + return 0 + fi + fi + + # 方案 2: 检查项目级配置 (.mcp.json) + if [[ -f "$PROJECT_ROOT/.mcp.json" ]]; then + if jq -e 'has("serena")' "$PROJECT_ROOT/.mcp.json" &>/dev/null 2>&1; then + return 0 + fi + fi + + # 方案 3: 检查旧版配置位置(兼容性) + if [[ -f ~/.claude/mcp.json ]]; then + if jq -e 'has("serena")' ~/.claude/mcp.json &>/dev/null 2>&1; then + return 0 + fi + fi + + return 1 +} + +# 检查 metadata.json 文件完整性 +validate_metadata() { + if [[ ! -f "$INDEX_METADATA" ]]; then + return 1 + fi + + # 检查文件是否为有效的 JSON + if ! jq empty "$INDEX_METADATA" 2>/dev/null; then + log_warning "metadata.json 文件损坏,将重新创建" + rm -f "$INDEX_METADATA" + return 1 + fi + + return 0 +} + +# 检查是否需要智能索引决策 +should_skip_index() { + local index_age_threshold=3600 # 1小时 + local change_threshold=10 # 10个文件变更 + + # 如果索引不存在,需要索引 + if ! validate_metadata; then + return 1 + fi + + # 检查索引年龄 + local current_time=$(date +%s) + local index_time=$(jq -r '.timestamp // 0' "$INDEX_METADATA" 2>/dev/null) + if [[ -z "$index_time" || "$index_time" == "null" ]]; then + index_time=0 + fi + local index_age=$((current_time - index_time)) + + if [[ $index_age -lt $index_age_threshold ]]; then + log_info "索引仍然新鲜($(($index_age / 60))分钟前),跳过索引" + return 0 + fi + + # 检查文件变更数量 + local changed_files + changed_files=$(cd "$PROJECT_ROOT" && git diff --name-only HEAD~1 2>/dev/null | wc -l || echo 0) + + if [[ $changed_files -lt $change_threshold ]]; then + log_info "文件变更较少($changed_files 个),跳过索引" + return 0 + fi + + return 1 +} + +# 执行索引 +run_index() { + log_info "开始 Serena 索引..." + + # 创建 .serena 目录 + mkdir -p "$SERENA_DIR" + + # 执行索引命令 + cd "$PROJECT_ROOT" + + if uvx --from git+https://github.com/oraios/serena serena project index 2>&1 | while IFS= read -r line; do + log_info "索引: $line" + done; then + # 创建索引元数据 + local metadata_content=$(cat </dev/null || echo 'unknown')", + "files_indexed": $(find . -name "*.go" -o -name "*.py" -o -name "*.js" -o -name "*.ts" | wc -l), + "index_size": $(du -sh "$SERENA_DIR" 2>/dev/null | cut -f1 || echo "unknown"), + "status": "completed" +} +EOF + ) + + echo "$metadata_content" > "$INDEX_METADATA" + log_success "Serena 索引完成" + return 0 + else + log_error "Serena 索引失败" + return 1 + fi +} + +# 主逻辑 +main() { + case "$HOOK_TYPE" in + "session-start") + log_info "会话开始 - 检查索引状态" + + # 优化:如果 Serena MCP 未启用,跳过索引检查 + if ! check_serena_mcp_enabled; then + log_info "Serena MCP 未启用,跳过索引检查" + exit 0 + fi + + if should_skip_index; then + log_success "索引检查完成,无需更新" + else + log_info "需要更新索引" + run_index + fi + ;; + "pre-tool") + log_info "Serena 工具使用前 - 快速检查" + # PreToolUse hook 执行更快的检查 + if validate_metadata; then + local timestamp=$(jq -r '.timestamp // 0' "$INDEX_METADATA" 2>/dev/null) + if [[ -z "$timestamp" || "$timestamp" == "null" ]]; then + timestamp=0 + fi + local index_age=$(($(date +%s) - timestamp)) + if [[ $index_age -lt 7200 ]]; then # 2小时内不重新索引 + log_success "索引仍然新鲜,继续使用工具" + else + log_warning "索引可能过期,建议手动运行 /serena-index" + fi + else + log_warning "未找到索引,建议手动运行 /serena-index" + fi + ;; + *) + log_error "未知的 hook 类型: $HOOK_TYPE" + exit 1 + ;; + esac +} + +# 错误处理 +trap 'log_error "Hook 执行过程中发生错误"' ERR + +# 执行主逻辑 +main "$@" \ No newline at end of file diff --git a/plugin.lock.json b/plugin.lock.json new file mode 100644 index 0000000..a57617e --- /dev/null +++ b/plugin.lock.json @@ -0,0 +1,69 @@ +{ + "$schema": "internal://schemas/plugin.lock.v1.json", + "pluginId": "gh:ZephyrDeng/cc-plugins:plugins/serena-indexer", + "normalized": { + "repo": null, + "ref": "refs/tags/v20251128.0", + "commit": "f8dc94de0fbc5f4d41ae6fd77ec44fd6c82fccfb", + "treeHash": "8c2f2a9133c537ddab399afddba079db699433300dc54c9bc2612dde028b99c9", + "generatedAt": "2025-11-28T10:12:59.610206Z", + "toolVersion": "publish_plugins.py@0.2.0" + }, + "origin": { + "remote": "git@github.com:zhongweili/42plugin-data.git", + "branch": "master", + "commit": "aa1497ed0949fd50e99e70d6324a29c5b34f9390", + "repoRoot": "/Users/zhongweili/projects/openmind/42plugin-data" + }, + "manifest": { + "name": "serena-indexer", + "description": "专业的 Serena 索引管理插件 - 提供异步索引初始化、智能重建和自动化维护功能", + "version": "1.1.0" + }, + "content": { + "files": [ + { + "path": "README.md", + "sha256": "4079531f9223409f16d07079160a9d673262b0b06e379cc66d209aef11fad735" + }, + { + "path": "agents/serena-monitor.md", + "sha256": "c80d6f3db490534f1e835fbc431c4fa4744699d502e41053497da4681bab2ecf" + }, + { + "path": "agents/serena-indexer.md", + "sha256": "9669d2b9186416b961c5d9ff2624e14a985d3c910aa6db6f628ffd6e3f4431bf" + }, + { + "path": "hooks/hooks.json", + "sha256": "f515dce512f24b446a752126494bd4b88f8b8da37d78c5827cc9341d30407f0a" + }, + { + "path": "hooks/serena-auto-index.sh", + "sha256": "0b7be6db193522fcce27b2763a29f0b3999bd82de93fac0ea6933c1f9665b288" + }, + { + "path": ".claude-plugin/plugin.json", + "sha256": "ba1691ad4acfaa51405832009a238ee11726d88303735d94a06e9202a12f04ea" + }, + { + "path": "commands/serena-cleanup.md", + "sha256": "0b9ff29c080d207965e8f4b49f57098a9e4b0064b87635a56a7a10274b683086" + }, + { + "path": "commands/serena-index.md", + "sha256": "c698796ff8d0795dfdc4042c32fca1272215a5fe3c28d2ec87a563b9fd0a5238" + }, + { + "path": "commands/serena-status.md", + "sha256": "6c7a75e6095e34ee869045f991e3c6d84f479edac00d2466eab78d08b7cd9340" + } + ], + "dirSha256": "8c2f2a9133c537ddab399afddba079db699433300dc54c9bc2612dde028b99c9" + }, + "security": { + "scannedAt": null, + "scannerVersion": null, + "flags": [] + } +} \ No newline at end of file