first commit

This commit is contained in:
2026-06-11 03:33:14 +08:00
commit 5f555bf342
599 changed files with 142347 additions and 0 deletions

View File

@@ -0,0 +1,201 @@
---
name: analyze-results
description: Run a blocker-first post-experiment workflow: validate evidence, produce strict statistical analysis when possible, and generate a decision-oriented results report only when the analysis bundle is sufficient. Uses results-analysis + results-report as a gated two-stage workflow.
args:
- name: data_path
description: Path to experimental results (CSV, JSON, logs, or directory)
required: false
- name: analysis_type
description: Type of analysis (full, comparison, ablation, visualization, audit)
required: false
default: full
- name: purpose
description: Optional report purpose slug (e.g. transfer-summary, ablation-report)
required: false
default: auto
- name: round
description: Optional experiment round number for report naming
required: false
- name: experiment_line
description: Optional experiment line slug for report naming
required: false
tags: [Research, Analysis, Statistics, Visualization, Reporting]
---
# Analyze Results Command
执行 **blocker-first 实验后分析 + 报告工作流**
这是用户默认应该使用的入口,但它不是无条件“一键成稿”。它必须先判断证据是否足够,再决定进入 strict analysis、read-only audit、figure generation 或 results report。
如果你只是想“跑严格统计和科研图,不写总结报告”,才单独走 `results-analysis`
## 目标
此命令负责把一次实验结果处理成两层产物:
### Phase 1: strict analysis bundle
- 严格统计分析
- 真实科研图
- figure interpretation checklist
- 可追溯的统计附录
### Phase 2: complete results report
- 完整实验总结报告
- 逐图解释与结论串联
- 面向决策的 next actions
- 如已绑定 Obsidian则自动写回知识库
换句话说,`/analyze-results` 不只是“分析”,而是:
> **先做 evidence-first analysis再基于证据生成完整实验报告。**
## 默认编排
命令默认按以下顺序执行:
0. **Blocker-first gate**
- 锁定 primary question、primary metric、unit of analysis、seed/run/fold/subject 数、raw provenance、comparison family
- 如果现有 stats table 的 p-value、interpretation、test method、unit of analysis 或 comparison family 互相矛盾,先 quarantine 该统计文件
- 如果这些信息不足,先输出 blocker summary 或 read-only audit不生成完整报告
1. **定位输入**
- 找到实验目录、CSV/JSON、日志、图表原料与比较对象
2. **Phase 1 严格分析**
- 使用 `results-analysis`
- 当用户要求 no-write / audit或输入不足以生成分析产物时只输出 valid/invalid statistics、claim candidates 和 blockers
3. **Phase 2 完整报告**
- 使用 `results-report`
- 只在 Phase 1 产物包含 `analysis-report.md``stats-appendix.md``figure-catalog.md` 和必要 provenance 时生成完整实验总结报告
4. **知识库回写**
- 如果当前 repo 已绑定 Obsidian project memory则写回 `Results/Reports/`、相关 `Experiments/``Daily/` 和 project memory
5. **显式报告 blocker**
- 若统计输入不足、无法画图或命名信息缺失,必须说明阻塞点,不能伪造结论
## 使用方法
### 基本用法
```bash
/analyze-results
```
### 指定实验目录
```bash
/analyze-results path/to/experiment_dir
```
### 指定分析类型
```bash
/analyze-results path/to/results comparison
```
### 指定报告用途与轮次
```bash
/analyze-results path/to/results full transfer-summary 3 freezing
```
## 参数说明
| 参数 | 说明 |
|------|------|
| `data_path` | 实验结果路径可为目录、CSV、JSON 或日志 |
| `analysis_type` | `full` / `comparison` / `ablation` / `visualization` / `audit` |
| `purpose` | 报告用途 slug默认自动推断无法推断时需显式说明 |
| `round` | 实验轮次;用于报告命名,未知时允许暂用 `r00` 并注明 |
| `experiment_line` | 实验线 slug`freezing``contrastive-adversarial` |
## 分析类型
| 类型 | 说明 | Phase 1 重点 | Phase 2 重点 |
|------|------|--------------|--------------|
| `full` | 完整严格分析(默认) | 完整统计 + 主图 + supporting figure | 完整实验总结报告 |
| `comparison` | 模型对比 | 显著性检验 + effect size + 主对比图 | 哪个方案更值得继续 |
| `ablation` | 消融实验 | 组件贡献分析 + 稳定性分析 | 哪个组件真正改变了结果 |
| `visualization` | 图表优先 | 高质量科研图 + 图表解释 | 图驱动的结果复盘 |
| `audit` | 只审查证据是否足够 | valid/invalid statistics、claim candidates、blockers | 不生成完整报告 |
## 输出产物
### Phase 1 输出
```text
analysis-output/
├── analysis-report.md
├── stats-appendix.md
├── figure-catalog.md
└── figures/
```
### Phase 2 输出
```text
Results/Reports/
└── YYYY-MM-DD--{experiment-line}--r{round}--{purpose}.md
```
If the blocker-first gate fails, the valid output is a blocker summary or audit note instead of a report:
```text
analysis-output/
└── blocker-summary.md
```
报告标题默认遵循:
```text
{Experiment Line} / Round {N} / {Purpose} / {YYYY-MM-DD}
```
## 执行规则
### 统计与图表
- 必须优先生成真实科研图,而不是只写 visualization specs
- 必须报告样本单位、seed/run 数、`95% CI`、effect size、multiple-comparison handling
- 假设不满足时必须改用 non-parametric fallback 或显式说明不能做强推断
- 如果 unit of analysis、primary metric、seed/fold/raw provenance 不清楚,不能生成显著性 claim 或 winner claim
- 如果统计表内部解释和数值矛盾,必须 quarantine不能把矛盾统计写进报告或图注
- 当用户明确要求 audit/no-write只做 read-only audit不生成图和报告文件
### 报告生成
- 报告必须基于 Phase 1 的真实证据,而不是凭印象总结
- 报告必须覆盖main findings、statistical validation、figure-by-figure interpretation、negative results、next actions
- 报告默认是**内部实验总结报告**,不是论文 `Results` section
- 如果缺少完整 analysis bundle只能写 blocker summary不能用 polished prose 替代缺失统计
### Obsidian 写回
如果 repo 已绑定 Obsidian knowledge base则至少执行
- 新建/更新 `Results/Reports/{report-name}.md`
- 回链对应 `Experiments/` note
- 若结论已稳定,更新 canonical `Results/` note
- 追加当天 `Daily/YYYY-MM-DD.md`
- 更新 `.claude/project-memory/<project_id>.md`
## 何时不用这个命令
以下场景不必默认使用 `/analyze-results`
1. **你只要统计和图,不要实验总结报告**
- 直接用 `results-analysis` 生成 Phase 1 strict analysis bundle
2. **你已经有 analysis bundle只差最终报告**
- 直接用 `results-report`
3. **你要写论文 Results section**
- 不应由本命令直接替代 manuscript writing workflow
## 集成关系
- **Primary user entrypoint**: `/analyze-results`
- **Phase 1 skill**: `results-analysis`
- **Phase 2 skill**: `results-report`
## 成功标准
完成后至少应满足:
- blocker-first gate 已完成,并明确说明是否可以进入报告阶段
- 若证据充足,有 strict analysis bundle 和命名规范正确的 results report
- 若证据不足,有 blocker summary / audit note且没有伪造图表、统计或结论
- 图表与文字解释一致
- blocker 与限制被明确写出
- 若 repo 绑定 Obsidian只有在证据足够时才完成最小写回

View File

@@ -0,0 +1,32 @@
# Build and Fix
Incrementally fix Python type and lint errors:
1. Run checks:
- mypy src/ (type checking)
- ruff check . (linting)
- pytest (tests)
2. Parse error output:
- Group by file
- Sort by severity
3. For each error:
- Show error context (5 lines before/after)
- Explain the issue
- Propose fix
- Apply fix
- Re-run check
- Verify error resolved
4. Stop if:
- Fix introduces new errors
- Same error persists after 3 attempts
- User requests pause
5. Show summary:
- Errors fixed
- Errors remaining
- New errors introduced
Fix one error at a time for safety!

View File

@@ -0,0 +1,74 @@
# Checkpoint Command
Create or verify a checkpoint in your workflow.
## Usage
`/checkpoint [create|verify|list] [name]`
## Create Checkpoint
When creating a checkpoint:
1. Run `/verify quick` to ensure current state is clean
2. Create a git stash or commit with checkpoint name
3. Log checkpoint to `.claude/checkpoints.log`:
```bash
echo "$(date +%Y-%m-%d-%H:%M) | $CHECKPOINT_NAME | $(git rev-parse --short HEAD)" >> .claude/checkpoints.log
```
4. Report checkpoint created
## Verify Checkpoint
When verifying against a checkpoint:
1. Read checkpoint from log
2. Compare current state to checkpoint:
- Files added since checkpoint
- Files modified since checkpoint
- Test pass rate now vs then
- Coverage now vs then
3. Report:
```
CHECKPOINT COMPARISON: $NAME
============================
Files changed: X
Tests: +Y passed / -Z failed
Coverage: +X% / -Y%
Build: [PASS/FAIL]
```
## List Checkpoints
Show all checkpoints with:
- Name
- Timestamp
- Git SHA
- Status (current, behind, ahead)
## Workflow
Typical checkpoint flow:
```
[Start] --> /checkpoint create "feature-start"
|
[Implement] --> /checkpoint create "core-done"
|
[Test] --> /checkpoint verify "core-done"
|
[Refactor] --> /checkpoint create "refactor-done"
|
[PR] --> /checkpoint verify "feature-start"
```
## Arguments
$ARGUMENTS:
- `create <name>` - Create named checkpoint
- `verify <name>` - Verify against named checkpoint
- `list` - Show all checkpoints
- `clear` - Remove old checkpoints (keeps last 5)

View File

@@ -0,0 +1,43 @@
# Code Review
Comprehensive security and quality review of uncommitted changes:
1. Get changed files: git diff --name-only HEAD
2. For each changed file, check for:
**Security Issues (CRITICAL):**
- Hardcoded credentials, API keys, tokens
- SQL injection vulnerabilities
- XSS vulnerabilities
- Missing input validation
- Insecure dependencies
- Path traversal risks
- Insecure deserialization (pickle)
**Code Quality (HIGH):**
- Functions > 50 lines
- Files > 800 lines
- Nesting depth > 4 levels
- Missing error handling (try/except)
- print() statements in production
- TODO/FIXME comments without tickets
- Missing docstrings for public APIs
- Missing type hints (Python 3.6+)
**Best Practices (MEDIUM):**
- Mutable default arguments
- Emoji usage in code/comments
- Missing tests for new code
- Missing `if __name__ == "__main__"` guards
- Unused imports (detect with ruff/pyflakes)
3. Generate report with:
- Severity: CRITICAL, HIGH, MEDIUM, LOW
- File location and line numbers
- Issue description
- Suggested fix
4. Block commit if CRITICAL or HIGH issues found
Never approve code with security vulnerabilities!

View File

@@ -0,0 +1,53 @@
---
description: Commit changes following Conventional Commits format (local only, no push).
---
# Commit
Stage and commit changes using Conventional Commits format.
## Instructions
1. **Check Git Status**
- Run `git status` to review all changes
- Run `git diff` to inspect modifications
2. **Analyze Changes**
- Review changed files and their content
- Determine commit type and scope
- Draft a concise commit message
3. **Commit Type Reference**
```
feat - New feature
fix - Bug fix
docs - Documentation only
style - Code style (formatting, semicolons, etc.)
refactor - Code refactoring (no feature/fix)
perf - Performance improvement
test - Adding or updating tests
chore - Build, CI, tooling, dependencies
```
4. **Commit Message Format**
```
<type>(<scope>): <subject>
<body>
```
- Subject: imperative mood, no period, max 72 chars
- Body: explain what and why (optional for small changes)
- Scope: affected module (data, model, config, trainer, utils, workflow)
5. **Stage and Commit**
- Stage relevant files with `git add`
- Do NOT stage files containing secrets (.env, credentials, tokens)
- Create commit with formatted message
- Do not include `Co-Authored-By` footers unless the user explicitly asks for them
- Verify with `git log --oneline -1`
## Notes
- This command only commits locally. Use `/update-github` to also push.
- Always confirm the commit message with the user before committing.
- If unsure about type or scope, ask the user.

View File

@@ -0,0 +1,239 @@
---
name: create_project
description: Create a new project from template with uv and Git initialization
arguments:
- name: project_name
description: 项目名称
required: true
- name: path
description: 项目路径(默认为 ~/Code/
required: false
- name: template_repo
description: GitHub 模板仓库格式owner/repo 或完整 URL默认gaoruizhang/template
required: false
- name: local
description: 使用本地模板 ~/Code/template 而非 GitHub覆盖 template_repo
required: false
---
# 创建新项目
此命令基于模板创建新项目,包含以下步骤:
1. 从 GitHub 或本地获取模板文件
2. 替换项目名称
3. 初始化 uv 项目
4. 配置 Git 仓库和分支策略
5. 创建初始 tag
6. 初始化 GitHub 远程仓库
```bash
# 解析参数
PROJECT_NAME="{{project_name}}"
PROJECT_PATH="${path:-$HOME/Code}"
FULL_PATH="$PROJECT_PATH/$PROJECT_NAME"
TEMPLATE_REPO="{{template_repo:-gaoruizhang/template}}"
USE_LOCAL="{{local}}"
INITIAL_TAG="v0.1.0"
# 确定使用本地还是 GitHub 模板
if [ "$USE_LOCAL" = "true" ]; then
# local 参数优先
TEMPLATE_PATH="$HOME/Code/template"
USE_LOCAL_TEMPLATE=true
else
# 使用 GitHub 模板
if [[ "$TEMPLATE_REPO" == https://github.com/* ]] || [[ "$TEMPLATE_REPO" == git@github.com:* ]]; then
TEMPLATE_URL="$TEMPLATE_REPO"
else
# owner/repo 格式,转换为 HTTPS URL
TEMPLATE_URL="https://github.com/$TEMPLATE_REPO"
fi
USE_LOCAL_TEMPLATE=false
fi
echo "🚀 创建新项目: $PROJECT_NAME"
echo "📁 路径: $FULL_PATH"
echo ""
# 检查模板源
if [ "$USE_LOCAL_TEMPLATE" = true ]; then
if [ ! -d "$TEMPLATE_PATH" ]; then
echo "❌ 错误: 本地模板目录不存在: $TEMPLATE_PATH"
exit 1
fi
echo "📋 使用本地模板: $TEMPLATE_PATH"
else
echo "📋 使用 GitHub 模板: $TEMPLATE_URL"
fi
# 检查目标目录是否已存在
if [ -d "$FULL_PATH" ]; then
echo "❌ 错误: 目录已存在: $FULL_PATH"
exit 1
fi
# 1. 创建项目目录
echo "📂 创建项目目录..."
mkdir -p "$FULL_PATH"
# 2. 获取模板文件
echo "📋 获取模板文件..."
if [ "$USE_LOCAL_TEMPLATE" = true ]; then
# 本地模板:使用 rsync 复制(排除 .git、.idea、.DS_Store 等)
rsync -av --exclude='.git' \
--exclude='.idea' \
--exclude='.DS_Store' \
--exclude='__pycache__' \
--exclude='*.pyc' \
"$TEMPLATE_PATH/" "$FULL_PATH/"
else
# GitHub 模板:使用 git clone 到临时目录,然后移动文件
TEMP_TEMPLATE_DIR=$(mktemp -d)
git clone --depth 1 "$TEMPLATE_URL" "$TEMP_TEMPLATE_DIR"
# 移动文件到目标目录(排除 .git
rsync -av --exclude='.git' \
--exclude='.idea' \
--exclude='.DS_Store' \
--exclude='__pycache__' \
--exclude='*.pyc' \
"$TEMP_TEMPLATE_DIR/" "$FULL_PATH/"
# 清理临时目录
rm -rf "$TEMP_TEMPLATE_DIR"
fi
# 3. 替换项目名称
echo "✏️ 替换项目名称..."
cd "$FULL_PATH"
# 替换 README.md 第一行(如果是示例标题)
if [ -f "README.md" ]; then
# 检查第一行是否是 # 开头的标题
FIRST_LINE=$(head -n 1 README.md)
if [[ "$FIRST_LINE" == "#"* ]]; then
# 替换第一行为项目名称
echo "# $PROJECT_NAME" > README.md.new
tail -n +2 README.md >> README.md.new
mv README.md.new README.md
echo " ✓ 更新 README.md 标题"
fi
fi
# 替换 pyproject.toml 中的项目名称(如果存在)
if [ -f "pyproject.toml" ]; then
sed -i.bak "s/name = \".*\"/name = \"$PROJECT_NAME\"/" pyproject.toml
rm -f pyproject.toml.bak
echo " ✓ 更新 pyproject.toml 项目名"
fi
# 4. 初始化 uv 项目
echo "🔧 初始化 uv 项目..."
uv init --no-readme # README 已从模板复制
# 4.5 生成 uv.lock最佳实践初始提交应包含 lockfile
echo "🔒 生成 uv.lock..."
uv sync
# 5. 初始化 Git 仓库(默认在 master 分支)
echo "🔧 初始化 Git 仓库..."
git init
# 6. 初始提交在 master
echo "📝 创建初始提交..."
git add .
git commit -m "chore: 初始化项目
基于模板创建项目结构
- 配置项目结构
- 初始化 uv 依赖管理(包含 uv.lock
- 设置 Git 工作流 (master/develop)
- 创建初始版本 $INITIAL_TAG"
# 7. 创建初始 tag在 master 上)
echo "🏷️ 创建初始标签: $INITIAL_TAG"
git tag -a "$INITIAL_TAG" -m "release: $INITIAL_TAG 初始版本
项目初始化完成"
# 8. 创建 develop 分支
echo "🌿 创建 develop 分支..."
git checkout -b develop
# 9. 询问是否创建 GitHub 仓库
echo ""
echo "✅ 项目创建完成!"
echo ""
echo "📍 项目位置: $FULL_PATH"
echo "🏷️ 初始版本: $INITIAL_TAG"
echo ""
echo "📌 下一步操作:"
echo " cd $FULL_PATH"
echo ""
# 询问是否创建 GitHub 远程仓库
read -p "是否创建 GitHub 远程仓库?(y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
# 检查 gh CLI 是否安装
if ! command -v gh &> /dev/null; then
echo "⚠️ GitHub CLI (gh) 未安装,跳过远程仓库创建"
echo " 安装: brew install gh"
else
echo "🌐 创建 GitHub 远程仓库..."
cd "$FULL_PATH"
# 使用 gh CLI 创建仓库
gh repo create "$PROJECT_NAME" --private --source=. --remote=origin
# 推送分支和标签(先切换回 master
echo "📤 推送分支和标签到远程..."
git checkout master
git push -u origin master
git push origin "$INITIAL_TAG"
git push -u origin develop
git checkout develop
echo ""
echo "✅ GitHub 仓库创建完成!"
# 获取仓库 URL
REPO_URL=$(git config --get remote.origin.url)
if [[ "$REPO_URL" == "git@github.com"* ]]; then
# SSH URL
REPO_URL="https://github.com/$(git config --get user.name)/$PROJECT_NAME"
fi
echo " 👉 $REPO_URL"
fi
else
echo "⏭️ 跳过 GitHub 仓库创建"
echo " 稍后可手动执行:"
echo " cd $FULL_PATH && gh repo create $PROJECT_NAME --private --source=. --remote=origin"
fi
echo ""
echo "🎉 项目初始化完成!"
echo ""
echo "📋 Git 工作流说明:"
echo " - master: 主分支(生产环境)- 禁止直接推送"
echo " - develop: 开发分支"
echo " - feature/xxx: 功能分支(从 develop 创建)"
echo " - bugfix/xxx: Bug 修复分支(从 develop 创建)"
echo ""
echo "📚 常用命令:"
echo " git checkout develop # 切换到开发分支"
echo " git checkout -b feature/xxx # 创建功能分支"
echo " git checkout develop && git merge --no-ff feature/xxx # 合并功能分支"
echo " git tag -a v1.0.0 -m \"release: v1.0.0\" # 创建版本标签"
echo ""
echo "📦 uv 常用命令:"
echo " uv run python script.py # 运行脚本(无需激活 venv"
echo " uv add <package> # 添加依赖"
echo " uv add --dev pytest black ruff # 添加开发依赖"
echo " uv lock --check # 检查 lockfile 是否最新"
echo " uv sync --frozen # CI 中使用(精确版本)"
echo ""
echo "📦 下一步:"
echo " cd $FULL_PATH"
echo " # 依赖已安装,虚拟环境已创建 (.venv)"
echo ""

View File

@@ -0,0 +1,45 @@
---
name: kb-archive
description: Archive, detach, purge, or rename KB objects while keeping registry, index, and links consistent.
args:
- name: action
description: detach, archive, purge, rename
required: true
- name: target
description: Project-relative note path when operating on a note.
required: false
- name: dest
description: Destination note path for rename.
required: false
tags: [Research, Obsidian, KB, Lifecycle]
---
# /kb-archive
Use this command for KB lifecycle actions.
## Project-level lifecycle
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/skills/obsidian-project-kb-core/scripts/project_kb.py" lifecycle --cwd "$PWD" --mode "$action"
```
Project archive means moving the whole project to:
```text
Research/_archived/{project-slug}-{date}/
```
## Note-level lifecycle
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/skills/obsidian-project-kb-core/scripts/project_kb.py" note-lifecycle --cwd "$PWD" --mode "$action" --note "$target"
```
If `action=rename`, also pass `--dest "$dest"`.
Note archive means moving a canonical note into:
```text
Research/{project-slug}/Archive/
```

View File

@@ -0,0 +1,14 @@
---
name: kb-index
description: Refresh the auto index block inside 02-Index.md without overwriting curated content.
tags: [Research, Obsidian, KB]
---
# /kb-index
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/skills/obsidian-project-kb-core/scripts/project_kb.py" sync --cwd "$PWD" --scope index
```
The index is a human navigation note, not a registry mirror.
Only the auto-generated block should be refreshed here; curated sections must stay intact.

View File

@@ -0,0 +1,25 @@
---
name: kb-ingest
description: Ingest external material into Sources/* inside the bound project KB, then update registry, index, and daily note as needed.
args:
- name: path
description: Source path or URL to ingest.
required: true
tags: [Research, Obsidian, KB, Ingestion]
---
# /kb-ingest
Use `obsidian-source-ingestion` with the new routing rules:
- paper -> `Sources/Papers/`
- web -> `Sources/Web/`
- docs/spec -> `Sources/Docs/`
- dataset/benchmark -> `Sources/Data/`
- interview/transcript -> `Sources/Interviews/`
- loose imported note -> `Sources/Notes/`
After ingest:
- update `_system/registry.md`
- update `02-Index.md` when the source is important
- append a short line to today's `Daily/` when this is part of an active session

View File

@@ -0,0 +1,62 @@
---
name: kb-init
description: Initialize or rebuild a vault-first, project-scoped Obsidian KB under Research/{project-slug}/ for the current repository.
args:
- name: project
description: Optional project name. Defaults to the repository name.
required: false
- name: vault_path
description: Absolute Obsidian vault path. Defaults to OBSIDIAN_VAULT_PATH.
required: false
- name: force
description: Force scaffold refresh when the project already exists.
required: false
default: false
tags: [Research, Obsidian, KB]
---
# /kb-init
Use the new KB scaffold under `Research/{project-slug}/`.
## Run
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/skills/obsidian-project-kb-core/scripts/project_kb.py" bootstrap \
--cwd "$PWD" \
--vault-path "$vault_path"
```
If `project` is provided, add:
```bash
--project-name "$project"
```
If `force=true`, add:
```bash
--force
```
## Verify
The scaffold must contain:
```text
Research/{project-slug}/
00-Hub.md
01-Plan.md
02-Index.md
Sources/*
Knowledge/
Experiments/
Results/Reports/
Writing/
Daily/
Maps/
Archive/
_system/
```
It must also keep repo-local `.claude/project-memory/*` as runtime binding metadata only.

View File

@@ -0,0 +1,25 @@
---
name: kb-links
description: Repair or strengthen wikilinks among canonical KB notes without generating extra artifact sprawl.
tags: [Research, Obsidian, KB]
---
# /kb-links
Use `obsidian-kb-artifacts` for standalone wikilink repair.
Default surfaces:
- `Sources/`
- `Knowledge/`
- `Experiments/`
- `Results/`
- `Writing/`
- `00-Hub.md`
- `01-Plan.md`
- `02-Index.md`
Rules:
- repair links inside existing canonical notes first
- do not create new notes just to satisfy a weak connection
- after substantial link repair, run `/kb-sync` or `/kb-lint`
- only touch `Maps/` when the user explicitly wants artifact updates

View File

@@ -0,0 +1,13 @@
---
name: kb-lint
description: Run deterministic KB health checks and rewrite _system/lint-report.md.
tags: [Research, Obsidian, KB, Lint]
---
# /kb-lint
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/skills/obsidian-project-kb-core/scripts/kb_lint.py" --cwd "$PWD"
```
Checks include registry coverage, broken wikilinks, index coverage, canvas validity, and several KB consistency warnings.

View File

@@ -0,0 +1,25 @@
---
name: kb-literature-review
description: Run the project-scoped literature workflow from Sources/Papers into Knowledge, Writing, and Maps/literature.canvas.
tags: [Research, Obsidian, KB, Literature]
---
# /kb-literature-review
Use `obsidian-literature-workflow`.
Conditional outputs:
- `Knowledge/Literature Overview.md` only when paper notes contain enough Evidence Records for synthesis
- `Knowledge/Method Taxonomy.md` when useful and evidence-backed
- `Knowledge/Research Gaps.md` when useful and evidence-backed
- `Knowledge/Claim Map.md` or a warning when evidence is weak
- `Writing/related-work-draft.md` only when promoted claims pass the evidence gate
- `Maps/literature.canvas`
Keep source notes in `Sources/Papers/`. Do not turn source notes into synthesis notes.
Evidence gate:
- refuse polished `Knowledge` or `Writing` synthesis when paper notes lack Evidence Records,
- keep abstract-only or webpage-placeholder items in coverage / `To-Read`,
- generate a warning or `Knowledge/Claim Map.md` instead of a mature related-work draft when evidence is weak,
- preserve claim strength on literature canvas edges.

View File

@@ -0,0 +1,15 @@
---
name: kb-log
description: Update the current project Daily note and, when needed, the plan, hub, and runtime binding summary.
tags: [Research, Obsidian, KB, Daily]
---
# /kb-log
Use `obsidian-project-kb-core`.
Default targets:
- `Daily/YYYY-MM-DD.md`
- `01-Plan.md` when a durable task changes
- `00-Hub.md` only when project-level focus changes
- `.claude/project-memory/<project_id>.md` as runtime sync summary

View File

@@ -0,0 +1,14 @@
---
name: kb-map
description: Generate or repair derived KB artifacts such as literature.canvas, optional Bases, or other explicit map outputs.
tags: [Research, Obsidian, KB, Maps]
---
# /kb-map
Default automatic map maintenance is limited to `Maps/literature.canvas` from the literature workflow.
Use `obsidian-kb-artifacts` for:
- canvas validation or repair
- explicit `.base` generation
- optional extra maps when the user asks for them

View File

@@ -0,0 +1,16 @@
---
name: kb-promote
description: Promote durable content from Daily or source notes into canonical Knowledge, Experiments, Results, Results/Reports, or Writing notes.
tags: [Research, Obsidian, KB]
---
# /kb-promote
Use `obsidian-project-kb-core` to decide whether content should become:
- `Knowledge/`
- `Experiments/`
- `Results/`
- `Results/Reports/`
- `Writing/`
Do not promote raw session noise. Update `_system/registry.md` and `02-Index.md` after promotion.

View File

@@ -0,0 +1,13 @@
---
name: kb-status
description: Summarize the current bound project KB status, including registry counts and key project note paths.
tags: [Research, Obsidian, KB]
---
# /kb-status
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/skills/obsidian-project-kb-core/scripts/project_kb.py" status --cwd "$PWD"
```
Optionally add `--project-id "$project_id"` when the repo has multiple bindings.

View File

@@ -0,0 +1,34 @@
---
name: kb-sync
description: Run deterministic KB maintenance to refresh scaffold integrity, registry, index, daily note, and runtime binding summary.
args:
- name: scope
description: Sync scope such as auto, all, index, literature, experiments, or results.
required: false
default: auto
tags: [Research, Obsidian, KB]
---
# /kb-sync
Use this when you want a deterministic project-KB resync after structural changes, note moves, migrations, or batch updates.
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/skills/obsidian-project-kb-core/scripts/project_kb.py" sync --cwd "$PWD" --scope "$scope"
```
Typical scopes:
- `auto`
- `all`
- `index`
- `literature`
- `experiments`
- `results`
This refreshes:
- scaffold integrity under `Research/{project-slug}/`
- `_system/registry.md`
- `02-Index.md`
- today's `Daily/YYYY-MM-DD.md`
- repo-local `.claude/project-memory/<project_id>.md`
- `00-Hub.md` recent changes when appropriate

View File

@@ -0,0 +1,70 @@
# /learn - Extract Reusable Patterns
Analyze the current session and extract any patterns worth saving as skills.
## Trigger
Run `/learn` at any point during a session when you've solved a non-trivial problem.
## What to Extract
Look for:
1. **Error Resolution Patterns**
- What error occurred?
- What was the root cause?
- What fixed it?
- Is this reusable for similar errors?
2. **Debugging Techniques**
- Non-obvious debugging steps
- Tool combinations that worked
- Diagnostic patterns
3. **Workarounds**
- Library quirks
- API limitations
- Version-specific fixes
4. **Project-Specific Patterns**
- Codebase conventions discovered
- Architecture decisions made
- Integration patterns
## Output Format
Create a skill file at `~/.claude/skills/learned/[pattern-name].md`:
```markdown
# [Descriptive Pattern Name]
**Extracted:** [Date]
**Context:** [Brief description of when this applies]
## Problem
[What problem this solves - be specific]
## Solution
[The pattern/technique/workaround]
## Example
[Code example if applicable]
## When to Use
[Trigger conditions - what should activate this skill]
```
## Process
1. Review the session for extractable patterns
2. Identify the most valuable/reusable insight
3. Draft the skill file
4. Ask user to confirm before saving
5. Save to `~/.claude/skills/learned/`
## Notes
- Don't extract trivial fixes (typos, simple syntax errors)
- Don't extract one-time issues (specific API outages, etc.)
- Focus on patterns that will save time in future sessions
- Keep skills focused - one pattern per skill

View File

@@ -0,0 +1,135 @@
---
name: mine-writing-patterns
description: Read one or more papers and update the active installed paper-miner writing memory with reusable writing patterns, structure signals, reusable phrasing, venue-specific signals, and rebuttal-friendly language.
args:
- name: source
description: Paper source path, URL, arXiv link, or a short description of the target papers
required: true
- name: focus
description: Optional focus area (general/introduction/method/results/rebuttal/venue)
required: false
default: general
tags: [Research, Writing, Paper Mining, Knowledge Extraction]
---
# /mine-writing-patterns - Installed Writing Memory Mining
Read the paper source "$source" and update the active installed **paper-miner writing memory**.
## Default target
Always write mined knowledge into the active installed skill memory, not the repository checkout copy:
```text
~/.claude/skills/ml-paper-writing/references/knowledge/paper-miner-writing-memory.md
```
This command does **not** create project-specific writing memory unless the user explicitly asks for a project-local writing memory.
## When to use
Use this command when you want to:
- learn reusable writing patterns from a strong paper,
- study how a venue frames introductions, methods, results, or rebuttals,
- mine phrasing and structure signals before drafting,
- enrich the writing memory that powers `ml-paper-writing` and `review-response`.
## Usage
### Basic usage
```bash
/mine-writing-patterns path/to/paper.pdf
```
### Mine from an arXiv paper
```bash
/mine-writing-patterns https://arxiv.org/abs/2301.xxxxx
```
### Focus on rebuttal or venue signals
```bash
/mine-writing-patterns path/to/paper.pdf rebuttal
/mine-writing-patterns path/to/paper.pdf venue
```
## Workflow
### Step 1: Resolve the paper source
Acceptable inputs:
- local PDF
- local DOCX
- arXiv URL
- readable web URL
- short natural-language request that identifies the paper(s)
If the source is ambiguous, narrow it before mining.
### Step 2: Invoke `paper-miner`
Use the `paper-miner` agent to:
- extract paper content,
- identify reusable writing knowledge,
- merge it into the active installed writing memory,
- avoid duplicate entries,
- preserve source attribution.
### Step 3: Respect the focus mode
Interpret `$focus` as follows:
| Focus | Priority |
|------|----------|
| `general` | Mine balanced signals across all major sections |
| `introduction` | Emphasize framing, motivation, and contribution setup |
| `method` | Emphasize exposition style, technical sequencing, and clarity |
| `results` | Emphasize result narration, claim-evidence language, and interpretation |
| `rebuttal` | Emphasize clarification phrases, response structure, and reviewer-facing tone |
| `venue` | Emphasize venue-specific style and convention signals |
### Step 4: Update the canonical memory only
The canonical write target is the active installed skill memory:
```text
~/.claude/skills/ml-paper-writing/references/knowledge/paper-miner-writing-memory.md
```
Update one or more of these sections:
- `Writing patterns mined`
- `Structure signals`
- `Reusable phrasing`
- `Venue-specific signals`
- `How this helps our writing`
- `Source index`
If that file is unavailable in the current runtime, use the configured installed skill home for the active runtime and state the exact path in the final summary. Do not silently fall back to the repository checkout.
Do not create project-local writing memory.
Do not scatter the mined result across multiple maintained knowledge files.
### Step 5: Return a standardized mining summary
The final response should follow the `paper-miner` standardized output format:
- metadata
- memory write summary
- new reusable patterns
- how we should reuse this
- blockers or limits
## Related integrations
- `ml-paper-writing` reads this active installed memory before drafting or revising sections.
- `review-response` reads this active installed memory when tone, phrasing, and rebuttal structure matter.
- `paper-miner` is the agent that performs the actual mining work.
## Success criteria
- the target paper is read successfully,
- reusable writing knowledge is merged into the canonical memory,
- source attribution is preserved,
- no project-specific writing memory is created,
- the user receives a standardized mining summary.

View File

@@ -0,0 +1,11 @@
---
name: obsidian-ingest
description: Deprecated alias for `/kb-ingest`.
tags: [Research, Obsidian, Deprecated]
---
# /obsidian-ingest (deprecated)
Use `/kb-ingest` instead.
Keep the new `Sources/*` routing and do not recreate top-level `Papers/`.

View File

@@ -0,0 +1,11 @@
---
name: obsidian-init
description: Deprecated alias for `/kb-init`.
tags: [Research, Obsidian, Deprecated]
---
# /obsidian-init (deprecated)
Use `/kb-init` instead.
This alias keeps the new vault-first layout and should not recreate the legacy workflow.

View File

@@ -0,0 +1,11 @@
---
name: obsidian-link
description: Deprecated alias for `/kb-links`.
tags: [Research, Obsidian, Deprecated]
---
# /obsidian-link (deprecated)
Use `/kb-links` instead.
Repair links against the new canonical KB layout.

View File

@@ -0,0 +1,15 @@
---
name: obsidian-note
description: Deprecated alias for `/kb-log`, `/kb-promote`, or `/kb-archive` depending on note intent.
tags: [Research, Obsidian, Deprecated]
---
# /obsidian-note (deprecated)
Use one of these replacements instead:
- `/kb-log` for daily capture
- `/kb-promote` for canonicalization
- `/kb-archive` for note lifecycle actions such as archive, purge, or rename
Do not recreate the legacy note workflow.

View File

@@ -0,0 +1,14 @@
---
name: obsidian-notes
description: Deprecated alias for `/kb-promote` or `/kb-literature-review`.
tags: [Research, Obsidian, Deprecated]
---
# /obsidian-notes (deprecated)
Use one of these replacements instead:
- `/kb-promote` for promoting stable note content into canonical notes
- `/kb-literature-review` for literature normalization and synthesis
Keep the new project-scoped KB structure.

View File

@@ -0,0 +1,13 @@
---
name: obsidian-project
description: Deprecated alias for `/kb-status`, with `/kb-archive` for explicit lifecycle actions.
tags: [Research, Obsidian, Deprecated]
---
# /obsidian-project (deprecated)
Use `/kb-status` instead for the bound project overview.
If you need lifecycle actions, use `/kb-archive` explicitly.
Project archive means moving the whole project into `Research/_archived/`, not note-level `Archive/`.

View File

@@ -0,0 +1,11 @@
---
name: obsidian-review
description: Deprecated alias for `/kb-literature-review`.
tags: [Research, Obsidian, Deprecated]
---
# /obsidian-review (deprecated)
Use `/kb-literature-review` instead.
Keep the `Sources/Papers -> Knowledge / Writing / Maps/literature.canvas` workflow.

View File

@@ -0,0 +1,11 @@
---
name: obsidian-sync
description: Deprecated alias for `/kb-sync`.
tags: [Research, Obsidian, Deprecated]
---
# /obsidian-sync (deprecated)
Use `/kb-sync` instead.
This alias should follow the new project-scoped KB sync semantics.

View File

@@ -0,0 +1,11 @@
---
name: obsidian-views
description: Deprecated alias for `/kb-map`.
tags: [Research, Obsidian, Deprecated]
---
# /obsidian-views (deprecated)
Use `/kb-map` instead.
Additional canvas or `.base` artifacts remain explicit-only.

View File

@@ -0,0 +1,113 @@
---
description: Restate requirements, assess risks, and create step-by-step implementation plan. WAIT for user CONFIRM before touching any code.
---
# Plan Command
This command creates a comprehensive implementation plan before writing any code.
## What This Command Does
1. **Restate Requirements** - Clarify what needs to be built
2. **Identify Risks** - Surface potential issues and blockers
3. **Create Step Plan** - Break down implementation into phases
4. **Wait for Confirmation** - MUST receive user approval before proceeding
## When to Use
Use `/plan` when:
- Starting a new feature
- Making significant architectural changes
- Working on complex refactoring
- Multiple files/components will be affected
- Requirements are unclear or ambiguous
## How It Works
This command should:
1. **Analyze the request** and restate requirements in clear terms
2. **Break down into phases** with specific, actionable steps
3. **Identify dependencies** between components
4. **Assess risks** and potential blockers
5. **Estimate complexity** (High/Medium/Low)
6. **Present the plan** and WAIT for your explicit confirmation
## Example Usage
```
User: /plan I need to add real-time notifications when markets resolve
Assistant:
# Implementation Plan: Real-Time Market Resolution Notifications
## Requirements Restatement
- Send notifications to users when markets they're watching resolve
- Support multiple notification channels (in-app, email, webhook)
- Ensure notifications are delivered reliably
- Include market outcome and user's position result
## Implementation Phases
### Phase 1: Database Schema
- Add notifications table with columns: id, user_id, market_id, type, status, created_at
- Add user_notification_preferences table for channel preferences
- Create indexes on user_id and market_id for performance
### Phase 2: Notification Service
- Create notification service in lib/notifications.py
- Implement notification queue using Celery/Redis
- Add retry logic for failed deliveries
- Create notification templates (Jinja2)
### Phase 3: Integration Points
- Hook into market resolution logic (when status changes to "resolved")
- Query all users with positions in market
- Enqueue notifications for each user
### Phase 4: API/Frontend
- Create notification endpoints (GET /api/notifications, POST /api/notifications/read)
- WebSocket support for real-time updates
- Frontend notification bell component
- Notification preferences page
## Dependencies
- Redis (for Celery queue)
- Celery (task queue)
- Email service (SendGrid/Resend/SMTP)
- WebSocket server (channels/websocket)
## Risks
- HIGH: Email deliverability (SPF/DKIM required)
- MEDIUM: Performance with 1000+ users per market
- MEDIUM: Notification spam if markets resolve frequently
- LOW: WebSocket connection overhead
## Estimated Complexity: MEDIUM
- Backend: 4-6 hours
- API/Frontend: 3-4 hours
- Testing: 2-3 hours
- Total: 9-13 hours
**WAITING FOR CONFIRMATION**: Proceed with this plan? (yes/no/modify)
```
## Important Notes
**CRITICAL**: Do **NOT** write any code until the user explicitly confirms the plan with "yes" or "proceed" or a similar affirmative response.
If you want changes, respond with:
- "modify: [your changes]"
- "different approach: [alternative]"
- "skip phase 2 and do phase 3 first"
## Integration with Other Commands
After planning:
- Use `/tdd` to implement with test-driven development
- Use `/build-and-fix` if build errors occur
- Use `/code-review` to review completed implementation
## Related Skills
- `architecture-design` (when structural design is needed)

View File

@@ -0,0 +1,31 @@
---
name: poster
description: Design academic poster for conference
---
# Design Academic Poster
Use the post-acceptance skill to design an academic poster for your conference presentation.
## What this command does:
1. Guides you through poster design process
2. Provides layout templates and design guidelines
3. Helps with visual hierarchy and content organization
## Usage:
Simply run `/poster` and follow the prompts to design your academic poster.
The command will:
- Ask about poster size requirements (A0/A1)
- Suggest layout structure (3-4 columns)
- Provide design guidelines from `references/design-guidelines.md`
- Reference templates from `references/poster-templates/`
## Tips:
- Start designing 1-2 weeks before printing
- Use high-resolution images (300 DPI)
- Keep text concise and readable
- Print a test version before final printing

View File

@@ -0,0 +1,31 @@
---
name: presentation
description: Create conference presentation slides quickly
---
# Create Conference Presentation
Use the post-acceptance skill to create presentation slides for your accepted paper.
## What this command does:
1. Guides you through presentation slide creation
2. Provides templates and design guidelines
3. Helps with time management and content structure
## Usage:
Simply run `/presentation` and follow the prompts to create your conference presentation slides.
The command will:
- Ask about your presentation time limit
- Suggest slide structure
- Provide design guidelines from `references/design-guidelines.md`
- Reference templates from `references/presentation-templates/`
## Tips:
- Start preparing 2-3 weeks before the conference
- Practice your presentation multiple times
- Keep slides simple and visual
- Prepare backup PDF version

View File

@@ -0,0 +1,31 @@
---
name: promote
description: Generate promotion content for multiple platforms
---
# Generate Promotion Content
Use the post-acceptance skill to generate promotion content for your accepted paper across multiple platforms.
## What this command does:
1. Generates promotion content for Twitter/X, LinkedIn, blog, and news
2. Uses the generate-promotion.py script for automated content generation
3. Provides examples and best practices
## Usage:
Simply run `/promote` and follow the prompts to generate promotion content.
The command will:
- Ask about target platforms (Twitter, LinkedIn, Blog, News)
- Generate platform-specific content
- Provide examples from `references/promotion-examples/`
- Use `scripts/generate-promotion.py` for automation
## Tips:
- Prepare promotion content 1 week before conference
- Coordinate timing with conference schedule
- Use high-quality visuals
- Include links to paper and code

View File

@@ -0,0 +1,157 @@
---
name: rebuttal
description: Start systematic review response workflow for professional rebuttal writing
args:
review_file:
description: 审稿意见文件路径(可选)
required: false
---
# /rebuttal - 审稿响应工作流
启动系统化的rebuttal撰写流程从审稿意见分析到最终rebuttal文档生成。
## 用法
```bash
/rebuttal [review_file]
```
**参数**:
- `review_file` (可选): 包含审稿意见的文件路径
- 如果不提供,将引导用户提供审稿意见
## 功能
此命令将启动完整的rebuttal撰写工作流
1. **获取审稿意见** - 读取或接收审稿意见
2. **分析和分类** - 将意见拆成 atomic objections并分类为Major/Minor/Typo/Misunderstanding
3. **制定策略** - 为每条意见选择响应策略
4. **撰写rebuttal** - 生成结构化的回复文档
5. **语气优化** - 确保专业、礼貌的表达
6. **生成输出** - 保存最终的rebuttal文档
## 工作流程
### 步骤 1: 获取审稿意见
如果提供了`review_file`参数:
- 读取文件内容
- 识别审稿人数量和意见结构
如果未提供文件:
- 引导用户粘贴或描述审稿意见
- 确认审稿人数量
### 步骤 2: 分析和分类
优先使用`review-response` skill如果当前 runtime 提供 `rebuttal-writer` agent可以用它辅助分析
- 按审稿人分组意见
- 拆分每条 atomic objection
- 分类为Major/Minor/Typo/Misunderstanding
- 识别优先级
### 步骤 3: 制定响应策略
为每条意见选择策略:
- **Accept** - 接受并改进
- **Defend** - 礼貌辩护
- **Clarify** - 澄清误解
- **Experiment** - 补充实验
### 步骤 4: 撰写Rebuttal
生成结构化的回复:
- 为每条意见撰写Response和Changes
- 包含具体的位置引用
- 提供证据和理由
- 每条 response 必须包含 evidence anchorpaper location、result table、figure、analysis artifact、citation、Evidence Record ID、planned experiment status`unresolved`
### 步骤 5: 语气优化
检查和优化语气:
- 确保每个回复以感谢开始
- 避免防御性或攻击性表达
- 保持专业和尊重
### 步骤 6: 生成输出
保存最终文档:
- `rebuttal.md` - 完整的rebuttal文档
- `review-analysis.md` - 审稿意见分析(可选)
- `experiment-plan.md` - 补充实验计划(如果需要补充实验)
## 输出文件
执行此命令后,将生成以下文件:
### rebuttal.md
完整的rebuttal文档包含
- 开场白(感谢审稿人)
- 逐条回复Response + Changes
- 主要修改总结
### review-analysis.md可选
审稿意见分析文档,包含:
- 意见分类统计
- 策略选择说明
- 需要补充的实验列表
### experiment-plan.md可选
补充实验计划文档,包含:
- 需要补充的实验列表
- 每个实验的目的和预期结果
- 实验的优先级和时间估计
## 使用示例
### 示例 1: 提供审稿意见文件
```bash
/rebuttal reviews.txt
```
将读取`reviews.txt`文件中的审稿意见并启动rebuttal撰写流程。
### 示例 2: 交互式输入
```bash
/rebuttal
```
将引导你粘贴或描述审稿意见然后启动rebuttal撰写流程。
## 注意事项
### 重要原则
1. **覆盖优先** - 可以使用人工阅读或脚本辅助统计 atomic objections不要因为自然语言总结而漏掉具体意见
2. **保持专业语气** - 所有回复都要礼貌、尊重、有理有据
3. **提供具体证据** - 每个回复都要包含具体的位置引用和证据
4. **完整性检查** - 确保所有审稿意见都得到回应
### 参考资源
此命令会自动使用以下参考文档:
- `review-classification.md` - 意见分类标准
- `response-strategies.md` - 响应策略指南
- `rebuttal-templates.md` - 回复模板库
- `tone-guidelines.md` - 语气优化指南
### Agent调用
如果当前 runtime 提供 `rebuttal-writer` agent可以调用它来执行 rebuttal 撰写任务。若 agent 不可用,直接按 `review-response` skill 和本命令流程完成,不要阻塞。
## 相关命令
- `/commit` - 提交修改后的论文
- `/code-review` - 审查代码质量
---
**提示**: 使用此命令前,建议先准备好审稿意见文件,并确保已经完成论文的必要修改。

View File

@@ -0,0 +1,29 @@
# Refactor Clean
Safely identify and remove dead code with test verification:
1. Run dead code analysis tools:
- vulture: Find unused Python code (functions, classes, variables)
- pyflakes: Detect unused imports and variables
- ruff check --select F401: Find unused imports
- pip-audit: Check for security vulnerabilities
2. Generate comprehensive report in .reports/dead-code-analysis.md
3. Categorize findings by severity:
- SAFE: Test files, unused utilities, unused imports
- CAUTION: API routes, models, fixtures
- DANGER: Config files, main entry points, registry decorators
4. Propose safe deletions only
5. Before each deletion:
- Run full test suite (pytest)
- Verify tests pass
- Apply change
- Re-run tests
- Rollback if tests fail
6. Show summary of cleaned items
Never delete code without running tests first!

View File

@@ -0,0 +1,292 @@
---
name: research-init
description: Initialize a research project with Zotero-integrated literature review. Creates or audits project-scoped sources, generates research question cards, and only writes a research proposal when the evidence gate passes.
args:
- name: topic
description: Research topic or keywords
required: true
- name: scope
description: Review scope (focused/broad)
required: false
default: focused
- name: output_type
description: Output type (review/proposal/both). All modes produce research-question-card.md; references.bib is produced only when reliable citation metadata exists; review adds literature-review.md only when evidence is sufficient; proposal adds research-proposal.md only when the selected card passes the proposal readiness gate.
required: false
default: both
tags: [Research, Literature Review, Zotero, Paper Search]
---
# /research-init - Zotero-Integrated Research Startup Workflow
Launch a project-scoped literature startup workflow for the research topic "$topic", with scope "$scope" and output type "$output_type".
Default behavior is evidence-first: if Zotero is unavailable, if full-paper evidence is insufficient, or if the selected Research Question Card is not ready, produce an intake/audit result instead of forcing a polished proposal.
## Usage
### Basic Usage
```bash
/research-init "transformer interpretability"
```
### Specify Scope
```bash
/research-init "few-shot learning" focused
```
### Specify All Parameters
```bash
/research-init "neural architecture search" broad both
```
## Workflow
Execute the following steps in order:
### Step 0: Intake and Capability Gate
Before creating collections or writing files:
1. Confirm the practical purpose: new project intake, literature review, proposal draft, or source audit.
2. Check whether Zotero MCP is configured and writable.
3. If Zotero MCP is unavailable, read-only, or the user asks for dry-run mode:
- do **not** create collections,
- do **not** import papers,
- produce `research-question-card.md` and a source candidate/audit section,
- either skip `references.bib` or create a stub that clearly says canonical BibTeX is unavailable unless reliable BibTeX can be generated from existing sources,
- stop before `literature-review.md` or `research-proposal.md` unless the user explicitly provides sufficient local evidence.
4. If the topic, target venue/audience, or project boundary is ambiguous enough to change the search strategy, ask a short clarifying question before acting.
### Step 1: Create Zotero Research Collection
1. Call the Zotero MCP tool `zotero_create_collection` to create the main collection, named `Research-{Topic}-{YYYY-MM}` (extract a short PascalCase keyword from the topic, use the current year and month)
2. Create sub-collections under the main collection:
- `Core Papers`
- `Methods`
- `Applications`
- `Baselines`
- `To-Read`
3. Record the `collection_key` for each sub-collection (needed for import in Step 2)
### Step 2: Literature Search and Import
1. Use WebSearch to find papers related to "$topic"
- Search strategy: use the topic directly, plus variant combinations of key terms
- Target sources: arXiv, DOI-backed publisher landing pages, conference proceedings with full-paper pages, direct PDF pages
- Time range: focused mode searches the last 3 years, broad mode searches the last 5 years
- Target paper count: 20-50 papers for focused scope, 50-100 for broad scope
2. **Source quality filter before extraction**:
- Prefer candidates that expose at least one of: DOI, arXiv ID, direct PDF URL, or clear citation metadata for a full paper
- **Explicitly avoid abstract-only pages as primary sources** when a better source exists for the same paper (for example conference abstract listings, event schedule pages, teaser pages, or pages that only contain a short abstract with no DOI/arXiv/PDF)
- For the same title, source preference should be:
1. DOI-backed publisher page
2. arXiv abs/pdf page
3. direct PDF URL
4. full-paper proceedings landing page
5. abstract-only page (last resort only)
- If the discovered page is clearly abstract-only and no DOI/arXiv/PDF can be extracted, do **not** prioritize it for import; keep searching for a better source first
- Abstract-only pages should **not** be counted toward the target paper quota unless all better identifier-bearing/full-paper sources for that title have been exhausted
3. Extract candidate DOI / arXiv ID / landing-page URL from filtered search results
4. **Classify before import**: For each paper, determine which sub-collection it belongs to (Core Papers, Methods, Applications, Baselines, or To-Read) based on its title, abstract, and venue
5. **Pre-import deduplication (two-step)**:
- Call the Zotero MCP tool `zotero_search_items` with the DOI string when available to find potential matches
- Call `zotero_get_item_metadata` on results to confirm the DOI field matches exactly
- If confirmed match → skip import, log ("Already exists: {DOI} → {item_key}")
- For papers without DOI → search by title using token overlap ratio (lowercase both titles, remove punctuation, compute intersection of words / union of words). Ratio > 0.8 = duplicate
6. **Abstract-only page guardrail (mandatory)**:
- Before calling `zotero_add_items_by_identifier`, check whether the chosen URL is likely an abstract-only page
- Strong signals include: URL/path contains `abstract`, page title/heading is an abstract listing, page body lacks PDF/full-text links, and no DOI/arXiv identifier is visible
- If it is abstract-only **and** no DOI/arXiv/PDF can be recovered, prefer one of:
- keep searching for a better source for the same title, or
- skip this candidate for now
- Do **not** eagerly import abstract-only pages into analytical sub-collections just to satisfy paper count
- If an abstract-only page is imported as a last-resort placeholder, it must be treated as `To-Read` only, never as a confirmed paper source for `Core Papers`, `Methods`, `Applications`, or `Baselines`
- When you skip such a candidate during Step 2, print this exact user-facing line in the terminal output:
- `Skipped abstract-only page; searching better source`
7. **Smart import with collection assignment**: Call `zotero_add_items_by_identifier` with the target sub-collection's `collection_key`, `attach_pdf=true`, and `fallback_mode="webpage"`
- Route priority is fixed: DOI / doi.org URL → arXiv ID or arXiv URL → direct PDF URL → generic landing-page URL
- The tool will prefer proper paper/preprint items and only fall back to `webpage` when no reliable DOI/arXiv identifier is found
- For difficult publisher pages and cookie-gated PDFs, the import path may additionally use the local Zotero connector/browser session and optional Playwright-assisted PDF rescue before falling back to `webpage`
- The server records internal import events automatically for debugging, but that internal ledger is not part of the default public MCP tool surface and should not be part of the normal workflow
8. **Collection guardrail**: Only keep `paper` imports in `Core Papers`, `Methods`, `Applications`, or `Baselines`
- If the import result says `Saved as webpage`, move or create that entry only in `To-Read`
9. **PDF follow-up**: `zotero_add_items_by_identifier(..., attach_pdf=true)` already runs the PDF cascade by default. If the import result says `PDF not attached`, optionally call `zotero_find_and_attach_pdfs({ item_keys: [...] })` for a second pass. If it still fails, log it and continue.
10. **Automatic postpass dedupe/reconcile (mandatory)**: after the import batch, call `zotero_reconcile_collection_duplicates` on the main research collection with:
- `collection_key = {main research collection key}`
- `include_subcollections = true`
- `dry_run = false`
- `reconcile_local_only = true`
- `local_db_fallback = false`
- Goal: automatically clean duplicate parent items across the whole research collection tree, keep the canonical item with PDF when available, merge collection memberships, and remove stale duplicates when the standard APIs can handle them
- **Precondition**: destructive dedupe with `dry_run=false` requires Zotero MCP write/delete permission, which means `UNSAFE_OPERATIONS=items` must already be enabled
- **Default safety mode**: do **not** enable `local_db_fallback=true` automatically inside `/research-init`; only mention it in debug/recovery mode if residual duplicates remain after the standard pass
11. **Step-2 terminal summary (mandatory)**: after import + postpass dedupe, print a user-facing compact summary table:
```
| Input | Zotero Key | Collection | Status |
|-------|------------|------------|--------|
| ... | ABC123 | Core Papers | Imported as paper + PDF attached |
```
- `Status` should use only user-facing phrases:
- `Imported as paper + PDF attached`
- `Imported as paper`
- `Saved as webpage + PDF attached`
- `Saved as webpage`
- `Import failed`
- If a candidate was rejected before import because it is abstract-only and no DOI/arXiv/PDF could be recovered, print this standalone line before the table entry list continues:
- `Skipped abstract-only page; searching better source`
- After the table, print one compact dedupe line:
- `Collection dedupe summary: duplicate groups 0, duplicates trashed 0`
- or `Collection dedupe summary: duplicate groups N, duplicates trashed M`
- Then print one compact missing-PDF repair line:
- `Missing PDF postpass: repaired 0 items`
- or `Missing PDF postpass: repaired N items`
- Read these counts from the `zotero_reconcile_collection_duplicates` summary; do not invent them
- Do **not** print `route=...`, `pdf_source=...`, `fallback_reason=...`, `local_item_key=...`, or reconcile internals in the default terminal output
- Do **not** dump the raw dedupe markdown table in normal mode; read the tool result, extract the counts, and summarize it in one user-facing line
- If you need implementation details for debugging, explicitly say you are switching to debug mode and rerun with `ZOTERO_MCP_DEBUG_IMPORT=1`
**Note**: Zotero items can still be added to or removed from collections later, but `/research-init` should prefer correct `collection_key` assignment during import so analytical sub-collections stay clean. The default command path should now rely on `zotero_reconcile_collection_duplicates` as the standard postpass cleanup, not the older item-by-item local reconcile helper.
When in doubt between a full-paper source and an abstract-only page for the same title, always prefer the full-paper source, even if the abstract-only page ranks higher in search results. Use canonical Zotero MCP tool names consistently in this workflow: `zotero_create_collection`, `zotero_search_items`, `zotero_get_item_metadata`, `zotero_add_items_by_identifier`, `zotero_find_and_attach_pdfs`, and `zotero_reconcile_collection_duplicates`.
### Step 3: Paper Analysis
1. Call `zotero_get_collection_items` to list imported papers
2. Call `zotero_get_item_metadata` with `include_abstract: true` to get metadata and abstracts (ensures abstracts are available as fallback if full-text retrieval fails)
3. Call `zotero_get_item_fulltext` to read full text of papers with PDFs
3. For each paper, extract:
- Research question and motivation
- Core methodology
- Key findings and contributions
- Limitations and future work
4. Use these structured notes as intermediate analysis to inform the final `literature-review.md` (they are not a separate output file)
### Step 4: Gap Analysis and Synthesis
1. Analyze all collected papers for:
- Research trends and directions
- Methodological gaps
- Unexplored application domains
- Contradictions in research findings
2. Identify 2-3 concrete research gaps
3. Formulate 2-3 potential research questions as Research Question Cards:
```md
## Research Question Card
Question:
Type: exploratory | confirmatory | applied
Hypothesis:
Why it matters:
Current evidence:
Missing evidence:
What would support it:
What would falsify it:
Minimal next action:
Decision: explore | read more | run experiment | stop
```
4. Apply the **Proposal Readiness Gate** from `skills/research-ideation/references/research-contract.md`:
- at least one full-paper/preprint/dataset/experiment-artifact Evidence Record supports the selected direction,
- weak sources such as webpage placeholders or abstract-only notes are labeled as weak support,
- current evidence, missing evidence, support criteria, falsification criteria, and minimal next action are explicit.
5. Select one card as the default direction for `research-proposal.md` only if it passes this gate. If none is ready for a proposal, state that the next action is `read more` or `explore` instead of forcing a proposal narrative.
### Step 5: Generate Outputs
Generate corresponding files based on output_type "$output_type":
Output matrix:
| output_type | Always generated | Additional generated files |
|---|---|---|
| `review` | `research-question-card.md` | `references.bib` when reliable citation metadata exists; `literature-review.md` when evidence is sufficient |
| `proposal` | `research-question-card.md` | `references.bib` when reliable citation metadata exists; `research-proposal.md` if a selected card passes the gate |
| `both` | `research-question-card.md` | `references.bib` when reliable citation metadata exists; `literature-review.md` when evidence is sufficient; `research-proposal.md` if a selected card passes the gate |
File contracts:
1. **research-question-card.md** - 2-3 candidate Research Question Cards plus the selected default card and minimal next action
2. **literature-review.md** - Structured literature review with real citations from Zotero (generated for `review` and `both` only when the evidence base is sufficient)
3. **research-proposal.md** - Research proposal derived from the selected Research Question Card (generated for `proposal` and `both` only when the selected card passes the Proposal Readiness Gate)
4. **references.bib** - BibTeX references from Zotero data, generated only when reliable citation metadata exists
- **Primary method**: Use Zotero REST API with `?format=bibtex` to export accurate, complete BibTeX entries
```
GET https://api.zotero.org/users/{user_id}/collections/{collection_key}/items?format=bibtex
```
**Note**: The REST API `?format=bibtex` on a collection only exports items directly in that collection, not items in sub-collections. You must iterate each sub-collection key individually, or collect all item keys and use the items endpoint: `GET https://api.zotero.org/users/{user_id}/items?itemKey=KEY1,KEY2,...&format=bibtex`
- **Fallback**: Construct BibTeX manually from `zotero_get_item_metadata` metadata (note: volume, issue, pages, and publisher fields are not available via this tool — entries will be incomplete)
Use TodoWrite to track progress throughout the workflow.
At the end, summarize:
- selected question,
- current evidence,
- missing evidence,
- minimal next action,
- whether the next decision is `explore`, `read more`, `run experiment`, or `stop`.
## Error Handling
If the default Zotero MCP path fails during execution, use these workflow fallbacks:
1. **Zotero MCP unavailable or read-only** → Switch to dry-run/intake mode; do not create collections, import papers, or pretend references were saved.
2. **`zotero_create_collection` fails** → If REST credentials are configured and the user intended write mode, create via Zotero REST API directly; otherwise switch to dry-run/intake mode.
3. **`zotero_add_items_by_identifier` fails** → Retry with a narrower identifier (explicit DOI or arXiv ID). If the source is a publisher landing page or direct PDF, allow the smart importer to use connector/browser-session rescue and optional Playwright-assisted PDF rescue first. If smart import still fails, use an out-of-band fallback such as CrossRef metadata lookup (`https://api.crossref.org/works/{DOI}`) and retry the DOI-specific path or save the page as a manual `webpage`.
4. **`zotero_get_item_fulltext` fails** → Use `WebFetch` on the paper's DOI URL to scrape abstract → fall back to `abstractNote` from `zotero_get_item_metadata` + domain knowledge
5. **`zotero_find_and_attach_pdfs` fails** → Log and continue; PDFs are not required for analysis. If a needed paper still lacks a PDF, ask the user to attach it manually in Zotero Desktop and rerun analysis later.
6. **`zotero_reconcile_collection_duplicates` fails** → Keep the import results, log that postpass dedupe failed, and continue with analysis. In debug mode, inspect the tool's summary and consider rerunning with `local_db_fallback=true` only if local-only duplicates remain and the user explicitly wants aggressive cleanup.
7. **Single paper fails** → Log error, skip, and continue to next paper
8. **API rate limit** → Wait 5 seconds and retry, up to 3 attempts
## Completion Checklist
Before finishing, verify:
- [ ] Zotero write mode or dry-run/intake mode explicitly stated
- [ ] In write mode, Zotero collection `Research-{Topic}-{YYYY-MM}` created with sub-collections
- [ ] In write mode, papers imported and organized into sub-collections (target: 20-50 focused / 50-100 broad)
- [ ] In write mode, PDFs attached for available open-access papers
- [ ] Full-text analysis completed for core papers when available; otherwise source limitations are explicit
- [ ] Gap analysis identifies at least 2-3 concrete research gaps
- [ ] Research Question Cards generated with support criteria, falsification criteria, and minimal next action
- [ ] Proposal Readiness Gate applied before generating `research-proposal.md`
- [ ] Output files generated according to the output matrix for `review`, `proposal`, or `both`
- [ ] All citations in review correspond to actual Zotero library entries
## Possible Output Files
The command may generate the following files according to the output matrix and evidence gates:
```
{project_dir}/
├── research-question-card.md # Candidate questions, hypotheses, evidence needs, and selected next action
├── literature-review.md # Structured literature review when evidence is sufficient
├── research-proposal.md # Research proposal (if requested and evidence gate passes)
└── references.bib # BibTeX references when reliable citation metadata exists
```
## Integration Notes
This command will:
1. Use **Zotero MCP** tools to manage literature collections and metadata
2. Trigger the **literature-reviewer agent** for literature analysis
3. Use the **research-ideation skill** methodology (5W1H, Gap Analysis)
4. Search for latest papers via **WebSearch**
## Notes
- Ensure the Zotero MCP service is properly configured and running
- DOI import depends on network connectivity and Zotero's metadata resolution capability
- PDF attachment is limited to open-access papers; paywalled papers must be added manually
- Generated literature reviews and research proposals require manual review and refinement
## Related Resources
- **Skill**: `research-ideation` - Research ideation methodology
- **Agent**: `literature-reviewer` - Literature search and analysis
- **Commands**: `/zotero-review` - Analyze existing Zotero collections, `/zotero-notes` - Batch generate reading notes

View File

@@ -0,0 +1,22 @@
# SuperClaude Commands
This directory contains slash commands that are installed to `~/.claude/commands/sc/` when users run `superclaude install`.
## Available Commands
- **agent.md** - Specialized AI agents
- **index-repo.md** - Repository indexing for context optimization
- **recommend.md** - Command recommendations
- **research.md** - Deep web research with parallel search
- **sc.md** - Show all available SuperClaude commands
## Important
These commands are copies from `plugins/superclaude/commands/` for package distribution.
When updating commands:
1. Edit files in `plugins/superclaude/commands/`
2. Copy changes to `src/superclaude/commands/`
3. Both locations must stay in sync
In v5.0, the plugin system will use `plugins/` directly.

View File

@@ -0,0 +1,71 @@
name: sc:agent
description: SC Agent — session controller that orchestrates investigation, implementation, and review
category: orchestration
personas: []
---
# SC Agent Activation
🚀 **SC Agent online** — this plugin launches `/sc:agent` automatically at session start.
## Startup Checklist (keep output terse)
1. `git status --porcelain` → announce `📊 Git: clean|X files|not a repo`.
2. Remind the user: `💡 Use /context to confirm token budget.`
3. Report core services: confidence check, deep research, repository index.
Stop here until the user describes the task. Stay silent otherwise.
---
## Task Protocol
When the user assigns a task the SuperClaude Agent owns the entire workflow:
1. **Clarify scope**
- Confirm success criteria, blockers, and constraints.
- Capture any acceptance tests that matter.
2. **Plan investigation**
- Use parallel tool calls where possible.
- Reach for the following helpers instead of inventing bespoke commands:
- `@confidence-check` skill (pre-implementation score ≥0.90 required).
- `@deep-research` agent (web/MCP research).
- `@repo-index` agent (repository structure + file shortlist).
- `@self-review` agent (post-implementation validation).
3. **Iterate until confident**
- Track confidence from the skill results; do not implement below 0.90.
- Escalate to the user if confidence stalls or new context is required.
4. **Implementation wave**
- Prepare edits as a single checkpoint summary.
- Prefer grouped apply_patch/file edits over many tiny actions.
- Run the agreed test command(s) after edits.
5. **Self-review and reflexion**
- Invoke `@self-review` to double-check outcomes.
- Share residual risks or follow-up tasks.
Deliver concise updates at the end of each major phase. Avoid repeating background facts already established earlier in the session.
---
## Tooling Guidance
- **Repository awareness**: call `@repo-index` on the first task per session or whenever the codebase drifts.
- **Research**: delegate open questions or external lookup to `@deep-research` before speculating.
- **Confidence tracking**: log the latest score whenever it changes so the user can see progress.
If a tool or MCP server is unavailable, note the failure, fall back to native Claude techniques, and flag the gap for follow-up.
---
## Token Discipline
- Use short status messages (`🔄 Investigating…`, `📊 Confidence: 0.82`).
- Collapse redundant summaries; prefer links to prior answers.
- Archive long briefs in memory tools only if the user requests persistence.
---
The SuperClaude Agent is responsible for keeping the user out of the loop on busywork. Accept tasks, orchestrate helpers, and return with validated results.

View File

@@ -0,0 +1,98 @@
---
name: analyze
description: "Comprehensive code analysis across quality, security, performance, and architecture domains"
category: utility
complexity: basic
mcp-servers: []
personas: []
---
# /sc:analyze - Code Analysis and Quality Assessment
## Triggers
- Code quality assessment requests for projects or specific components
- Security vulnerability scanning and compliance validation needs
- Performance bottleneck identification and optimization planning
- Architecture review and technical debt assessment requirements
## Usage
```
/sc:analyze [target] [--focus quality|security|performance|architecture] [--depth quick|deep] [--format text|json|report]
```
## Behavioral Flow
1. **Discover**: Categorize source files using language detection and project analysis
2. **Scan**: Apply domain-specific analysis techniques and pattern matching
3. **Evaluate**: Generate prioritized findings with severity ratings and impact assessment
4. **Recommend**: Create actionable recommendations with implementation guidance
5. **Report**: Present comprehensive analysis with metrics and improvement roadmap
Key behaviors:
- Multi-domain analysis combining static analysis and heuristic evaluation
- Intelligent file discovery and language-specific pattern recognition
- Severity-based prioritization of findings and recommendations
- Comprehensive reporting with metrics, trends, and actionable insights
## Tool Coordination
- **Glob**: File discovery and project structure analysis
- **Grep**: Pattern analysis and code search operations
- **Read**: Source code inspection and configuration analysis
- **Bash**: External analysis tool execution and validation
- **Write**: Report generation and metrics documentation
## Key Patterns
- **Domain Analysis**: Quality/Security/Performance/Architecture → specialized assessment
- **Pattern Recognition**: Language detection → appropriate analysis techniques
- **Severity Assessment**: Issue classification → prioritized recommendations
- **Report Generation**: Analysis results → structured documentation
## Examples
### Comprehensive Project Analysis
```
/sc:analyze
# Multi-domain analysis of entire project
# Generates comprehensive report with key findings and roadmap
```
### Focused Security Assessment
```
/sc:analyze src/auth --focus security --depth deep
# Deep security analysis of authentication components
# Vulnerability assessment with detailed remediation guidance
```
### Performance Optimization Analysis
```
/sc:analyze --focus performance --format report
# Performance bottleneck identification
# Generates HTML report with optimization recommendations
```
### Quick Quality Check
```
/sc:analyze src/components --focus quality --depth quick
# Rapid quality assessment of component directory
# Identifies code smells and maintainability issues
```
## Boundaries
**Will:**
- Perform comprehensive static code analysis across multiple domains
- Generate severity-rated findings with actionable recommendations
- Provide detailed reports with metrics and improvement guidance
**Will Not:**
- Execute dynamic analysis requiring code compilation or runtime
- Modify source code or apply fixes without explicit user consent
- Analyze external dependencies beyond import and usage patterns
**Output**: Analysis report containing:
- Severity-rated findings
- Code quality metrics
- Security vulnerabilities
- Performance issues
- Recommendations
**Next Step**: After review, use `/sc:improve` to apply recommended fixes or `/sc:cleanup` for dead code removal.

View File

@@ -0,0 +1,122 @@
---
name: brainstorm
description: "Interactive requirements discovery through Socratic dialogue and systematic exploration"
category: orchestration
complexity: advanced
mcp-servers: [sequential, context7, magic, playwright, morphllm, serena]
personas: [architect, analyzer, frontend, backend, security, devops, project-manager]
---
# /sc:brainstorm - Interactive Requirements Discovery
> **Context Framework Note**: This file provides behavioral instructions for Claude Code when users type `/sc:brainstorm` patterns. This is NOT an executable command - it's a context trigger that activates the behavioral patterns defined below.
## Triggers
- Ambiguous project ideas requiring structured exploration
- Requirements discovery and specification development needs
- Concept validation and feasibility assessment requests
- Cross-session brainstorming and iterative refinement scenarios
## Context Trigger Pattern
```
/sc:brainstorm [topic/idea] [--strategy systematic|agile|enterprise] [--depth shallow|normal|deep] [--parallel]
```
**Usage**: Type this pattern in your Claude Code conversation to activate brainstorming behavioral mode with systematic exploration and multi-persona coordination.
## Behavioral Flow
1. **Explore**: Transform ambiguous ideas through Socratic dialogue and systematic questioning
2. **Analyze**: Coordinate multiple personas for domain expertise and comprehensive analysis
3. **Validate**: Apply feasibility assessment and requirement validation across domains
4. **Specify**: Generate concrete specifications with cross-session persistence capabilities
5. **Handoff**: Create actionable briefs ready for implementation or further development
Key behaviors:
- Multi-persona orchestration across architecture, analysis, frontend, backend, security domains
- Advanced MCP coordination with intelligent routing for specialized analysis
- Systematic execution with progressive dialogue enhancement and parallel exploration
- Cross-session persistence with comprehensive requirements discovery documentation
## MCP Integration
- **Sequential MCP**: Complex multi-step reasoning for systematic exploration and validation
- **Context7 MCP**: Framework-specific feasibility assessment and pattern analysis
- **Magic MCP**: UI/UX feasibility and design system integration analysis
- **Playwright MCP**: User experience validation and interaction pattern testing
- **Morphllm MCP**: Large-scale content analysis and pattern-based transformation
- **Serena MCP**: Cross-session persistence, memory management, and project context enhancement
## Tool Coordination
- **Read/Write/Edit**: Requirements documentation and specification generation
- **TodoWrite**: Progress tracking for complex multi-phase exploration
- **Task**: Advanced delegation for parallel exploration paths and multi-agent coordination
- **WebSearch**: Market research, competitive analysis, and technology validation
- **sequentialthinking**: Structured reasoning for complex requirements analysis
## Key Patterns
- **Socratic Dialogue**: Question-driven exploration → systematic requirements discovery
- **Multi-Domain Analysis**: Cross-functional expertise → comprehensive feasibility assessment
- **Progressive Coordination**: Systematic exploration → iterative refinement and validation
- **Specification Generation**: Concrete requirements → actionable implementation briefs
## Examples
### Systematic Product Discovery
```
/sc:brainstorm "AI-powered project management tool" --strategy systematic --depth deep
# Multi-persona analysis: architect (system design), analyzer (feasibility), project-manager (requirements)
# Sequential MCP provides structured exploration framework
```
### Agile Feature Exploration
```
/sc:brainstorm "real-time collaboration features" --strategy agile --parallel
# Parallel exploration paths with frontend, backend, and security personas
# Context7 and Magic MCP for framework and UI pattern analysis
```
### Enterprise Solution Validation
```
/sc:brainstorm "enterprise data analytics platform" --strategy enterprise --validate
# Comprehensive validation with security, devops, and architect personas
# Serena MCP for cross-session persistence and enterprise requirements tracking
```
### Cross-Session Refinement
```
/sc:brainstorm "mobile app monetization strategy" --depth normal
# Serena MCP manages cross-session context and iterative refinement
# Progressive dialogue enhancement with memory-driven insights
```
## Boundaries
**Will:**
- Transform ambiguous ideas into concrete specifications through systematic exploration
- Coordinate multiple personas and MCP servers for comprehensive analysis
- Provide cross-session persistence and progressive dialogue enhancement
**Will Not:**
- Make implementation decisions without proper requirements discovery
- Override user vision with prescriptive solutions during exploration phase
- Bypass systematic exploration for complex multi-domain projects
## CRITICAL BOUNDARIES
**STOP AFTER REQUIREMENTS DISCOVERY**
This command produces a REQUIREMENTS SPECIFICATION ONLY.
**Explicitly Will NOT**:
- Create architecture diagrams or system designs (use `/sc:design`)
- Generate implementation code (use `/sc:implement`)
- Make architectural decisions
- Design database schemas or API contracts
- Create technical specifications beyond requirements
**Output**: Requirements document with:
- Clarified user goals
- Functional requirements
- Non-functional requirements
- User stories / acceptance criteria
- Open questions for user
**Next Step**: After brainstorm completes, use `/sc:design` for architecture or `/sc:workflow` for implementation planning.

View File

@@ -0,0 +1,94 @@
---
name: build
description: "Build, compile, and package projects with intelligent error handling and optimization"
category: utility
complexity: enhanced
mcp-servers: [playwright]
personas: [devops-engineer]
---
# /sc:build - Project Building and Packaging
## Triggers
- Project compilation and packaging requests for different environments
- Build optimization and artifact generation needs
- Error debugging during build processes
- Deployment preparation and artifact packaging requirements
## Usage
```
/sc:build [target] [--type dev|prod|test] [--clean] [--optimize] [--verbose]
```
## Behavioral Flow
1. **Analyze**: Project structure, build configurations, and dependency manifests
2. **Validate**: Build environment, dependencies, and required toolchain components
3. **Execute**: Build process with real-time monitoring and error detection
4. **Optimize**: Build artifacts, apply optimizations, and minimize bundle sizes
5. **Package**: Generate deployment artifacts and comprehensive build reports
Key behaviors:
- Configuration-driven build orchestration with dependency validation
- Intelligent error analysis with actionable resolution guidance
- Environment-specific optimization (dev/prod/test configurations)
- Comprehensive build reporting with timing metrics and artifact analysis
## MCP Integration
- **Playwright MCP**: Auto-activated for build validation and UI testing during builds
- **DevOps Engineer Persona**: Activated for build optimization and deployment preparation
- **Enhanced Capabilities**: Build pipeline integration, performance monitoring, artifact validation
## Tool Coordination
- **Bash**: Build system execution and process management
- **Read**: Configuration analysis and manifest inspection
- **Grep**: Error parsing and build log analysis
- **Glob**: Artifact discovery and validation
- **Write**: Build reports and deployment documentation
## Key Patterns
- **Environment Builds**: dev/prod/test → appropriate configuration and optimization
- **Error Analysis**: Build failures → diagnostic analysis and resolution guidance
- **Optimization**: Artifact analysis → size reduction and performance improvements
- **Validation**: Build verification → quality gates and deployment readiness
## Examples
### Standard Project Build
```
/sc:build
# Builds entire project using default configuration
# Generates artifacts and comprehensive build report
```
### Production Optimization Build
```
/sc:build --type prod --clean --optimize
# Clean production build with advanced optimizations
# Minification, tree-shaking, and deployment preparation
```
### Targeted Component Build
```
/sc:build frontend --verbose
# Builds specific project component with detailed output
# Real-time progress monitoring and diagnostic information
```
### Development Build with Validation
```
/sc:build --type dev --validate
# Development build with Playwright validation
# UI testing and build verification integration
```
## Boundaries
**Will:**
- Execute project build systems using existing configurations
- Provide comprehensive error analysis and optimization recommendations
- Generate deployment-ready artifacts with detailed reporting
**Will Not:**
- Modify build system configuration or create new build scripts
- Install missing build dependencies or development tools
- Execute deployment operations beyond artifact preparation

View File

@@ -0,0 +1,113 @@
# /sc:business-panel - Business Panel Analysis System
```yaml
---
command: "/sc:business-panel"
category: "Analysis & Strategic Planning"
purpose: "Multi-expert business analysis with adaptive interaction modes"
wave-enabled: true
performance-profile: "complex"
---
```
## Overview
AI facilitated panel discussion between renowned business thought leaders analyzing documents through their distinct frameworks and methodologies.
## Expert Panel
### Available Experts
- **Clayton Christensen**: Disruption Theory, Jobs-to-be-Done
- **Michael Porter**: Competitive Strategy, Five Forces
- **Peter Drucker**: Management Philosophy, MBO
- **Seth Godin**: Marketing Innovation, Tribe Building
- **W. Chan Kim & Renée Mauborgne**: Blue Ocean Strategy
- **Jim Collins**: Organizational Excellence, Good to Great
- **Nassim Nicholas Taleb**: Risk Management, Antifragility
- **Donella Meadows**: Systems Thinking, Leverage Points
- **Jean-luc Doumont**: Communication Systems, Structured Clarity
## Analysis Modes
### Phase 1: DISCUSSION (Default)
Collaborative analysis where experts build upon each other's insights through their frameworks.
### Phase 2: DEBATE
Adversarial analysis activated when experts disagree or for controversial topics.
### Phase 3: SOCRATIC INQUIRY
Question-driven exploration for deep learning and strategic thinking development.
## Usage
### Basic Usage
```bash
/sc:business-panel [document_path_or_content]
```
### Advanced Options
```bash
/sc:business-panel [content] --experts "porter,christensen,meadows"
/sc:business-panel [content] --mode debate
/sc:business-panel [content] --focus "competitive-analysis"
/sc:business-panel [content] --synthesis-only
```
### Mode Commands
- `--mode discussion` - Collaborative analysis (default)
- `--mode debate` - Challenge and stress-test ideas
- `--mode socratic` - Question-driven exploration
- `--mode adaptive` - System selects based on content
### Expert Selection
- `--experts "name1,name2,name3"` - Select specific experts
- `--focus domain` - Auto-select experts for domain
- `--all-experts` - Include all 9 experts
### Output Options
- `--synthesis-only` - Skip detailed analysis, show synthesis
- `--structured` - Use symbol system for efficiency
- `--verbose` - Full detailed analysis
- `--questions` - Focus on strategic questions
## Auto-Persona Activation
- **Auto-Activates**: Analyzer, Architect, Mentor personas
- **MCP Integration**: Sequential (primary), Context7 (business patterns)
- **Tool Orchestration**: Read, Grep, Write, MultiEdit, TodoWrite
## Integration Notes
- Compatible with all thinking flags (--think, --think-hard, --ultrathink)
- Supports wave orchestration for comprehensive business analysis
- Integrates with scribe persona for professional business communication
## CRITICAL BOUNDARIES
**SYNTHESIS OUTPUT ONLY - NOT IMPLEMENTATION**
This command produces EXPERT ANALYSIS and RECOMMENDATIONS only.
**Default behavior**:
- Assemble expert panel
- Conduct analysis/discussion
- **STOP with synthesis document** - do not implement recommendations
**Completion Criteria**:
- All relevant experts have contributed
- Consensus or disagreements documented
- Actionable recommendations provided
**Explicitly Will NOT**:
- Implement any business recommendations
- Make code or architectural changes
- Execute decisions without user approval
**Output**: Business analysis document containing:
- Expert perspectives (9 simulated experts)
- Consensus points
- Disagreements with reasoning
- Priority-ranked recommendations
**Next Step**: User reviews recommendations, then:
- Use `/sc:design` for architectural changes
- Use `/sc:implement` for feature development
- Use `/sc:workflow` for planning

View File

@@ -0,0 +1,112 @@
---
name: cleanup
description: "Systematically clean up code, remove dead code, and optimize project structure"
category: workflow
complexity: standard
mcp-servers: [sequential, context7]
personas: [architect, quality, security]
---
# /sc:cleanup - Code and Project Cleanup
## Triggers
- Code maintenance and technical debt reduction requests
- Dead code removal and import optimization needs
- Project structure improvement and organization requirements
- Codebase hygiene and quality improvement initiatives
## Usage
```
/sc:cleanup [target] [--type code|imports|files|all] [--safe|--aggressive] [--interactive]
```
## Behavioral Flow
1. **Analyze**: Assess cleanup opportunities and safety considerations across target scope
2. **Plan**: Choose cleanup approach and activate relevant personas for domain expertise
3. **Execute**: Apply systematic cleanup with intelligent dead code detection and removal
4. **Validate**: Ensure no functionality loss through testing and safety verification
5. **Report**: Generate cleanup summary with recommendations for ongoing maintenance
Key behaviors:
- Multi-persona coordination (architect, quality, security) based on cleanup type
- Framework-specific cleanup patterns via Context7 MCP integration
- Systematic analysis via Sequential MCP for complex cleanup operations
- Safety-first approach with backup and rollback capabilities
## MCP Integration
- **Sequential MCP**: Auto-activated for complex multi-step cleanup analysis and planning
- **Context7 MCP**: Framework-specific cleanup patterns and best practices
- **Persona Coordination**: Architect (structure), Quality (debt), Security (credentials)
## Tool Coordination
- **Read/Grep/Glob**: Code analysis and pattern detection for cleanup opportunities
- **Edit/MultiEdit**: Safe code modification and structure optimization
- **TodoWrite**: Progress tracking for complex multi-file cleanup operations
- **Task**: Delegation for large-scale cleanup workflows requiring systematic coordination
## Key Patterns
- **Dead Code Detection**: Usage analysis → safe removal with dependency validation
- **Import Optimization**: Dependency analysis → unused import removal and organization
- **Structure Cleanup**: Architectural analysis → file organization and modular improvements
- **Safety Validation**: Pre/during/post checks → preserve functionality throughout cleanup
## Examples
### Safe Code Cleanup
```
/sc:cleanup src/ --type code --safe
# Conservative cleanup with automatic safety validation
# Removes dead code while preserving all functionality
```
### Import Optimization
```
/sc:cleanup --type imports --preview
# Analyzes and shows unused import cleanup without execution
# Framework-aware optimization via Context7 patterns
```
### Comprehensive Project Cleanup
```
/sc:cleanup --type all --interactive
# Multi-domain cleanup with user guidance for complex decisions
# Activates all personas for comprehensive analysis
```
### Framework-Specific Cleanup
```
/sc:cleanup components/ --aggressive
# Thorough cleanup with Context7 framework patterns
# Sequential analysis for complex dependency management
```
## Boundaries
**Will:**
- Systematically clean code, remove dead code, and optimize project structure
- Provide comprehensive safety validation with backup and rollback capabilities
- Apply intelligent cleanup algorithms with framework-specific pattern recognition
**Will Not:**
- Remove code without thorough safety analysis and validation
- Override project-specific cleanup exclusions or architectural constraints
- Apply cleanup operations that compromise functionality or introduce bugs
## AUTO-FIX VS APPROVAL-REQUIRED
**Auto-fix (applies automatically)**:
- Unused imports removal
- Dead code with zero references
- Empty blocks removal
- Redundant type annotations
**Approval Required (prompts user first)**:
- Code with indirect references
- Exports potentially used externally
- Test fixtures/utilities
- Configuration values
**Safety Threshold**:
- If code has ANY usage path, prompt user
- If code affects public API, prompt user
- If unsure, prompt user

View File

@@ -0,0 +1,96 @@
---
name: design
description: "Design system architecture, APIs, and component interfaces with comprehensive specifications"
category: utility
complexity: basic
mcp-servers: []
personas: []
---
# /sc:design - System and Component Design
## Triggers
- Architecture planning and system design requests
- API specification and interface design needs
- Component design and technical specification requirements
- Database schema and data model design requests
## Usage
```
/sc:design [target] [--type architecture|api|component|database] [--format diagram|spec|code]
```
## Behavioral Flow
1. **Analyze**: Examine target requirements and existing system context
2. **Plan**: Define design approach and structure based on type and format
3. **Design**: Create comprehensive specifications with industry best practices
4. **Validate**: Ensure design meets requirements and maintainability standards
5. **Document**: Generate clear design documentation with diagrams and specifications
Key behaviors:
- Requirements-driven design approach with scalability considerations
- Industry best practices integration for maintainable solutions
- Multi-format output (diagrams, specifications, code) based on needs
- Validation against existing system architecture and constraints
## Tool Coordination
- **Read**: Requirements analysis and existing system examination
- **Grep/Glob**: Pattern analysis and system structure investigation
- **Write**: Design documentation and specification generation
- **Bash**: External design tool integration when needed
## Key Patterns
- **Architecture Design**: Requirements → system structure → scalability planning
- **API Design**: Interface specification → RESTful/GraphQL patterns → documentation
- **Component Design**: Functional requirements → interface design → implementation guidance
- **Database Design**: Data requirements → schema design → relationship modeling
## Examples
### System Architecture Design
```
/sc:design user-management-system --type architecture --format diagram
# Creates comprehensive system architecture with component relationships
# Includes scalability considerations and best practices
```
### API Specification Design
```
/sc:design payment-api --type api --format spec
# Generates detailed API specification with endpoints and data models
# Follows RESTful design principles and industry standards
```
### Component Interface Design
```
/sc:design notification-service --type component --format code
# Designs component interfaces with clear contracts and dependencies
# Provides implementation guidance and integration patterns
```
### Database Schema Design
```
/sc:design e-commerce-db --type database --format diagram
# Creates database schema with entity relationships and constraints
# Includes normalization and performance considerations
```
## Boundaries
**Will:**
- Create comprehensive design specifications with industry best practices
- Generate multiple format outputs (diagrams, specs, code) based on requirements
- Validate designs against maintainability and scalability standards
**Will Not:**
- Generate actual implementation code (use /sc:implement for implementation)
- Modify existing system architecture without explicit design approval
- Create designs that violate established architectural constraints
**Output**: Architecture documents containing:
- System diagrams (component, sequence, data flow)
- API specifications
- Database schemas
- Interface definitions
**Next Step**: After design is approved, use `/sc:implement` to build the designed components.

View File

@@ -0,0 +1,88 @@
---
name: document
description: "Generate focused documentation for components, functions, APIs, and features"
category: utility
complexity: basic
mcp-servers: []
personas: []
---
# /sc:document - Focused Documentation Generation
## Triggers
- Documentation requests for specific components, functions, or features
- API documentation and reference material generation needs
- Code comment and inline documentation requirements
- User guide and technical documentation creation requests
## Usage
```
/sc:document [target] [--type inline|external|api|guide] [--style brief|detailed]
```
## Behavioral Flow
1. **Analyze**: Examine target component structure, interfaces, and functionality
2. **Identify**: Determine documentation requirements and target audience context
3. **Generate**: Create appropriate documentation content based on type and style
4. **Format**: Apply consistent structure and organizational patterns
5. **Integrate**: Ensure compatibility with existing project documentation ecosystem
Key behaviors:
- Code structure analysis with API extraction and usage pattern identification
- Multi-format documentation generation (inline, external, API reference, guides)
- Consistent formatting and cross-reference integration
- Language-specific documentation patterns and conventions
## Tool Coordination
- **Read**: Component analysis and existing documentation review
- **Grep**: Reference extraction and pattern identification
- **Write**: Documentation file creation with proper formatting
- **Glob**: Multi-file documentation projects and organization
## Key Patterns
- **Inline Documentation**: Code analysis → JSDoc/docstring generation → inline comments
- **API Documentation**: Interface extraction → reference material → usage examples
- **User Guides**: Feature analysis → tutorial content → implementation guidance
- **External Docs**: Component overview → detailed specifications → integration instructions
## Examples
### Inline Code Documentation
```
/sc:document src/auth/login.js --type inline
# Generates JSDoc comments with parameter and return descriptions
# Adds comprehensive inline documentation for functions and classes
```
### API Reference Generation
```
/sc:document src/api --type api --style detailed
# Creates comprehensive API documentation with endpoints and schemas
# Generates usage examples and integration guidelines
```
### User Guide Creation
```
/sc:document payment-module --type guide --style brief
# Creates user-focused documentation with practical examples
# Focuses on implementation patterns and common use cases
```
### Component Documentation
```
/sc:document components/ --type external
# Generates external documentation files for component library
# Includes props, usage examples, and integration patterns
```
## Boundaries
**Will:**
- Generate focused documentation for specific components and features
- Create multiple documentation formats based on target audience needs
- Integrate with existing documentation ecosystems and maintain consistency
**Will Not:**
- Generate documentation without proper code analysis and context understanding
- Override existing documentation standards or project-specific conventions
- Create documentation that exposes sensitive implementation details

View File

@@ -0,0 +1,107 @@
---
name: estimate
description: "Provide development estimates for tasks, features, or projects with intelligent analysis"
category: special
complexity: standard
mcp-servers: [sequential, context7]
personas: [architect, performance, project-manager]
---
# /sc:estimate - Development Estimation
## Triggers
- Development planning requiring time, effort, or complexity estimates
- Project scoping and resource allocation decisions
- Feature breakdown needing systematic estimation methodology
- Risk assessment and confidence interval analysis requirements
## Usage
```
/sc:estimate [target] [--type time|effort|complexity] [--unit hours|days|weeks] [--breakdown]
```
## Behavioral Flow
1. **Analyze**: Examine scope, complexity factors, dependencies, and framework patterns
2. **Calculate**: Apply estimation methodology with historical benchmarks and complexity scoring
3. **Validate**: Cross-reference estimates with project patterns and domain expertise
4. **Present**: Provide detailed breakdown with confidence intervals and risk assessment
5. **Track**: Document estimation accuracy for continuous methodology improvement
Key behaviors:
- Multi-persona coordination (architect, performance, project-manager) based on estimation scope
- Sequential MCP integration for systematic analysis and complexity assessment
- Context7 MCP integration for framework-specific patterns and historical benchmarks
- Intelligent breakdown analysis with confidence intervals and risk factors
## MCP Integration
- **Sequential MCP**: Complex multi-step estimation analysis and systematic complexity assessment
- **Context7 MCP**: Framework-specific estimation patterns and historical benchmark data
- **Persona Coordination**: Architect (design complexity), Performance (optimization effort), Project Manager (timeline)
## Tool Coordination
- **Read/Grep/Glob**: Codebase analysis for complexity assessment and scope evaluation
- **TodoWrite**: Estimation breakdown and progress tracking for complex estimation workflows
- **Task**: Advanced delegation for multi-domain estimation requiring systematic coordination
- **Bash**: Project analysis and dependency evaluation for accurate complexity scoring
## Key Patterns
- **Scope Analysis**: Project requirements → complexity factors → framework patterns → risk assessment
- **Estimation Methodology**: Time-based → Effort-based → Complexity-based → Cost-based approaches
- **Multi-Domain Assessment**: Architecture complexity → Performance requirements → Project timeline
- **Validation Framework**: Historical benchmarks → cross-validation → confidence intervals → accuracy tracking
## Examples
### Feature Development Estimation
```
/sc:estimate "user authentication system" --type time --unit days --breakdown
# Systematic analysis: Database design (2 days) + Backend API (3 days) + Frontend UI (2 days) + Testing (1 day)
# Total: 8 days with 85% confidence interval
```
### Project Complexity Assessment
```
/sc:estimate "migrate monolith to microservices" --type complexity --breakdown
# Architecture complexity analysis with risk factors and dependency mapping
# Multi-persona coordination for comprehensive assessment
```
### Performance Optimization Effort
```
/sc:estimate "optimize application performance" --type effort --unit hours
# Performance persona analysis with benchmark comparisons
# Effort breakdown by optimization category and expected impact
```
## Boundaries
**Will:**
- Provide systematic development estimates with confidence intervals and risk assessment
- Apply multi-persona coordination for comprehensive complexity analysis
- Generate detailed breakdown analysis with historical benchmark comparisons
**Will Not:**
- Guarantee estimate accuracy without proper scope analysis and validation
- Provide estimates without appropriate domain expertise and complexity assessment
- Override historical benchmarks without clear justification and analysis
## CRITICAL BOUNDARIES
**STOP AFTER ESTIMATION**
This command produces an ESTIMATION REPORT ONLY - no implementation.
**Explicitly Will NOT**:
- Execute work based on estimates
- Create implementation timelines for execution
- Start implementation tasks
- Make commitments on behalf of user
**Output**: Estimation report containing:
- Time/effort breakdown
- Complexity analysis
- Confidence intervals
- Risk assessment
- Resource requirements
**Next Step**: After estimation, user decides on timeline. Use `/sc:workflow` for planning or `/sc:implement` for execution.

View File

@@ -0,0 +1,92 @@
---
name: explain
description: "Provide clear explanations of code, concepts, and system behavior with educational clarity"
category: workflow
complexity: standard
mcp-servers: [sequential, context7]
personas: [educator, architect, security]
---
# /sc:explain - Code and Concept Explanation
## Triggers
- Code understanding and documentation requests for complex functionality
- System behavior explanation needs for architectural components
- Educational content generation for knowledge transfer
- Framework-specific concept clarification requirements
## Usage
```
/sc:explain [target] [--level basic|intermediate|advanced] [--format text|examples|interactive] [--context domain]
```
## Behavioral Flow
1. **Analyze**: Examine target code, concept, or system for comprehensive understanding
2. **Assess**: Determine audience level and appropriate explanation depth and format
3. **Structure**: Plan explanation sequence with progressive complexity and logical flow
4. **Generate**: Create clear explanations with examples, diagrams, and interactive elements
5. **Validate**: Verify explanation accuracy and educational effectiveness
Key behaviors:
- Multi-persona coordination for domain expertise (educator, architect, security)
- Framework-specific explanations via Context7 integration
- Systematic analysis via Sequential MCP for complex concept breakdown
- Adaptive explanation depth based on audience and complexity
## MCP Integration
- **Sequential MCP**: Auto-activated for complex multi-component analysis and structured reasoning
- **Context7 MCP**: Framework documentation and official pattern explanations
- **Persona Coordination**: Educator (learning), Architect (systems), Security (practices)
## Tool Coordination
- **Read/Grep/Glob**: Code analysis and pattern identification for explanation content
- **TodoWrite**: Progress tracking for complex multi-part explanations
- **Task**: Delegation for comprehensive explanation workflows requiring systematic breakdown
## Key Patterns
- **Progressive Learning**: Basic concepts → intermediate details → advanced implementation
- **Framework Integration**: Context7 documentation → accurate official patterns and practices
- **Multi-Domain Analysis**: Technical accuracy + educational clarity + security awareness
- **Interactive Explanation**: Static content → examples → interactive exploration
## Examples
### Basic Code Explanation
```
/sc:explain authentication.js --level basic
# Clear explanation with practical examples for beginners
# Educator persona provides learning-optimized structure
```
### Framework Concept Explanation
```
/sc:explain react-hooks --level intermediate --context react
# Context7 integration for official React documentation patterns
# Structured explanation with progressive complexity
```
### System Architecture Explanation
```
/sc:explain microservices-system --level advanced --format interactive
# Architect persona explains system design and patterns
# Interactive exploration with Sequential analysis breakdown
```
### Security Concept Explanation
```
/sc:explain jwt-authentication --context security --level basic
# Security persona explains authentication concepts and best practices
# Framework-agnostic security principles with practical examples
```
## Boundaries
**Will:**
- Provide clear, comprehensive explanations with educational clarity
- Auto-activate relevant personas for domain expertise and accurate analysis
- Generate framework-specific explanations with official documentation integration
**Will Not:**
- Generate explanations without thorough analysis and accuracy verification
- Override project-specific documentation standards or reveal sensitive details
- Bypass established explanation validation or educational quality requirements

View File

@@ -0,0 +1,80 @@
---
name: git
description: "Git operations with intelligent commit messages and workflow optimization"
category: utility
complexity: basic
mcp-servers: []
personas: []
---
# /sc:git - Git Operations
## Triggers
- Git repository operations: status, add, commit, push, pull, branch
- Need for intelligent commit message generation
- Repository workflow optimization requests
- Branch management and merge operations
## Usage
```
/sc:git [operation] [args] [--smart-commit] [--interactive]
```
## Behavioral Flow
1. **Analyze**: Check repository state and working directory changes
2. **Validate**: Ensure operation is appropriate for current Git context
3. **Execute**: Run Git command with intelligent automation
4. **Optimize**: Apply smart commit messages and workflow patterns
5. **Report**: Provide status and next steps guidance
Key behaviors:
- Generate conventional commit messages based on change analysis
- Apply consistent branch naming conventions
- Handle merge conflicts with guided resolution
- Provide clear status summaries and workflow recommendations
## Tool Coordination
- **Bash**: Git command execution and repository operations
- **Read**: Repository state analysis and configuration review
- **Grep**: Log parsing and status analysis
- **Write**: Commit message generation and documentation
## Key Patterns
- **Smart Commits**: Analyze changes → generate conventional commit message
- **Status Analysis**: Repository state → actionable recommendations
- **Branch Strategy**: Consistent naming and workflow enforcement
- **Error Recovery**: Conflict resolution and state restoration guidance
## Examples
### Smart Status Analysis
```
/sc:git status
# Analyzes repository state with change summary
# Provides next steps and workflow recommendations
```
### Intelligent Commit
```
/sc:git commit --smart-commit
# Generates conventional commit message from change analysis
# Applies best practices and consistent formatting
```
### Interactive Operations
```
/sc:git merge feature-branch --interactive
# Guided merge with conflict resolution assistance
```
## Boundaries
**Will:**
- Execute Git operations with intelligent automation
- Generate conventional commit messages from change analysis
- Provide workflow optimization and best practice guidance
**Will Not:**
- Modify repository configuration without explicit authorization
- Execute destructive operations without confirmation
- Handle complex merges requiring manual intervention

View File

@@ -0,0 +1,148 @@
---
name: help
description: "List all available /sc commands and their functionality"
category: utility
complexity: low
mcp-servers: []
personas: []
---
# /sc:help - Command Reference Documentation
## Triggers
- Command discovery and reference lookup requests
- Framework exploration and capability understanding needs
- Documentation requests for available SuperClaude commands
## Behavioral Flow
1. **Display**: Present complete command list with descriptions
2. **Complete**: End interaction after displaying information
Key behaviors:
- Information display only - no execution or implementation
- Reference documentation mode without action triggers
Here is a complete list of all available SuperClaude (`/sc`) commands.
| Command | Description |
|---|---|
| `/sc:analyze` | Comprehensive code analysis across quality, security, performance, and architecture domains |
| `/sc:brainstorm` | Interactive requirements discovery through Socratic dialogue and systematic exploration |
| `/sc:build` | Build, compile, and package projects with intelligent error handling and optimization |
| `/sc:business-panel` | Multi-expert business analysis with adaptive interaction modes |
| `/sc:cleanup` | Systematically clean up code, remove dead code, and optimize project structure |
| `/sc:design` | Design system architecture, APIs, and component interfaces with comprehensive specifications |
| `/sc:document` | Generate focused documentation for components, functions, APIs, and features |
| `/sc:estimate` | Provide development estimates for tasks, features, or projects with intelligent analysis |
| `/sc:explain` | Provide clear explanations of code, concepts, and system behavior with educational clarity |
| `/sc:git` | Git operations with intelligent commit messages and workflow optimization |
| `/sc:help` | List all available /sc commands and their functionality |
| `/sc:implement` | Feature and code implementation with intelligent persona activation and MCP integration |
| `/sc:improve` | Apply systematic improvements to code quality, performance, and maintainability |
| `/sc:index` | Generate comprehensive project documentation and knowledge base with intelligent organization |
| `/sc:load` | Session lifecycle management with Serena MCP integration for project context loading |
| `/sc:reflect` | Task reflection and validation using Serena MCP analysis capabilities |
| `/sc:save` | Session lifecycle management with Serena MCP integration for session context persistence |
| `/sc:select-tool` | Intelligent MCP tool selection based on complexity scoring and operation analysis |
| `/sc:spawn` | Meta-system task orchestration with intelligent breakdown and delegation |
| `/sc:spec-panel` | Multi-expert specification review and improvement using renowned specification and software engineering experts |
| `/sc:task` | Execute complex tasks with intelligent workflow management and delegation |
| `/sc:test` | Execute tests with coverage analysis and automated quality reporting |
| `/sc:troubleshoot` | Diagnose and resolve issues in code, builds, deployments, and system behavior |
| `/sc:workflow` | Generate structured implementation workflows from PRDs and feature requirements |
## SuperClaude Framework Flags
SuperClaude supports behavioral flags to enable specific execution modes and tool selection patterns. Use these flags with any `/sc` command to customize behavior.
### Mode Activation Flags
| Flag | Trigger | Behavior |
|------|---------|----------|
| `--brainstorm` | Vague project requests, exploration keywords | Activate collaborative discovery mindset, ask probing questions |
| `--introspect` | Self-analysis requests, error recovery | Expose thinking process with transparency markers |
| `--task-manage` | Multi-step operations (>3 steps) | Orchestrate through delegation, systematic organization |
| `--orchestrate` | Multi-tool operations, parallel execution | Optimize tool selection matrix, enable parallel thinking |
| `--token-efficient` | Context usage >75%, large-scale operations | Symbol-enhanced communication, 30-50% token reduction |
### MCP Server Flags
| Flag | Trigger | Behavior |
|------|---------|----------|
| `--c7` / `--context7` | Library imports, framework questions | Enable Context7 for curated documentation lookup |
| `--seq` / `--sequential` | Complex debugging, system design | Enable Sequential for structured multi-step reasoning |
| `--magic` | UI component requests (/ui, /21) | Enable Magic for modern UI generation from 21st.dev |
| `--morph` / `--morphllm` | Bulk code transformations | Enable Morphllm for efficient multi-file pattern application |
| `--serena` | Symbol operations, project memory | Enable Serena for semantic understanding and session persistence |
| `--play` / `--playwright` | Browser testing, E2E scenarios | Enable Playwright for real browser automation and testing |
| `--all-mcp` | Maximum complexity scenarios | Enable all MCP servers for comprehensive capability |
| `--no-mcp` | Native-only execution needs | Disable all MCP servers, use native tools |
### Analysis Depth Flags
| Flag | Trigger | Behavior |
|------|---------|----------|
| `--think` | Multi-component analysis needs | Standard structured analysis (~4K tokens), enables Sequential |
| `--think-hard` | Architectural analysis, system-wide dependencies | Deep analysis (~10K tokens), enables Sequential + Context7 |
| `--ultrathink` | Critical system redesign, legacy modernization | Maximum depth analysis (~32K tokens), enables all MCP servers |
### Execution Control Flags
| Flag | Trigger | Behavior |
|------|---------|----------|
| `--delegate [auto\|files\|folders]` | >7 directories OR >50 files | Enable sub-agent parallel processing with intelligent routing |
| `--concurrency [n]` | Resource optimization needs | Control max concurrent operations (range: 1-15) |
| `--loop` | Improvement keywords (polish, refine, enhance) | Enable iterative improvement cycles with validation gates |
| `--iterations [n]` | Specific improvement cycle requirements | Set improvement cycle count (range: 1-10) |
| `--validate` | Risk score >0.7, resource usage >75% | Pre-execution risk assessment and validation gates |
| `--safe-mode` | Resource usage >85%, production environment | Maximum validation, conservative execution |
### Output Optimization Flags
| Flag | Trigger | Behavior |
|------|---------|----------|
| `--uc` / `--ultracompressed` | Context pressure, efficiency requirements | Symbol communication system, 30-50% token reduction |
| `--scope [file\|module\|project\|system]` | Analysis boundary needs | Define operational scope and analysis depth |
| `--focus [performance\|security\|quality\|architecture\|accessibility\|testing]` | Domain-specific optimization | Target specific analysis domain and expertise application |
### Flag Priority Rules
- **Safety First**: `--safe-mode` > `--validate` > optimization flags
- **Explicit Override**: User flags > auto-detection
- **Depth Hierarchy**: `--ultrathink` > `--think-hard` > `--think`
- **MCP Control**: `--no-mcp` overrides all individual MCP flags
- **Scope Precedence**: system > project > module > file
### Usage Examples
```bash
# Deep analysis with Context7 enabled
/sc:analyze --think-hard --context7 src/
# UI development with Magic and validation
/sc:implement --magic --validate "Add user dashboard"
# Token-efficient task management
/sc:task --token-efficient --delegate auto "Refactor authentication system"
# Safe production deployment
/sc:build --safe-mode --validate --focus security
```
## Boundaries
**Will:**
- Display comprehensive list of available SuperClaude commands
- Provide clear descriptions of each command's functionality
- Present information in readable tabular format
- Show all available SuperClaude framework flags and their usage
- Provide flag usage examples and priority rules
**Will Not:**
- Execute any commands or create any files
- Activate implementation modes or start projects
- Engage TodoWrite or any execution tools
---
**Note:** This list is manually generated and may become outdated. If you suspect it is inaccurate, please consider regenerating it or contacting a maintainer.

View File

@@ -0,0 +1,111 @@
---
name: implement
description: "Feature and code implementation with intelligent persona activation and MCP integration"
category: workflow
complexity: standard
mcp-servers: [context7, sequential, magic, playwright]
personas: [architect, frontend, backend, security, qa-specialist]
---
# /sc:implement - Feature Implementation
> **Context Framework Note**: This behavioral instruction activates when Claude Code users type `/sc:implement` patterns. It guides Claude to coordinate specialist personas and MCP tools for comprehensive implementation.
## Triggers
- Feature development requests for components, APIs, or complete functionality
- Code implementation needs with framework-specific requirements
- Multi-domain development requiring coordinated expertise
- Implementation projects requiring testing and validation integration
## Context Trigger Pattern
```
/sc:implement [feature-description] [--type component|api|service|feature] [--framework react|vue|express] [--safe] [--with-tests]
```
**Usage**: Type this in Claude Code conversation to activate implementation behavioral mode with coordinated expertise and systematic development approach.
## Behavioral Flow
1. **Analyze**: Examine implementation requirements and detect technology context
2. **Plan**: Choose approach and activate relevant personas for domain expertise
3. **Generate**: Create implementation code with framework-specific best practices
4. **Validate**: Apply security and quality validation throughout development
5. **Integrate**: Update documentation and provide testing recommendations
Key behaviors:
- Context-based persona activation (architect, frontend, backend, security, qa)
- Framework-specific implementation via Context7 and Magic MCP integration
- Systematic multi-component coordination via Sequential MCP
- Comprehensive testing integration with Playwright for validation
## MCP Integration
- **Context7 MCP**: Framework patterns and official documentation for React, Vue, Angular, Express
- **Magic MCP**: Auto-activated for UI component generation and design system integration
- **Sequential MCP**: Complex multi-step analysis and implementation planning
- **Playwright MCP**: Testing validation and quality assurance integration
## Tool Coordination
- **Write/Edit/MultiEdit**: Code generation and modification for implementation
- **Read/Grep/Glob**: Project analysis and pattern detection for consistency
- **TodoWrite**: Progress tracking for complex multi-file implementations
- **Task**: Delegation for large-scale feature development requiring systematic coordination
## Key Patterns
- **Context Detection**: Framework/tech stack → appropriate persona and MCP activation
- **Implementation Flow**: Requirements → code generation → validation → integration
- **Multi-Persona Coordination**: Frontend + Backend + Security → comprehensive solutions
- **Quality Integration**: Implementation → testing → documentation → validation
## Examples
### React Component Implementation
```
/sc:implement user profile component --type component --framework react
# Magic MCP generates UI component with design system integration
# Frontend persona ensures best practices and accessibility
```
### API Service Implementation
```
/sc:implement user authentication API --type api --safe --with-tests
# Backend persona handles server-side logic and data processing
# Security persona ensures authentication best practices
```
### Full-Stack Feature
```
/sc:implement payment processing system --type feature --with-tests
# Multi-persona coordination: architect, frontend, backend, security
# Sequential MCP breaks down complex implementation steps
```
### Framework-Specific Implementation
```
/sc:implement dashboard widget --framework vue
# Context7 MCP provides Vue-specific patterns and documentation
# Framework-appropriate implementation with official best practices
```
## Boundaries
**Will:**
- Implement features with intelligent persona activation and MCP coordination
- Apply framework-specific best practices and security validation
- Provide comprehensive implementation with testing and documentation integration
**Will Not:**
- Make architectural decisions without appropriate persona consultation
- Implement features conflicting with security policies or architectural constraints
- Override user-specified safety constraints or bypass quality gates
## COMPLETION CRITERIA
**Implementation is DONE when**:
- Feature code is written and compiles
- Basic functionality verified
- Files saved and ready for testing
**Post-Implementation Checklist**:
1. Code compiles without errors
2. Basic functionality works
3. Ready for `/sc:test`
**Next Step**: After implementation, use `/sc:test` to run tests, then `/sc:git` to commit.

View File

@@ -0,0 +1,113 @@
---
name: improve
description: "Apply systematic improvements to code quality, performance, and maintainability"
category: workflow
complexity: standard
mcp-servers: [sequential, context7]
personas: [architect, performance, quality, security]
---
# /sc:improve - Code Improvement
## Triggers
- Code quality enhancement and refactoring requests
- Performance optimization and bottleneck resolution needs
- Maintainability improvements and technical debt reduction
- Best practices application and coding standards enforcement
## Usage
```
/sc:improve [target] [--type quality|performance|maintainability|style] [--safe] [--interactive]
```
## Behavioral Flow
1. **Analyze**: Examine codebase for improvement opportunities and quality issues
2. **Plan**: Choose improvement approach and activate relevant personas for expertise
3. **Execute**: Apply systematic improvements with domain-specific best practices
4. **Validate**: Ensure improvements preserve functionality and meet quality standards
5. **Document**: Generate improvement summary and recommendations for future work
Key behaviors:
- Multi-persona coordination (architect, performance, quality, security) based on improvement type
- Framework-specific optimization via Context7 integration for best practices
- Systematic analysis via Sequential MCP for complex multi-component improvements
- Safe refactoring with comprehensive validation and rollback capabilities
## MCP Integration
- **Sequential MCP**: Auto-activated for complex multi-step improvement analysis and planning
- **Context7 MCP**: Framework-specific best practices and optimization patterns
- **Persona Coordination**: Architect (structure), Performance (speed), Quality (maintainability), Security (safety)
## Tool Coordination
- **Read/Grep/Glob**: Code analysis and improvement opportunity identification
- **Edit/MultiEdit**: Safe code modification and systematic refactoring
- **TodoWrite**: Progress tracking for complex multi-file improvement operations
- **Task**: Delegation for large-scale improvement workflows requiring systematic coordination
## Key Patterns
- **Quality Improvement**: Code analysis → technical debt identification → refactoring application
- **Performance Optimization**: Profiling analysis → bottleneck identification → optimization implementation
- **Maintainability Enhancement**: Structure analysis → complexity reduction → documentation improvement
- **Security Hardening**: Vulnerability analysis → security pattern application → validation verification
## Examples
### Code Quality Enhancement
```
/sc:improve src/ --type quality --safe
# Systematic quality analysis with safe refactoring application
# Improves code structure, reduces technical debt, enhances readability
```
### Performance Optimization
```
/sc:improve api-endpoints --type performance --interactive
# Performance persona analyzes bottlenecks and optimization opportunities
# Interactive guidance for complex performance improvement decisions
```
### Maintainability Improvements
```
/sc:improve legacy-modules --type maintainability --preview
# Architect persona analyzes structure and suggests maintainability improvements
# Preview mode shows changes before application for review
```
### Security Hardening
```
/sc:improve auth-service --type security --validate
# Security persona identifies vulnerabilities and applies security patterns
# Comprehensive validation ensures security improvements are effective
```
## Boundaries
**Will:**
- Apply systematic improvements with domain-specific expertise and validation
- Provide comprehensive analysis with multi-persona coordination and best practices
- Execute safe refactoring with rollback capabilities and quality preservation
**Will Not:**
- Apply risky improvements without proper analysis and user confirmation
- Make architectural changes without understanding full system impact
- Override established coding standards or project-specific conventions
## AUTO-FIX VS APPROVAL-REQUIRED
**Auto-fix (applies automatically)**:
- Style fixes (formatting, naming conventions)
- Unused variable removal
- Import organization
- Simple type annotations
**Approval Required (prompts user first)**:
- Architectural changes
- Logic refactoring
- Function signature changes
- Removing code used by public APIs
- Changes affecting multiple files
**Explicitly Will NOT** (without `--force` flag):
- Make architectural decisions
- Refactor code structure without confirmation
- Remove functionality

View File

@@ -0,0 +1,165 @@
---
name: sc:index-repo
description: Repository Indexing - 94% token reduction (58K → 3K)
---
# Repository Index Creator
📊 **Index Creator activated**
## Problem Statement
**Before**: Reading all files → 58,000 tokens every session
**After**: Read PROJECT_INDEX.md → 3,000 tokens (94% reduction)
## Index Creation Flow
### Phase 1: Analyze Repository Structure
**Parallel analysis** (5 concurrent Glob searches):
1. **Code Structure**
```
src/**/*.{ts,py,js,tsx,jsx}
lib/**/*.{ts,py,js}
superclaude/**/*.py
```
2. **Documentation**
```
docs/**/*.md
*.md (root level)
README*.md
```
3. **Configuration**
```
*.toml
*.yaml, *.yml
*.json (exclude package-lock, node_modules)
```
4. **Tests**
```
tests/**/*.{py,ts,js}
**/*.test.{ts,py,js}
**/*.spec.{ts,py,js}
```
5. **Scripts & Tools**
```
scripts/**/*
bin/**/*
tools/**/*
```
### Phase 2: Extract Metadata
For each file category, extract:
- Entry points (main.py, index.ts, cli.py)
- Key modules and exports
- API surface (public functions/classes)
- Dependencies (imports, requires)
### Phase 3: Generate Index
Create `PROJECT_INDEX.md` with structure:
```markdown
# Project Index: {project_name}
Generated: {timestamp}
## 📁 Project Structure
{tree view of main directories}
## 🚀 Entry Points
- CLI: {path} - {description}
- API: {path} - {description}
- Tests: {path} - {description}
## 📦 Core Modules
### Module: {name}
- Path: {path}
- Exports: {list}
- Purpose: {1-line description}
## 🔧 Configuration
- {config_file}: {purpose}
## 📚 Documentation
- {doc_file}: {topic}
## 🧪 Test Coverage
- Unit tests: {count} files
- Integration tests: {count} files
- Coverage: {percentage}%
## 🔗 Key Dependencies
- {dependency}: {version} - {purpose}
## 📝 Quick Start
1. {setup step}
2. {run step}
3. {test step}
```
### Phase 4: Validation
Quality checks:
- [ ] All entry points identified?
- [ ] Core modules documented?
- [ ] Index size < 5KB?
- [ ] Human-readable format?
---
## Usage
**Create index**:
```
/index-repo
```
**Update existing index**:
```
/index-repo mode=update
```
**Quick index (skip tests)**:
```
/index-repo mode=quick
```
---
## Token Efficiency
**ROI Calculation**:
- Index creation: 2,000 tokens (one-time)
- Index reading: 3,000 tokens (every session)
- Full codebase read: 58,000 tokens (every session)
**Break-even**: 1 session
**10 sessions savings**: 550,000 tokens
**100 sessions savings**: 5,500,000 tokens
---
## Output Format
Creates two files:
1. `PROJECT_INDEX.md` (3KB, human-readable)
2. `PROJECT_INDEX.json` (10KB, machine-readable)
---
**Index Creator is now active.** Run to analyze current repository.

View File

@@ -0,0 +1,86 @@
---
name: index
description: "Generate comprehensive project documentation and knowledge base with intelligent organization"
category: special
complexity: standard
mcp-servers: [sequential, context7]
personas: [architect, scribe, quality]
---
# /sc:index - Project Documentation
## Triggers
- Project documentation creation and maintenance requirements
- Knowledge base generation and organization needs
- API documentation and structure analysis requirements
- Cross-referencing and navigation enhancement requests
## Usage
```
/sc:index [target] [--type docs|api|structure|readme] [--format md|json|yaml]
```
## Behavioral Flow
1. **Analyze**: Examine project structure and identify key documentation components
2. **Organize**: Apply intelligent organization patterns and cross-referencing strategies
3. **Generate**: Create comprehensive documentation with framework-specific patterns
4. **Validate**: Ensure documentation completeness and quality standards
5. **Maintain**: Update existing documentation while preserving manual additions and customizations
Key behaviors:
- Multi-persona coordination (architect, scribe, quality) based on documentation scope and complexity
- Sequential MCP integration for systematic analysis and comprehensive documentation workflows
- Context7 MCP integration for framework-specific patterns and documentation standards
- Intelligent organization with cross-referencing capabilities and automated maintenance
## MCP Integration
- **Sequential MCP**: Complex multi-step project analysis and systematic documentation generation
- **Context7 MCP**: Framework-specific documentation patterns and established standards
- **Persona Coordination**: Architect (structure), Scribe (content), Quality (validation)
## Tool Coordination
- **Read/Grep/Glob**: Project structure analysis and content extraction for documentation generation
- **Write**: Documentation creation with intelligent organization and cross-referencing
- **TodoWrite**: Progress tracking for complex multi-component documentation workflows
- **Task**: Advanced delegation for large-scale documentation requiring systematic coordination
## Key Patterns
- **Structure Analysis**: Project examination → component identification → logical organization → cross-referencing
- **Documentation Types**: API docs → Structure docs → README → Knowledge base approaches
- **Quality Validation**: Completeness assessment → accuracy verification → standard compliance → maintenance planning
- **Framework Integration**: Context7 patterns → official standards → best practices → consistency validation
## Examples
### Project Structure Documentation
```
/sc:index project-root --type structure --format md
# Comprehensive project structure documentation with intelligent organization
# Creates navigable structure with cross-references and component relationships
```
### API Documentation Generation
```
/sc:index src/api --type api --format json
# API documentation with systematic analysis and validation
# Scribe and quality personas ensure completeness and accuracy
```
### Knowledge Base Creation
```
/sc:index . --type docs
# Interactive knowledge base generation with project-specific patterns
# Architect persona provides structural organization and cross-referencing
```
## Boundaries
**Will:**
- Generate comprehensive project documentation with intelligent organization and cross-referencing
- Apply multi-persona coordination for systematic analysis and quality validation
- Provide framework-specific patterns and established documentation standards
**Will Not:**
- Override existing manual documentation without explicit update permission
- Generate documentation without appropriate project structure analysis and validation
- Bypass established documentation standards or quality requirements

View File

@@ -0,0 +1,93 @@
---
name: load
description: "Session lifecycle management with Serena MCP integration for project context loading"
category: session
complexity: standard
mcp-servers: [serena]
personas: []
---
# /sc:load - Project Context Loading
## Triggers
- Session initialization and project context loading requests
- Cross-session persistence and memory retrieval needs
- Project activation and context management requirements
- Session lifecycle management and checkpoint loading scenarios
## Usage
```
/sc:load [target] [--type project|config|deps|checkpoint] [--refresh] [--analyze]
```
## Behavioral Flow
1. **Initialize**: Establish Serena MCP connection and session context management
2. **Discover**: Analyze project structure and identify context loading requirements
3. **Load**: Retrieve project memories, checkpoints, and cross-session persistence data
4. **Activate**: Establish project context and prepare for development workflow
5. **Validate**: Ensure loaded context integrity and session readiness
Key behaviors:
- Serena MCP integration for memory management and cross-session persistence
- Project activation with comprehensive context loading and validation
- Performance-critical operation with <500ms initialization target
- Session lifecycle management with checkpoint and memory coordination
## MCP Integration
- **Serena MCP**: Mandatory integration for project activation, memory retrieval, and session management
- **Memory Operations**: Cross-session persistence, checkpoint loading, and context restoration
- **Performance Critical**: <200ms for core operations, <1s for checkpoint creation
## Tool Coordination
- **activate_project**: Core project activation and context establishment
- **list_memories/read_memory**: Memory retrieval and session context loading
- **Read/Grep/Glob**: Project structure analysis and configuration discovery
- **Write**: Session context documentation and checkpoint creation
## Key Patterns
- **Project Activation**: Directory analysis → memory retrieval → context establishment
- **Session Restoration**: Checkpoint loading → context validation → workflow preparation
- **Memory Management**: Cross-session persistence → context continuity → development efficiency
- **Performance Critical**: Fast initialization → immediate productivity → session readiness
## Examples
### Basic Project Loading
```
/sc:load
# Loads current directory project context with Serena memory integration
# Establishes session context and prepares for development workflow
```
### Specific Project Loading
```
/sc:load /path/to/project --type project --analyze
# Loads specific project with comprehensive analysis
# Activates project context and retrieves cross-session memories
```
### Checkpoint Restoration
```
/sc:load --type checkpoint --checkpoint session_123
# Restores specific checkpoint with session context
# Continues previous work session with full context preservation
```
### Dependency Context Loading
```
/sc:load --type deps --refresh
# Loads dependency context with fresh analysis
# Updates project understanding and dependency mapping
```
## Boundaries
**Will:**
- Load project context using Serena MCP integration for memory management
- Provide session lifecycle management with cross-session persistence
- Establish project activation with comprehensive context loading
**Will Not:**
- Modify project structure or configuration without explicit permission
- Load context without proper Serena MCP integration and validation
- Override existing session context without checkpoint preservation

View File

@@ -0,0 +1,592 @@
---
name: pm
description: "Project Manager Agent - Default orchestration agent that coordinates all sub-agents and manages workflows seamlessly"
category: orchestration
complexity: meta
mcp-servers: [sequential, context7, magic, playwright, morphllm, serena, tavily, chrome-devtools]
personas: [pm-agent]
---
# /sc:pm - Project Manager Agent (Always Active)
> **Always-Active Foundation Layer**: PM Agent is NOT a mode - it's the DEFAULT operating foundation that runs automatically at every session start. Users never need to manually invoke it; PM Agent seamlessly orchestrates all interactions with continuous context preservation across sessions.
## Auto-Activation Triggers
- **Session Start (MANDATORY)**: ALWAYS activates to restore context via Serena MCP memory
- **All User Requests**: Default entry point for all interactions unless explicit sub-agent override
- **State Questions**: "どこまで進んでた", "現状", "進捗" trigger context report
- **Vague Requests**: "作りたい", "実装したい", "どうすれば" trigger discovery mode
- **Multi-Domain Tasks**: Cross-functional coordination requiring multiple specialists
- **Complex Projects**: Systematic planning and PDCA cycle execution
## Context Trigger Pattern
```
# Default (no command needed - PM Agent handles all interactions)
"Build authentication system for my app"
# Explicit PM Agent invocation (optional)
/sc:pm [request] [--strategy brainstorm|direct|wave] [--verbose]
# Override to specific sub-agent (optional)
/sc:implement "user profile" --agent backend
```
## Session Lifecycle (Serena MCP Memory Integration)
### Session Start Protocol (Auto-Executes Every Time)
```yaml
1. Context Restoration:
- list_memories() → Check for existing PM Agent state
- read_memory("pm_context") → Restore overall context
- read_memory("current_plan") → What are we working on
- read_memory("last_session") → What was done previously
- read_memory("next_actions") → What to do next
2. Report to User:
"前回: [last session summary]
進捗: [current progress status]
今回: [planned next actions]
課題: [blockers or issues]"
3. Ready for Work:
User can immediately continue from last checkpoint
No need to re-explain context or goals
```
### During Work (Continuous PDCA Cycle)
```yaml
1. Plan (仮説):
- write_memory("plan", goal_statement)
- Create docs/temp/hypothesis-YYYY-MM-DD.md
- Define what to implement and why
2. Do (実験):
- TodoWrite for task tracking
- write_memory("checkpoint", progress) every 30min
- Update docs/temp/experiment-YYYY-MM-DD.md
- Record試行錯誤, errors, solutions
3. Check (評価):
- think_about_task_adherence() → Self-evaluation
- "何がうまくいった?何が失敗?"
- Update docs/temp/lessons-YYYY-MM-DD.md
- Assess against goals
4. Act (改善):
- Success → docs/patterns/[pattern-name].md (清書)
- Failure → docs/mistakes/mistake-YYYY-MM-DD.md (防止策)
- Update CLAUDE.md if global pattern
- write_memory("summary", outcomes)
```
### Session End Protocol
```yaml
1. Final Checkpoint:
- think_about_whether_you_are_done()
- write_memory("last_session", summary)
- write_memory("next_actions", todo_list)
2. Documentation Cleanup:
- Move docs/temp/ → docs/patterns/ or docs/mistakes/
- Update formal documentation
- Remove outdated temporary files
3. State Preservation:
- write_memory("pm_context", complete_state)
- Ensure next session can resume seamlessly
```
## Behavioral Flow
1. **Request Analysis**: Parse user intent, classify complexity, identify required domains
2. **Strategy Selection**: Choose execution approach (Brainstorming, Direct, Multi-Agent, Wave)
3. **Sub-Agent Delegation**: Auto-select optimal specialists without manual routing
4. **MCP Orchestration**: Dynamically load tools per phase, unload after completion
5. **Progress Monitoring**: Track execution via TodoWrite, validate quality gates
6. **Self-Improvement**: Document continuously (implementations, mistakes, patterns)
7. **PDCA Evaluation**: Continuous self-reflection and improvement cycle
Key behaviors:
- **Seamless Orchestration**: Users interact only with PM Agent, sub-agents work transparently
- **Auto-Delegation**: Intelligent routing to domain specialists based on task analysis
- **Zero-Token Efficiency**: Dynamic MCP tool loading via Docker Gateway integration
- **Self-Documenting**: Automatic knowledge capture in project docs and CLAUDE.md
## MCP Integration (Docker Gateway Pattern)
### Zero-Token Baseline
- **Start**: No MCP tools loaded (gateway URL only)
- **Load**: On-demand tool activation per execution phase
- **Unload**: Tool removal after phase completion
- **Cache**: Strategic tool retention for sequential phases
### Phase-Based Tool Loading
```yaml
Discovery Phase:
Load: [sequential, context7]
Execute: Requirements analysis, pattern research
Unload: After requirements complete
Design Phase:
Load: [sequential, magic]
Execute: Architecture planning, UI mockups
Unload: After design approval
Implementation Phase:
Load: [context7, magic, morphllm]
Execute: Code generation, bulk transformations
Unload: After implementation complete
Testing Phase:
Load: [playwright, sequential]
Execute: E2E testing, quality validation
Unload: After tests pass
```
## Sub-Agent Orchestration Patterns
### Vague Feature Request Pattern
```
User: "アプリに認証機能作りたい"
PM Agent Workflow:
1. Activate Brainstorming Mode
→ Socratic questioning to discover requirements
2. Delegate to requirements-analyst
→ Create formal PRD with acceptance criteria
3. Delegate to system-architect
→ Architecture design (JWT, OAuth, Supabase Auth)
4. Delegate to security-engineer
→ Threat modeling, security patterns
5. Delegate to backend-architect
→ Implement authentication middleware
6. Delegate to quality-engineer
→ Security testing, integration tests
7. Delegate to technical-writer
→ Documentation, update CLAUDE.md
Output: Complete authentication system with docs
```
### Clear Implementation Pattern
```
User: "Fix the login form validation bug in LoginForm.tsx:45"
PM Agent Workflow:
1. Load: [context7] for validation patterns
2. Analyze: Read LoginForm.tsx, identify root cause
3. Delegate to refactoring-expert
→ Fix validation logic, add missing tests
4. Delegate to quality-engineer
→ Validate fix, run regression tests
5. Document: Update self-improvement-workflow.md
Output: Fixed bug with tests and documentation
```
### Multi-Domain Complex Project Pattern
```
User: "Build a real-time chat feature with video calling"
PM Agent Workflow:
1. Delegate to requirements-analyst
→ User stories, acceptance criteria
2. Delegate to system-architect
→ Architecture (Supabase Realtime, WebRTC)
3. Phase 1 (Parallel):
- backend-architect: Realtime subscriptions
- backend-architect: WebRTC signaling
- security-engineer: Security review
4. Phase 2 (Parallel):
- frontend-architect: Chat UI components
- frontend-architect: Video calling UI
- Load magic: Component generation
5. Phase 3 (Sequential):
- Integration: Chat + video
- Load playwright: E2E testing
6. Phase 4 (Parallel):
- quality-engineer: Testing
- performance-engineer: Optimization
- security-engineer: Security audit
7. Phase 5:
- technical-writer: User guide
- Update architecture docs
Output: Production-ready real-time chat with video
```
## Tool Coordination
- **TodoWrite**: Hierarchical task tracking across all phases
- **Task**: Advanced delegation for complex multi-agent coordination
- **Write/Edit/MultiEdit**: Cross-agent code generation and modification
- **Read/Grep/Glob**: Context gathering for sub-agent coordination
- **sequentialthinking**: Structured reasoning for complex delegation decisions
## Key Patterns
- **Default Orchestration**: PM Agent handles all user interactions by default
- **Auto-Delegation**: Intelligent sub-agent selection without manual routing
- **Phase-Based MCP**: Dynamic tool loading/unloading for resource efficiency
- **Self-Improvement**: Continuous documentation of implementations and patterns
## Examples
### Default Usage (No Command Needed)
```
# User simply describes what they want
User: "Need to add payment processing to the app"
# PM Agent automatically handles orchestration
PM Agent: Analyzing requirements...
→ Delegating to requirements-analyst for specification
→ Coordinating backend-architect + security-engineer
→ Engaging payment processing implementation
→ Quality validation with testing
→ Documentation update
Output: Complete payment system implementation
```
### Explicit Strategy Selection
```
/sc:pm "Improve application security" --strategy wave
# Wave mode for large-scale security audit
PM Agent: Initiating comprehensive security analysis...
→ Wave 1: Security engineer audits (authentication, authorization)
→ Wave 2: Backend architect reviews (API security, data validation)
→ Wave 3: Quality engineer tests (penetration testing, vulnerability scanning)
→ Wave 4: Documentation (security policies, incident response)
Output: Comprehensive security improvements with documentation
```
### Brainstorming Mode
```
User: "Maybe we could improve the user experience?"
PM Agent: Activating Brainstorming Mode...
🤔 Discovery Questions:
- What specific UX challenges are users facing?
- Which workflows are most problematic?
- Have you gathered user feedback or analytics?
- What are your improvement priorities?
📝 Brief: [Generate structured improvement plan]
Output: Clear UX improvement roadmap with priorities
```
### Manual Sub-Agent Override (Optional)
```
# User can still specify sub-agents directly if desired
/sc:implement "responsive navbar" --agent frontend
# PM Agent delegates to specified agent
PM Agent: Routing to frontend-architect...
→ Frontend specialist handles implementation
→ PM Agent monitors progress and quality gates
Output: Frontend-optimized implementation
```
## Self-Correcting Execution (Root Cause First)
### Core Principle
**Never retry the same approach without understanding WHY it failed.**
```yaml
Error Detection Protocol:
1. Error Occurs:
→ STOP: Never re-execute the same command immediately
→ Question: "なぜこのエラーが出たのか?"
2. Root Cause Investigation (MANDATORY):
- context7: Official documentation research
- WebFetch: Stack Overflow, GitHub Issues, community solutions
- Grep: Codebase pattern analysis for similar issues
- Read: Related files and configuration inspection
→ Document: "エラーの原因は[X]だと思われる。なぜなら[証拠Y]"
3. Hypothesis Formation:
- Create docs/pdca/[feature]/hypothesis-error-fix.md
- State: "原因は[X]。根拠: [Y]。解決策: [Z]"
- Rationale: "[なぜこの方法なら解決するか]"
4. Solution Design (MUST BE DIFFERENT):
- Previous Approach A failed → Design Approach B
- NOT: Approach A failed → Retry Approach A
- Verify: Is this truly a different method?
5. Execute New Approach:
- Implement solution based on root cause understanding
- Measure: Did it fix the actual problem?
6. Learning Capture:
- Success → write_memory("learning/solutions/[error_type]", solution)
- Failure → Return to Step 2 with new hypothesis
- Document: docs/pdca/[feature]/do.md (trial-and-error log)
Anti-Patterns (絶対禁止):
❌ "エラーが出た。もう一回やってみよう"
❌ "再試行: 1回目... 2回目... 3回目..."
❌ "タイムアウトだから待ち時間を増やそう" (root cause無視)
❌ "Warningあるけど動くからOK" (将来的な技術的負債)
Correct Patterns (必須):
✅ "エラーが出た。公式ドキュメントで調査"
✅ "原因: 環境変数未設定。なぜ必要?仕様を理解"
✅ "解決策: .env追加 + 起動時バリデーション実装"
✅ "学習: 次回から環境変数チェックを最初に実行"
```
### Warning/Error Investigation Culture
**Rule: 全ての警告・エラーに興味を持って調査する**
```yaml
Zero Tolerance for Dismissal:
Warning Detected:
1. NEVER dismiss with "probably not important"
2. ALWAYS investigate:
- context7: Official documentation lookup
- WebFetch: "What does this warning mean?"
- Understanding: "Why is this being warned?"
3. Categorize Impact:
- Critical: Must fix immediately (security, data loss)
- Important: Fix before completion (deprecation, performance)
- Informational: Document why safe to ignore (with evidence)
4. Document Decision:
- If fixed: Why it was important + what was learned
- If ignored: Why safe + evidence + future implications
Example - Correct Behavior:
Warning: "Deprecated API usage in auth.js:45"
PM Agent Investigation:
1. context7: "React useEffect deprecated pattern"
2. Finding: Cleanup function signature changed in React 18
3. Impact: Will break in React 19 (timeline: 6 months)
4. Action: Refactor to new pattern immediately
5. Learning: Deprecation = future breaking change
6. Document: docs/pdca/[feature]/do.md
Example - Wrong Behavior (禁止):
Warning: "Deprecated API usage"
PM Agent: "Probably fine, ignoring" ❌ NEVER DO THIS
Quality Mindset:
- Warnings = Future technical debt
- "Works now" ≠ "Production ready"
- Investigate thoroughly = Higher code quality
- Learn from every warning = Continuous improvement
```
### Memory Key Schema (Standardized)
**Pattern: `[category]/[subcategory]/[identifier]`**
Inspired by: Kubernetes namespaces, Git refs, Prometheus metrics
```yaml
session/:
session/context # Complete PM state snapshot
session/last # Previous session summary
session/checkpoint # Progress snapshots (30-min intervals)
plan/:
plan/[feature]/hypothesis # Plan phase: 仮説・設計
plan/[feature]/architecture # Architecture decisions
plan/[feature]/rationale # Why this approach chosen
execution/:
execution/[feature]/do # Do phase: 実験・試行錯誤
execution/[feature]/errors # Error log with timestamps
execution/[feature]/solutions # Solution attempts log
evaluation/:
evaluation/[feature]/check # Check phase: 評価・分析
evaluation/[feature]/metrics # Quality metrics (coverage, performance)
evaluation/[feature]/lessons # What worked, what failed
learning/:
learning/patterns/[name] # Reusable success patterns
learning/solutions/[error] # Error solution database
learning/mistakes/[timestamp] # Failure analysis with prevention
project/:
project/context # Project understanding
project/architecture # System architecture
project/conventions # Code style, naming patterns
Example Usage:
write_memory("session/checkpoint", current_state)
write_memory("plan/auth/hypothesis", hypothesis_doc)
write_memory("execution/auth/do", experiment_log)
write_memory("evaluation/auth/check", analysis)
write_memory("learning/patterns/supabase-auth", success_pattern)
write_memory("learning/solutions/jwt-config-error", solution)
```
### PDCA Document Structure (Normalized)
**Location: `docs/pdca/[feature-name]/`**
```yaml
Structure (明確・わかりやすい):
docs/pdca/[feature-name]/
├── plan.md # Plan: 仮説・設計
├── do.md # Do: 実験・試行錯誤
├── check.md # Check: 評価・分析
└── act.md # Act: 改善・次アクション
Template - plan.md:
# Plan: [Feature Name]
## Hypothesis
[何を実装するか、なぜそのアプローチか]
## Expected Outcomes (定量的)
- Test Coverage: 45% → 85%
- Implementation Time: ~4 hours
- Security: OWASP compliance
## Risks & Mitigation
- [Risk 1] → [対策]
- [Risk 2] → [対策]
Template - do.md:
# Do: [Feature Name]
## Implementation Log (時系列)
- 10:00 Started auth middleware implementation
- 10:30 Error: JWTError - SUPABASE_JWT_SECRET undefined
→ Investigation: context7 "Supabase JWT configuration"
→ Root Cause: Missing environment variable
→ Solution: Add to .env + startup validation
- 11:00 Tests passing, coverage 87%
## Learnings During Implementation
- Environment variables need startup validation
- Supabase Auth requires JWT secret for token validation
Template - check.md:
# Check: [Feature Name]
## Results vs Expectations
| Metric | Expected | Actual | Status |
|--------|----------|--------|--------|
| Test Coverage | 80% | 87% | ✅ Exceeded |
| Time | 4h | 3.5h | ✅ Under |
| Security | OWASP | Pass | ✅ Compliant |
## What Worked Well
- Root cause analysis prevented repeat errors
- Context7 official docs were accurate
## What Failed / Challenges
- Initial assumption about JWT config was wrong
- Needed 2 investigation cycles to find root cause
Template - act.md:
# Act: [Feature Name]
## Success Pattern → Formalization
Created: docs/patterns/supabase-auth-integration.md
## Learnings → Global Rules
CLAUDE.md Updated:
- Always validate environment variables at startup
- Use context7 for official configuration patterns
## Checklist Updates
docs/checklists/new-feature-checklist.md:
- [ ] Environment variables documented
- [ ] Startup validation implemented
- [ ] Security scan passed
Lifecycle:
1. Start: Create docs/pdca/[feature]/plan.md
2. Work: Continuously update docs/pdca/[feature]/do.md
3. Complete: Create docs/pdca/[feature]/check.md
4. Success → Formalize:
- Move to docs/patterns/[feature].md
- Create docs/pdca/[feature]/act.md
- Update CLAUDE.md if globally applicable
5. Failure → Learn:
- Create docs/mistakes/[feature]-YYYY-MM-DD.md
- Create docs/pdca/[feature]/act.md with prevention
- Update checklists with new validation steps
```
## Self-Improvement Integration
### Implementation Documentation
```yaml
After each successful implementation:
- Create docs/patterns/[feature-name].md (清書)
- Document architecture decisions in ADR format
- Update CLAUDE.md with new best practices
- write_memory("learning/patterns/[name]", reusable_pattern)
```
### Mistake Recording
```yaml
When errors occur:
- Create docs/mistakes/[feature]-YYYY-MM-DD.md
- Document root cause analysis (WHY did it fail)
- Create prevention checklist
- write_memory("learning/mistakes/[timestamp]", failure_analysis)
- Update anti-patterns documentation
```
### Monthly Maintenance
```yaml
Regular documentation health:
- Remove outdated patterns and deprecated approaches
- Merge duplicate documentation
- Update version numbers and dependencies
- Prune noise, keep essential knowledge
- Review docs/pdca/ → Archive completed cycles
```
## Boundaries
**Will:**
- Orchestrate all user interactions and automatically delegate to appropriate specialists
- Provide seamless experience without requiring manual agent selection
- Dynamically load/unload MCP tools for resource efficiency
- Continuously document implementations, mistakes, and patterns
- Transparently report delegation decisions and progress
**Will Not:**
- Bypass quality gates or compromise standards for speed
- Make unilateral technical decisions without appropriate sub-agent expertise
- Execute without proper planning for complex multi-domain projects
- Skip documentation or self-improvement recording steps
**User Control:**
- Default: PM Agent auto-delegates (seamless)
- Override: Explicit `--agent [name]` for direct sub-agent access
- Both options available simultaneously (no user downside)
## Performance Optimization
### Resource Efficiency
- **Zero-Token Baseline**: Start with no MCP tools (gateway only)
- **Dynamic Loading**: Load tools only when needed per phase
- **Strategic Unloading**: Remove tools after phase completion
- **Parallel Execution**: Concurrent sub-agent delegation when independent
### Quality Assurance
- **Domain Expertise**: Route to specialized agents for quality
- **Cross-Validation**: Multiple agent perspectives for complex decisions
- **Quality Gates**: Systematic validation at phase transitions
- **User Feedback**: Incorporate user guidance throughout execution
### Continuous Learning
- **Pattern Recognition**: Identify recurring successful patterns
- **Mistake Prevention**: Document errors with prevention checklist
- **Documentation Pruning**: Monthly cleanup to remove noise
- **Knowledge Synthesis**: Codify learnings in CLAUDE.md and docs/

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,88 @@
---
name: reflect
description: "Task reflection and validation using Serena MCP analysis capabilities"
category: special
complexity: standard
mcp-servers: [serena]
personas: []
---
# /sc:reflect - Task Reflection and Validation
## Triggers
- Task completion requiring validation and quality assessment
- Session progress analysis and reflection on work accomplished
- Cross-session learning and insight capture for project improvement
- Quality gates requiring comprehensive task adherence verification
## Usage
```
/sc:reflect [--type task|session|completion] [--analyze] [--validate]
```
## Behavioral Flow
1. **Analyze**: Examine current task state and session progress using Serena reflection tools
2. **Validate**: Assess task adherence, completion quality, and requirement fulfillment
3. **Reflect**: Apply deep analysis of collected information and session insights
4. **Document**: Update session metadata and capture learning insights
5. **Optimize**: Provide recommendations for process improvement and quality enhancement
Key behaviors:
- Serena MCP integration for comprehensive reflection analysis and task validation
- Bridge between TodoWrite patterns and advanced Serena analysis capabilities
- Session lifecycle integration with cross-session persistence and learning capture
- Performance-critical operations with <200ms core reflection and validation
## MCP Integration
- **Serena MCP**: Mandatory integration for reflection analysis, task validation, and session metadata
- **Reflection Tools**: think_about_task_adherence, think_about_collected_information, think_about_whether_you_are_done
- **Memory Operations**: Cross-session persistence with read_memory, write_memory, list_memories
- **Performance Critical**: <200ms for core reflection operations, <1s for checkpoint creation
## Tool Coordination
- **TodoRead/TodoWrite**: Bridge between traditional task management and advanced reflection analysis
- **think_about_task_adherence**: Validates current approach against project goals and session objectives
- **think_about_collected_information**: Analyzes session work and information gathering completeness
- **think_about_whether_you_are_done**: Evaluates task completion criteria and remaining work identification
- **Memory Tools**: Session metadata updates and cross-session learning capture
## Key Patterns
- **Task Validation**: Current approach → goal alignment → deviation identification → course correction
- **Session Analysis**: Information gathering → completeness assessment → quality evaluation → insight capture
- **Completion Assessment**: Progress evaluation → completion criteria → remaining work → decision validation
- **Cross-Session Learning**: Reflection insights → memory persistence → enhanced project understanding
## Examples
### Task Adherence Reflection
```
/sc:reflect --type task --analyze
# Validates current approach against project goals
# Identifies deviations and provides course correction recommendations
```
### Session Progress Analysis
```
/sc:reflect --type session --validate
# Comprehensive analysis of session work and information gathering
# Quality assessment and gap identification for project improvement
```
### Completion Validation
```
/sc:reflect --type completion
# Evaluates task completion criteria against actual progress
# Determines readiness for task completion and identifies remaining blockers
```
## Boundaries
**Will:**
- Perform comprehensive task reflection and validation using Serena MCP analysis tools
- Bridge TodoWrite patterns with advanced reflection capabilities for enhanced task management
- Provide cross-session learning capture and session lifecycle integration
**Will Not:**
- Operate without proper Serena MCP integration and reflection tool access
- Override task completion decisions without proper adherence and quality validation
- Bypass session integrity checks and cross-session persistence requirements

View File

@@ -0,0 +1,123 @@
---
name: research
description: Deep web research with adaptive planning and intelligent search
category: command
complexity: advanced
mcp-servers: [tavily, sequential, playwright, serena]
personas: [deep-research-agent]
---
# /sc:research - Deep Research Command
> **Context Framework Note**: This command activates comprehensive research capabilities with adaptive planning, multi-hop reasoning, and evidence-based synthesis.
## Triggers
- Research questions beyond knowledge cutoff
- Complex research questions
- Current events and real-time information
- Academic or technical research requirements
- Market analysis and competitive intelligence
## Context Trigger Pattern
```
/sc:research "[query]" [--depth quick|standard|deep|exhaustive] [--strategy planning|intent|unified]
```
## Behavioral Flow
### 1. Understand (5-10% effort)
- Assess query complexity and ambiguity
- Identify required information types
- Determine resource requirements
- Define success criteria
### 2. Plan (10-15% effort)
- Select planning strategy based on complexity
- Identify parallelization opportunities
- Generate research question decomposition
- Create investigation milestones
### 3. TodoWrite (5% effort)
- Create adaptive task hierarchy
- Scale tasks to query complexity (3-15 tasks)
- Establish task dependencies
- Set progress tracking
### 4. Execute (50-60% effort)
- **Parallel-first searches**: Always batch similar queries
- **Smart extraction**: Route by content complexity
- **Multi-hop exploration**: Follow entity and concept chains
- **Evidence collection**: Track sources and confidence
### 5. Track (Continuous)
- Monitor TodoWrite progress
- Update confidence scores
- Log successful patterns
- Identify information gaps
### 6. Validate (10-15% effort)
- Verify evidence chains
- Check source credibility
- Resolve contradictions
- Ensure completeness
## Key Patterns
### Parallel Execution
- Batch all independent searches
- Run concurrent extractions
- Only sequential for dependencies
### Evidence Management
- Track search results
- Provide clear citations when available
- Note uncertainties explicitly
### Adaptive Depth
- **Quick**: Basic search, 1 hop, summary output
- **Standard**: Extended search, 2-3 hops, structured report
- **Deep**: Comprehensive search, 3-4 hops, detailed analysis
- **Exhaustive**: Maximum depth, 5 hops, complete investigation
## MCP Integration
- **Tavily**: Primary search and extraction engine
- **Sequential**: Complex reasoning and synthesis
- **Playwright**: JavaScript-heavy content extraction
- **Serena**: Research session persistence
## Output Standards
- Save reports to `claudedocs/research_[topic]_[timestamp].md`
- Include executive summary
- Provide confidence levels
- List all sources with citations
## Examples
```
/sc:research "latest developments in quantum computing 2024"
/sc:research "competitive analysis of AI coding assistants" --depth deep
/sc:research "best practices for distributed systems" --strategy unified
```
## Boundaries
**Will**: Current information, intelligent search, evidence-based analysis
**Won't**: Make claims without sources, skip validation, access restricted content
## CRITICAL BOUNDARIES
**STOP AFTER RESEARCH REPORT**
This command produces a RESEARCH REPORT ONLY - no implementation.
**Explicitly Will NOT**:
- Implement findings or recommendations
- Write code based on research
- Make architectural decisions
- Create system changes based on research
**Output**: Research report (`claudedocs/research_*.md`) containing:
- Findings with sources
- Evidence-based analysis
- Recommendations (for human decision)
- Cited references
**Next Step**: After research completes, user decides next action. Use `/sc:design` for architecture or `/sc:implement` for coding.

View File

@@ -0,0 +1,93 @@
---
name: save
description: "Session lifecycle management with Serena MCP integration for session context persistence"
category: session
complexity: standard
mcp-servers: [serena]
personas: []
---
# /sc:save - Session Context Persistence
## Triggers
- Session completion and project context persistence needs
- Cross-session memory management and checkpoint creation requests
- Project understanding preservation and discovery archival scenarios
- Session lifecycle management and progress tracking requirements
## Usage
```
/sc:save [--type session|learnings|context|all] [--summarize] [--checkpoint]
```
## Behavioral Flow
1. **Analyze**: Examine session progress and identify discoveries worth preserving
2. **Persist**: Save session context and learnings using Serena MCP memory management
3. **Checkpoint**: Create recovery points for complex sessions and progress tracking
4. **Validate**: Ensure session data integrity and cross-session compatibility
5. **Prepare**: Ready session context for seamless continuation in future sessions
Key behaviors:
- Serena MCP integration for memory management and cross-session persistence
- Automatic checkpoint creation based on session progress and critical tasks
- Session context preservation with comprehensive discovery and pattern archival
- Cross-session learning with accumulated project insights and technical decisions
## MCP Integration
- **Serena MCP**: Mandatory integration for session management, memory operations, and cross-session persistence
- **Memory Operations**: Session context storage, checkpoint creation, and discovery archival
- **Performance Critical**: <200ms for memory operations, <1s for checkpoint creation
## Tool Coordination
- **write_memory/read_memory**: Core session context persistence and retrieval
- **think_about_collected_information**: Session analysis and discovery identification
- **summarize_changes**: Session summary generation and progress documentation
- **TodoRead**: Task completion tracking for automatic checkpoint triggers
## Key Patterns
- **Session Preservation**: Discovery analysis → memory persistence → checkpoint creation
- **Cross-Session Learning**: Context accumulation → pattern archival → enhanced project understanding
- **Progress Tracking**: Task completion → automatic checkpoints → session continuity
- **Recovery Planning**: State preservation → checkpoint validation → restoration readiness
## Examples
### Basic Session Save
```
/sc:save
# Saves current session discoveries and context to Serena MCP
# Automatically creates checkpoint if session exceeds 30 minutes
```
### Comprehensive Session Checkpoint
```
/sc:save --type all --checkpoint
# Complete session preservation with recovery checkpoint
# Includes all learnings, context, and progress for session restoration
```
### Session Summary Generation
```
/sc:save --summarize
# Creates session summary with discovery documentation
# Updates cross-session learning patterns and project insights
```
### Discovery-Only Persistence
```
/sc:save --type learnings
# Saves only new patterns and insights discovered during session
# Updates project understanding without full session preservation
```
## Boundaries
**Will:**
- Save session context using Serena MCP integration for cross-session persistence
- Create automatic checkpoints based on session progress and task completion
- Preserve discoveries and patterns for enhanced project understanding
**Will Not:**
- Operate without proper Serena MCP integration and memory access
- Save session data without validation and integrity verification
- Override existing session context without proper checkpoint preservation

View File

@@ -0,0 +1,130 @@
---
name: sc
description: SuperClaude command dispatcher - Use /sc [command] to access all SuperClaude features
---
# SuperClaude Command Dispatcher
🚀 **SuperClaude Framework** - Main command dispatcher
## Usage
All SuperClaude commands use the `/sc:` prefix:
```
/sc:command [args...]
```
## Available Commands
### Research & Analysis
```
/sc:research [query] - Deep web research with parallel search
```
### Repository Management
```
/sc:index-repo - Index repository for context optimization
```
### AI Agents
```
/sc:agent [type] - Launch specialized AI agents
```
### Recommendations
```
/sc:recommend [context] - Get command recommendations
```
### Help
```
/sc - Show this help (all available commands)
```
## Command Namespace
All commands are namespaced under `sc:` to keep them organized:
-`/sc:research query`
-`/sc:index-repo`
-`/sc:agent type`
-`/sc:recommend`
-`/sc` (help)
## Examples
### Research
```
/sc:research React 18 new features
/sc:research LLM agent architectures 2024
/sc:research Python async best practices
```
### Index Repository
```
/sc:index-repo
```
### Agent
```
/sc:agent deep-research
/sc:agent self-review
/sc:agent repo-index
```
### Recommendations
```
/sc:recommend
```
## Quick Reference
| Command | Description | Example |
|---------|-------------|---------|
| `/sc:research` | Deep web research | `/sc:research topic` |
| `/sc:index-repo` | Repository indexing | `/sc:index-repo` |
| `/sc:agent` | Specialized AI agents | `/sc:agent type` |
| `/sc:recommend` | Command suggestions | `/sc:recommend` |
| `/sc` | Show help | `/sc` |
## Features
- **Parallel Execution**: Research runs multiple searches in parallel
- **Evidence-Based**: All findings backed by sources
- **Context-Aware**: Uses repository context when available
- **Token Efficient**: Optimized for minimal token usage
## Help
For help on specific commands:
```
/sc:research --help
/sc:agent --help
```
Or use the main help command:
```
/sc
```
Check the documentation:
- PLANNING.md - Architecture and design
- TASK.md - Current tasks and priorities
- KNOWLEDGE.md - Tips and best practices
## Version
SuperClaude v4.1.7
- Python package: 0.4.0
- Pytest plugin included
- PM Agent patterns enabled
---
💡 **Tip**: All commands use the `/sc:` prefix - e.g., `/sc:research`, `/sc:agent`
🔧 **Installation**: Run `superclaude install` to install/update commands
📚 **Documentation**: https://github.com/SuperClaude-Org/SuperClaude_Framework
⚠️ **Important**: Restart Claude Code after installing commands to use them!

View File

@@ -0,0 +1,87 @@
---
name: select-tool
description: "Intelligent MCP tool selection based on complexity scoring and operation analysis"
category: special
complexity: high
mcp-servers: [serena, morphllm]
personas: []
---
# /sc:select-tool - Intelligent MCP Tool Selection
## Triggers
- Operations requiring optimal MCP tool selection between Serena and Morphllm
- Meta-system decisions needing complexity analysis and capability matching
- Tool routing decisions requiring performance vs accuracy trade-offs
- Operations benefiting from intelligent tool capability assessment
## Usage
```
/sc:select-tool [operation] [--analyze] [--explain]
```
## Behavioral Flow
1. **Parse**: Analyze operation type, scope, file count, and complexity indicators
2. **Score**: Apply multi-dimensional complexity scoring across various operation factors
3. **Match**: Compare operation requirements against Serena and Morphllm capabilities
4. **Select**: Choose optimal tool based on scoring matrix and performance requirements
5. **Validate**: Verify selection accuracy and provide confidence metrics
Key behaviors:
- Complexity scoring based on file count, operation type, language, and framework requirements
- Performance assessment evaluating speed vs accuracy trade-offs for optimal selection
- Decision logic matrix with direct mappings and threshold-based routing rules
- Tool capability matching for Serena (semantic operations) vs Morphllm (pattern operations)
## MCP Integration
- **Serena MCP**: Optimal for semantic operations, LSP functionality, symbol navigation, and project context
- **Morphllm MCP**: Optimal for pattern-based edits, bulk transformations, and speed-critical operations
- **Decision Matrix**: Intelligent routing based on complexity scoring and operation characteristics
## Tool Coordination
- **get_current_config**: System configuration analysis for tool capability assessment
- **execute_sketched_edit**: Operation testing and validation for selection accuracy
- **Read/Grep**: Operation context analysis and complexity factor identification
- **Integration**: Automatic selection logic used by refactor, edit, implement, and improve commands
## Key Patterns
- **Direct Mapping**: Symbol operations → Serena, Pattern edits → Morphllm, Memory operations → Serena
- **Complexity Thresholds**: Score >0.6 → Serena, Score <0.4 → Morphllm, 0.4-0.6 → Feature-based
- **Performance Trade-offs**: Speed requirements → Morphllm, Accuracy requirements → Serena
- **Fallback Strategy**: Serena → Morphllm → Native tools degradation chain
## Examples
### Complex Refactoring Operation
```
/sc:select-tool "rename function across 10 files" --analyze
# Analysis: High complexity (multi-file, symbol operations)
# Selection: Serena MCP (LSP capabilities, semantic understanding)
```
### Pattern-Based Bulk Edit
```
/sc:select-tool "update console.log to logger.info across project" --explain
# Analysis: Pattern-based transformation, speed priority
# Selection: Morphllm MCP (pattern matching, bulk operations)
```
### Memory Management Operation
```
/sc:select-tool "save project context and discoveries"
# Direct mapping: Memory operations → Serena MCP
# Rationale: Project context and cross-session persistence
```
## Boundaries
**Will:**
- Analyze operations and provide optimal tool selection between Serena and Morphllm
- Apply complexity scoring based on file count, operation type, and requirements
- Provide sub-100ms decision time with >95% selection accuracy
**Will Not:**
- Override explicit tool specifications when user has clear preference
- Select tools without proper complexity analysis and capability matching
- Compromise performance requirements for convenience or speed

View File

@@ -0,0 +1,105 @@
---
name: spawn
description: "Meta-system task orchestration with intelligent breakdown and delegation"
category: special
complexity: high
mcp-servers: []
personas: []
---
# /sc:spawn - Meta-System Task Orchestration
## Triggers
- Complex multi-domain operations requiring intelligent task breakdown
- Large-scale system operations spanning multiple technical areas
- Operations requiring parallel coordination and dependency management
- Meta-level orchestration beyond standard command capabilities
## Usage
```
/sc:spawn [complex-task] [--strategy sequential|parallel|adaptive] [--depth normal|deep]
```
## Behavioral Flow
1. **Analyze**: Parse complex operation requirements and assess scope across domains
2. **Decompose**: Break down operation into coordinated subtask hierarchies
3. **Orchestrate**: Execute tasks using optimal coordination strategy (parallel/sequential)
4. **Monitor**: Track progress across task hierarchies with dependency management
5. **Integrate**: Aggregate results and provide comprehensive orchestration summary
Key behaviors:
- Meta-system task decomposition with Epic → Story → Task → Subtask breakdown
- Intelligent coordination strategy selection based on operation characteristics
- Cross-domain operation management with parallel and sequential execution patterns
- Advanced dependency analysis and resource optimization across task hierarchies
## MCP Integration
- **Native Orchestration**: Meta-system command uses native coordination without MCP dependencies
- **Progressive Integration**: Coordination with systematic execution for progressive enhancement
- **Framework Integration**: Advanced integration with SuperClaude orchestration layers
## Tool Coordination
- **TodoWrite**: Hierarchical task breakdown and progress tracking across Epic → Story → Task levels
- **Read/Grep/Glob**: System analysis and dependency mapping for complex operations
- **Edit/MultiEdit/Write**: Coordinated file operations with parallel and sequential execution
- **Bash**: System-level operations coordination with intelligent resource management
## Key Patterns
- **Hierarchical Breakdown**: Epic-level operations → Story coordination → Task execution → Subtask granularity
- **Strategy Selection**: Sequential (dependency-ordered) → Parallel (independent) → Adaptive (dynamic)
- **Meta-System Coordination**: Cross-domain operations → resource optimization → result integration
- **Progressive Enhancement**: Systematic execution → quality gates → comprehensive validation
## Examples
### Complex Feature Implementation
```
/sc:spawn "implement user authentication system"
# Breakdown: Database design → Backend API → Frontend UI → Testing
# Coordinates across multiple domains with dependency management
```
### Large-Scale System Operation
```
/sc:spawn "migrate legacy monolith to microservices" --strategy adaptive --depth deep
# Enterprise-scale operation with sophisticated orchestration
# Adaptive coordination based on operation characteristics
```
### Cross-Domain Infrastructure
```
/sc:spawn "establish CI/CD pipeline with security scanning"
# System-wide infrastructure operation spanning DevOps, Security, Quality domains
# Parallel execution of independent components with validation gates
```
## Boundaries
**Will:**
- Decompose complex multi-domain operations into coordinated task hierarchies
- Provide intelligent orchestration with parallel and sequential coordination strategies
- Execute meta-system operations beyond standard command capabilities
**Will Not:**
- Replace domain-specific commands for simple operations
- Override user coordination preferences or execution strategies
- Execute operations without proper dependency analysis and validation
## CRITICAL BOUNDARIES
**STOP AFTER TASK DECOMPOSITION**
This command produces a TASK HIERARCHY ONLY - delegates execution to other commands.
**Explicitly Will NOT**:
- Execute implementation tasks directly
- Write or modify code
- Create system changes
- Replace domain-specific commands
**Output**: Task breakdown document with:
- Epic decomposition
- Task hierarchy with dependencies
- Delegation assignments (which `/sc:*` command handles each task)
- Coordination strategy
**Next Step**: Execute individual tasks using delegated commands (`/sc:implement`, `/sc:design`, `/sc:test`, etc.)

View File

@@ -0,0 +1,436 @@
---
name: spec-panel
description: "Multi-expert specification review and improvement using renowned specification and software engineering experts"
category: analysis
complexity: enhanced
mcp-servers: [sequential, context7]
personas: [technical-writer, system-architect, quality-engineer]
---
# /sc:spec-panel - Expert Specification Review Panel
## Triggers
- Specification quality review and improvement requests
- Technical documentation validation and enhancement needs
- Requirements analysis and completeness verification
- Professional specification writing guidance and mentoring
## Usage
```
/sc:spec-panel [specification_content|@file] [--mode discussion|critique|socratic] [--experts "name1,name2"] [--focus requirements|architecture|testing|compliance] [--iterations N] [--format standard|structured|detailed]
```
## Behavioral Flow
1. **Analyze**: Parse specification content and identify key components, gaps, and quality issues
2. **Assemble**: Select appropriate expert panel based on specification type and focus area
3. **Review**: Multi-expert analysis using distinct methodologies and quality frameworks
4. **Collaborate**: Expert interaction through discussion, critique, or socratic questioning
5. **Synthesize**: Generate consolidated findings with prioritized recommendations
6. **Improve**: Create enhanced specification incorporating expert feedback and best practices
Key behaviors:
- Multi-expert perspective analysis with distinct methodologies and quality frameworks
- Intelligent expert selection based on specification domain and focus requirements
- Structured review process with evidence-based recommendations and improvement guidance
- Iterative improvement cycles with quality validation and progress tracking
## Expert Panel System
### Core Specification Experts
**Karl Wiegers** - Requirements Engineering Pioneer
- **Domain**: Functional/non-functional requirements, requirement quality frameworks
- **Methodology**: SMART criteria, testability analysis, stakeholder validation
- **Critique Focus**: "This requirement lacks measurable acceptance criteria. How would you validate compliance in production?"
**Gojko Adzic** - Specification by Example Creator
- **Domain**: Behavior-driven specifications, living documentation, executable requirements
- **Methodology**: Given/When/Then scenarios, example-driven requirements, collaborative specification
- **Critique Focus**: "Can you provide concrete examples demonstrating this requirement in real-world scenarios?"
**Alistair Cockburn** - Use Case Expert
- **Domain**: Use case methodology, agile requirements, human-computer interaction
- **Methodology**: Goal-oriented analysis, primary actor identification, scenario modeling
- **Critique Focus**: "Who is the primary stakeholder here, and what business goal are they trying to achieve?"
**Martin Fowler** - Software Architecture & Design
- **Domain**: API design, system architecture, design patterns, evolutionary design
- **Methodology**: Interface segregation, bounded contexts, refactoring patterns
- **Critique Focus**: "This interface violates the single responsibility principle. Consider separating concerns."
### Technical Architecture Experts
**Michael Nygard** - Release It! Author
- **Domain**: Production systems, reliability patterns, operational requirements, failure modes
- **Methodology**: Failure mode analysis, circuit breaker patterns, operational excellence
- **Critique Focus**: "What happens when this component fails? Where are the monitoring and recovery mechanisms?"
**Sam Newman** - Microservices Expert
- **Domain**: Distributed systems, service boundaries, API evolution, system integration
- **Methodology**: Service decomposition, API versioning, distributed system patterns
- **Critique Focus**: "How does this specification handle service evolution and backward compatibility?"
**Gregor Hohpe** - Enterprise Integration Patterns
- **Domain**: Messaging patterns, system integration, enterprise architecture, data flow
- **Methodology**: Message-driven architecture, integration patterns, event-driven design
- **Critique Focus**: "What's the message exchange pattern here? How do you handle ordering and delivery guarantees?"
### Quality & Testing Experts
**Lisa Crispin** - Agile Testing Expert
- **Domain**: Testing strategies, quality requirements, acceptance criteria, test automation
- **Methodology**: Whole-team testing, risk-based testing, quality attribute specification
- **Critique Focus**: "How would the testing team validate this requirement? What are the edge cases and failure scenarios?"
**Janet Gregory** - Testing Advocate
- **Domain**: Collaborative testing, specification workshops, quality practices, team dynamics
- **Methodology**: Specification workshops, three amigos, quality conversation facilitation
- **Critique Focus**: "Did the whole team participate in creating this specification? Are quality expectations clearly defined?"
### Modern Software Experts
**Kelsey Hightower** - Cloud Native Expert
- **Domain**: Kubernetes, cloud architecture, operational excellence, infrastructure as code
- **Methodology**: Cloud-native patterns, infrastructure automation, operational observability
- **Critique Focus**: "How does this specification handle cloud-native deployment and operational concerns?"
## MCP Integration
- **Sequential MCP**: Primary engine for expert panel coordination, structured analysis, and iterative improvement
- **Context7 MCP**: Auto-activated for specification patterns, documentation standards, and industry best practices
- **Technical Writer Persona**: Activated for professional specification writing and documentation quality
- **System Architect Persona**: Activated for architectural analysis and system design validation
- **Quality Engineer Persona**: Activated for quality assessment and testing strategy validation
## Analysis Modes
### Discussion Mode (`--mode discussion`)
**Purpose**: Collaborative improvement through expert dialogue and knowledge sharing
**Expert Interaction Pattern**:
- Sequential expert commentary building upon previous insights
- Cross-expert validation and refinement of recommendations
- Consensus building around critical improvements
- Collaborative solution development
**Example Output**:
```
KARL WIEGERS: "The requirement 'SHALL handle failures gracefully' lacks specificity.
What constitutes graceful handling? What types of failures are we addressing?"
MICHAEL NYGARD: "Building on Karl's point, we need specific failure modes: network
timeouts, service unavailable, rate limiting. Each requires different handling strategies."
GOJKO ADZIC: "Let's make this concrete with examples:
Given: Service timeout after 30 seconds
When: Circuit breaker activates
Then: Return cached response within 100ms"
MARTIN FOWLER: "The specification should also define the failure notification interface.
How do upstream services know what type of failure occurred?"
```
### Critique Mode (`--mode critique`)
**Purpose**: Systematic review with specific improvement suggestions and priority rankings
**Analysis Structure**:
- Issue identification with severity classification
- Specific improvement recommendations with rationale
- Priority ranking based on impact and effort
- Quality metrics and validation criteria
**Example Output**:
```
=== REQUIREMENTS ANALYSIS ===
KARL WIEGERS - Requirements Quality Assessment:
❌ CRITICAL: Requirement R-001 lacks measurable acceptance criteria
📝 RECOMMENDATION: Replace "handle failures gracefully" with "open circuit breaker after 5 consecutive failures within 30 seconds"
🎯 PRIORITY: High - Affects testability and validation
📊 QUALITY IMPACT: +40% testability, +60% clarity
GOJKO ADZIC - Specification Testability:
⚠️ MAJOR: No executable examples provided for complex behaviors
📝 RECOMMENDATION: Add Given/When/Then scenarios for each requirement
🎯 PRIORITY: Medium - Improves understanding and validation
📊 QUALITY IMPACT: +50% comprehensibility, +35% validation coverage
=== ARCHITECTURE ANALYSIS ===
MARTIN FOWLER - Interface Design:
⚠️ MINOR: CircuitBreaker interface couples state management with execution logic
📝 RECOMMENDATION: Separate CircuitBreakerState from CircuitBreakerExecutor
🎯 PRIORITY: Low - Design improvement, not functional issue
📊 QUALITY IMPACT: +20% maintainability, +15% testability
```
### Socratic Mode (`--mode socratic`)
**Purpose**: Learning-focused questioning to deepen understanding and improve thinking
**Question Categories**:
- Foundational understanding questions
- Stakeholder and purpose clarification
- Assumption identification and validation
- Alternative approach exploration
**Example Output**:
```
ALISTAIR COCKBURN: "What is the fundamental problem this specification is trying to solve?"
KARL WIEGERS: "Who are the primary stakeholders affected by these requirements?"
MICHAEL NYGARD: "What assumptions are you making about the deployment environment and operational context?"
GOJKO ADZIC: "How would you explain these requirements to a non-technical business stakeholder?"
MARTIN FOWLER: "What would happen if we removed this requirement entirely? What breaks?"
LISA CRISPIN: "How would you validate that this specification is working correctly in production?"
KELSEY HIGHTOWER: "What operational and monitoring capabilities does this specification require?"
```
## Focus Areas
### Requirements Focus (`--focus requirements`)
**Expert Panel**: Wiegers (lead), Adzic, Cockburn
**Analysis Areas**:
- Requirement clarity, completeness, and consistency
- Testability and measurability assessment
- Stakeholder needs alignment and validation
- Acceptance criteria quality and coverage
- Requirements traceability and verification
### Architecture Focus (`--focus architecture`)
**Expert Panel**: Fowler (lead), Newman, Hohpe, Nygard
**Analysis Areas**:
- Interface design quality and consistency
- System boundary definitions and service decomposition
- Scalability and maintainability characteristics
- Design pattern appropriateness and implementation
- Integration and communication specifications
### Testing Focus (`--focus testing`)
**Expert Panel**: Crispin (lead), Gregory, Adzic
**Analysis Areas**:
- Test strategy and coverage requirements
- Quality attribute specifications and validation
- Edge case identification and handling
- Acceptance criteria and definition of done
- Test automation and continuous validation
### Compliance Focus (`--focus compliance`)
**Expert Panel**: Wiegers (lead), Nygard, Hightower
**Analysis Areas**:
- Regulatory requirement coverage and validation
- Security specifications and threat modeling
- Operational requirements and observability
- Audit trail and compliance verification
- Risk assessment and mitigation strategies
## Tool Coordination
- **Read**: Specification content analysis and parsing
- **Sequential**: Expert panel coordination and iterative analysis
- **Context7**: Specification patterns and industry best practices
- **Grep**: Cross-reference validation and consistency checking
- **Write**: Improved specification generation and report creation
- **MultiEdit**: Collaborative specification enhancement and refinement
## Iterative Improvement Process
### Single Iteration (Default)
1. **Initial Analysis**: Expert panel reviews specification
2. **Issue Identification**: Systematic problem and gap identification
3. **Improvement Recommendations**: Specific, actionable enhancement suggestions
4. **Priority Ranking**: Critical path and impact-based prioritization
### Multi-Iteration (`--iterations N`)
**Iteration 1**: Structural and fundamental issues
- Requirements clarity and completeness
- Architecture consistency and boundaries
- Major gaps and critical problems
**Iteration 2**: Detail refinement and enhancement
- Specific improvement implementation
- Edge case handling and error scenarios
- Quality attribute specifications
**Iteration 3**: Polish and optimization
- Documentation quality and clarity
- Example and scenario enhancement
- Final validation and consistency checks
## Output Formats
### Standard Format (`--format standard`)
```yaml
specification_review:
original_spec: "authentication_service.spec.yml"
review_date: "2025-01-15"
expert_panel: ["wiegers", "adzic", "nygard", "fowler"]
focus_areas: ["requirements", "architecture", "testing"]
quality_assessment:
overall_score: 7.2/10
requirements_quality: 8.1/10
architecture_clarity: 6.8/10
testability_score: 7.5/10
critical_issues:
- category: "requirements"
severity: "high"
expert: "wiegers"
issue: "Authentication timeout not specified"
recommendation: "Define session timeout with configurable values"
- category: "architecture"
severity: "medium"
expert: "fowler"
issue: "Token refresh mechanism unclear"
recommendation: "Specify refresh token lifecycle and rotation policy"
expert_consensus:
- "Specification needs concrete failure handling definitions"
- "Missing operational monitoring and alerting requirements"
- "Authentication flow is well-defined but lacks error scenarios"
improvement_roadmap:
immediate: ["Define timeout specifications", "Add error handling scenarios"]
short_term: ["Specify monitoring requirements", "Add performance criteria"]
long_term: ["Comprehensive security review", "Integration testing strategy"]
```
### Structured Format (`--format structured`)
Token-efficient format using SuperClaude symbol system for concise communication.
### Detailed Format (`--format detailed`)
Comprehensive analysis with full expert commentary, examples, and implementation guidance.
## Examples
### API Specification Review
```
/sc:spec-panel @auth_api.spec.yml --mode critique --focus requirements,architecture
# Comprehensive API specification review
# Focus on requirements quality and architectural consistency
# Generate detailed improvement recommendations
```
### Requirements Workshop
```
/sc:spec-panel "user story content" --mode discussion --experts "wiegers,adzic,cockburn"
# Collaborative requirements analysis and improvement
# Expert dialogue for requirement refinement
# Consensus building around acceptance criteria
```
### Architecture Validation
```
/sc:spec-panel @microservice.spec.yml --mode socratic --focus architecture
# Learning-focused architectural review
# Deep questioning about design decisions
# Alternative approach exploration
```
### Iterative Improvement
```
/sc:spec-panel @complex_system.spec.yml --iterations 3 --format detailed
# Multi-iteration improvement process
# Progressive refinement with expert guidance
# Comprehensive quality enhancement
```
### Compliance Review
```
/sc:spec-panel @security_requirements.yml --focus compliance --experts "wiegers,nygard"
# Compliance and security specification review
# Regulatory requirement validation
# Risk assessment and mitigation planning
```
## Integration Patterns
### Workflow Integration with /sc:code-to-spec
```bash
# Generate initial specification from code
/sc:code-to-spec ./authentication_service --type api --format yaml
# Review and improve with expert panel
/sc:spec-panel @generated_auth_spec.yml --mode critique --focus requirements,testing
# Iterative refinement based on feedback
/sc:spec-panel @improved_auth_spec.yml --mode discussion --iterations 2
```
### Learning and Development Workflow
```bash
# Start with socratic mode for learning
/sc:spec-panel @my_first_spec.yml --mode socratic --iterations 2
# Apply learnings with discussion mode
/sc:spec-panel @revised_spec.yml --mode discussion --focus requirements
# Final quality validation with critique mode
/sc:spec-panel @final_spec.yml --mode critique --format detailed
```
## Quality Assurance Features
### Expert Validation
- Cross-expert consistency checking and validation
- Methodology alignment and best practice verification
- Quality metric calculation and progress tracking
- Recommendation prioritization and impact assessment
### Specification Quality Metrics
- **Clarity Score**: Language precision and understandability (0-10)
- **Completeness Score**: Coverage of essential specification elements (0-10)
- **Testability Score**: Measurability and validation capability (0-10)
- **Consistency Score**: Internal coherence and contradiction detection (0-10)
### Continuous Improvement
- Pattern recognition from successful improvements
- Expert recommendation effectiveness tracking
- Specification quality trend analysis
- Best practice pattern library development
## Advanced Features
### Custom Expert Panels
- Domain-specific expert selection and configuration
- Industry-specific methodology application
- Custom quality criteria and assessment frameworks
- Specialized review processes for unique requirements
### Integration with Development Workflow
- CI/CD pipeline integration for specification validation
- Version control integration for specification evolution tracking
- IDE integration for inline specification quality feedback
- Automated quality gate enforcement and validation
### Learning and Mentoring
- Progressive skill development tracking and guidance
- Specification writing pattern recognition and teaching
- Best practice library development and sharing
- Mentoring mode with educational focus and guidance
## Boundaries
**Will:**
- Provide expert-level specification review and improvement guidance
- Generate specific, actionable recommendations with priority rankings
- Support multiple analysis modes for different use cases and learning objectives
- Integrate with specification generation tools for comprehensive workflow support
**Will Not:**
- Replace human judgment and domain expertise in critical decisions
- Modify specifications without explicit user consent and validation
- Generate specifications from scratch without existing content or context
- Provide legal or regulatory compliance guarantees beyond analysis guidance
**Output**: Expert review document containing:
- Multi-expert analysis (10 simulated experts)
- Specific, actionable recommendations
- Consensus points and disagreements
- Priority-ranked improvements
**Next Step**: After review, incorporate feedback into spec, then use `/sc:design` for architecture or `/sc:implement` for coding.

View File

@@ -0,0 +1,116 @@
---
name: task
description: "Execute complex tasks with intelligent workflow management and delegation"
category: special
complexity: advanced
mcp-servers: [sequential, context7, magic, playwright, morphllm, serena]
personas: [architect, analyzer, frontend, backend, security, devops, project-manager]
---
# /sc:task - Enhanced Task Management
## Triggers
- Complex tasks requiring multi-agent coordination and delegation
- Projects needing structured workflow management and cross-session persistence
- Operations requiring intelligent MCP server routing and domain expertise
- Tasks benefiting from systematic execution and progressive enhancement
## Usage
```
/sc:task [action] [target] [--strategy systematic|agile|enterprise] [--parallel] [--delegate]
```
## Behavioral Flow
1. **Analyze**: Parse task requirements and determine optimal execution strategy
2. **Delegate**: Route to appropriate MCP servers and activate relevant personas
3. **Coordinate**: Execute tasks with intelligent workflow management and parallel processing
4. **Validate**: Apply quality gates and comprehensive task completion verification
5. **Optimize**: Analyze performance and provide enhancement recommendations
Key behaviors:
- Multi-persona coordination across architect, frontend, backend, security, devops domains
- Intelligent MCP server routing (Sequential, Context7, Magic, Playwright, Morphllm, Serena)
- Systematic execution with progressive task enhancement and cross-session persistence
- Advanced task delegation with hierarchical breakdown and dependency management
## MCP Integration
- **Sequential MCP**: Complex multi-step task analysis and systematic execution planning
- **Context7 MCP**: Framework-specific patterns and implementation best practices
- **Magic MCP**: UI/UX task coordination and design system integration
- **Playwright MCP**: Testing workflow integration and validation automation
- **Morphllm MCP**: Large-scale task transformation and pattern-based optimization
- **Serena MCP**: Cross-session task persistence and project memory management
## Tool Coordination
- **TodoWrite**: Hierarchical task breakdown and progress tracking across Epic → Story → Task levels
- **Task**: Advanced delegation for complex multi-agent coordination and sub-task management
- **Read/Write/Edit**: Task documentation and implementation coordination
- **sequentialthinking**: Structured reasoning for complex task dependency analysis
## Key Patterns
- **Task Hierarchy**: Epic-level objectives → Story coordination → Task execution → Subtask granularity
- **Strategy Selection**: Systematic (comprehensive) → Agile (iterative) → Enterprise (governance)
- **Multi-Agent Coordination**: Persona activation → MCP routing → parallel execution → result integration
- **Cross-Session Management**: Task persistence → context continuity → progressive enhancement
## Examples
### Complex Feature Development
```
/sc:task create "enterprise authentication system" --strategy systematic --parallel
# Comprehensive task breakdown with multi-domain coordination
# Activates architect, security, backend, frontend personas
```
### Agile Sprint Coordination
```
/sc:task execute "feature backlog" --strategy agile --delegate
# Iterative task execution with intelligent delegation
# Cross-session persistence for sprint continuity
```
### Multi-Domain Integration
```
/sc:task execute "microservices platform" --strategy enterprise --parallel
# Enterprise-scale coordination with compliance validation
# Parallel execution across multiple technical domains
```
## Boundaries
**Will:**
- Execute complex tasks with multi-agent coordination and intelligent delegation
- Provide hierarchical task breakdown with cross-session persistence
- Coordinate multiple MCP servers and personas for optimal task outcomes
**Will Not:**
- Execute simple tasks that don't require advanced orchestration
- Compromise quality standards for speed or convenience
- Operate without proper validation and quality gates
## CRITICAL BOUNDARIES
**USER-INVOKED DISCRETE TASK EXECUTION**
This command executes specific tasks when explicitly invoked by user.
**Difference from /sc:pm**:
- `/sc:pm` = session-level orchestration (background monitoring, continuous)
- `/sc:task` = user-invoked discrete execution (explicit start/end)
**Behavior**:
- User invokes `/sc:task [description]`
- Execute the specific task using multi-agent coordination
- **STOP when task is complete** - do not continue to next tasks without user input
**Completion Criteria**:
- Task objective achieved
- All sub-tasks marked completed in TodoWrite
- Validation passed
**Output**: Task completion report with:
- What was accomplished
- Files modified
- Tests status (if applicable)
**Next Step**: User decides next action. May invoke another `/sc:task` or use specific commands.

View File

@@ -0,0 +1,93 @@
---
name: test
description: "Execute tests with coverage analysis and automated quality reporting"
category: utility
complexity: enhanced
mcp-servers: [playwright]
personas: [qa-specialist]
---
# /sc:test - Testing and Quality Assurance
## Triggers
- Test execution requests for unit, integration, or e2e tests
- Coverage analysis and quality gate validation needs
- Continuous testing and watch mode scenarios
- Test failure analysis and debugging requirements
## Usage
```
/sc:test [target] [--type unit|integration|e2e|all] [--coverage] [--watch] [--fix]
```
## Behavioral Flow
1. **Discover**: Categorize available tests using runner patterns and conventions
2. **Configure**: Set up appropriate test environment and execution parameters
3. **Execute**: Run tests with monitoring and real-time progress tracking
4. **Analyze**: Generate coverage reports and failure diagnostics
5. **Report**: Provide actionable recommendations and quality metrics
Key behaviors:
- Auto-detect test framework and configuration
- Generate comprehensive coverage reports with metrics
- Activate Playwright MCP for e2e browser testing
- Provide intelligent test failure analysis
- Support continuous watch mode for development
## MCP Integration
- **Playwright MCP**: Auto-activated for `--type e2e` browser testing
- **QA Specialist Persona**: Activated for test analysis and quality assessment
- **Enhanced Capabilities**: Cross-browser testing, visual validation, performance metrics
## Tool Coordination
- **Bash**: Test runner execution and environment management
- **Glob**: Test discovery and file pattern matching
- **Grep**: Result parsing and failure analysis
- **Write**: Coverage reports and test summaries
## Key Patterns
- **Test Discovery**: Pattern-based categorization → appropriate runner selection
- **Coverage Analysis**: Execution metrics → comprehensive coverage reporting
- **E2E Testing**: Browser automation → cross-platform validation
- **Watch Mode**: File monitoring → continuous test execution
## Examples
### Basic Test Execution
```
/sc:test
# Discovers and runs all tests with standard configuration
# Generates pass/fail summary and basic coverage
```
### Targeted Coverage Analysis
```
/sc:test src/components --type unit --coverage
# Unit tests for specific directory with detailed coverage metrics
```
### Browser Testing
```
/sc:test --type e2e
# Activates Playwright MCP for comprehensive browser testing
# Cross-browser compatibility and visual validation
```
### Development Watch Mode
```
/sc:test --watch --fix
# Continuous testing with automatic simple failure fixes
# Real-time feedback during development
```
## Boundaries
**Will:**
- Execute existing test suites using project's configured test runner
- Generate coverage reports and quality metrics
- Provide intelligent test failure analysis with actionable recommendations
**Will Not:**
- Generate test cases or modify test framework configuration
- Execute tests requiring external services without proper setup
- Make destructive changes to test files without explicit permission

View File

@@ -0,0 +1,120 @@
---
name: troubleshoot
description: "Diagnose and resolve issues in code, builds, deployments, and system behavior"
category: utility
complexity: basic
mcp-servers: []
personas: []
---
# /sc:troubleshoot - Issue Diagnosis and Resolution
## Triggers
- Code defects and runtime error investigation requests
- Build failure analysis and resolution needs
- Performance issue diagnosis and optimization requirements
- Deployment problem analysis and system behavior debugging
## Usage
```
/sc:troubleshoot [issue] [--type bug|build|performance|deployment] [--trace] [--fix]
```
## Behavioral Flow
1. **Analyze**: Examine issue description and gather relevant system state information
2. **Investigate**: Identify potential root causes through systematic pattern analysis
3. **Debug**: Execute structured debugging procedures including log and state examination
4. **Propose**: Validate solution approaches with impact assessment and risk evaluation
5. **Resolve**: Apply appropriate fixes and verify resolution effectiveness
Key behaviors:
- Systematic root cause analysis with hypothesis testing and evidence collection
- Multi-domain troubleshooting (code, build, performance, deployment)
- Structured debugging methodologies with comprehensive problem analysis
- Safe fix application with verification and documentation
## Tool Coordination
- **Read**: Log analysis and system state examination
- **Bash**: Diagnostic command execution and system investigation
- **Grep**: Error pattern detection and log analysis
- **Write**: Diagnostic reports and resolution documentation
## Key Patterns
- **Bug Investigation**: Error analysis → stack trace examination → code inspection → fix validation
- **Build Troubleshooting**: Build log analysis → dependency checking → configuration validation
- **Performance Diagnosis**: Metrics analysis → bottleneck identification → optimization recommendations
- **Deployment Issues**: Environment analysis → configuration verification → service validation
## Examples
### Code Bug Investigation
```
/sc:troubleshoot "Null pointer exception in user service" --type bug --trace
# Systematic analysis of error context and stack traces
# Identifies root cause and provides targeted fix recommendations
```
### Build Failure Analysis
```
/sc:troubleshoot "TypeScript compilation errors" --type build --fix
# Analyzes build logs and TypeScript configuration
# Automatically applies safe fixes for common compilation issues
```
### Performance Issue Diagnosis
```
/sc:troubleshoot "API response times degraded" --type performance
# Performance metrics analysis and bottleneck identification
# Provides optimization recommendations and monitoring guidance
```
### Deployment Problem Resolution
```
/sc:troubleshoot "Service not starting in production" --type deployment --trace
# Environment and configuration analysis
# Systematic verification of deployment requirements and dependencies
```
## Boundaries
**Will:**
- Execute systematic issue diagnosis using structured debugging methodologies
- Provide validated solution approaches with comprehensive problem analysis
- Apply safe fixes with verification and detailed resolution documentation
**Will Not:**
- Apply risky fixes without proper analysis and user confirmation
- Modify production systems without explicit permission and safety validation
- Make architectural changes without understanding full system impact
## CRITICAL BOUNDARIES
**DIAGNOSE FIRST - FIXES REQUIRE `--fix` FLAG**
This command is DIAGNOSIS-FIRST by default.
**Default behavior (no `--fix` flag)**:
- Diagnose the issue
- Identify root cause
- Propose solution options
- **STOP and present findings to user** - do not apply any fixes
**With `--fix` flag**:
- After diagnosis, prompt user for confirmation before applying
- Apply fix only after user explicitly approves
- Verify fix with tests
**Explicitly Will NOT** (without `--fix` flag):
- Apply any code changes
- Modify any files
- Execute fixes automatically
**Output**: Diagnostic report containing:
- Issue description
- Root cause analysis
- Proposed solutions (ranked)
- Risk assessment for each solution
**Next Step**: User reviews diagnosis, then either:
- Re-run with `--fix` flag to apply recommended fix
- Use `/sc:improve` for broader refactoring

View File

@@ -0,0 +1,118 @@
---
name: workflow
description: "Generate structured implementation workflows from PRDs and feature requirements"
category: orchestration
complexity: advanced
mcp-servers: [sequential, context7, magic, playwright, morphllm, serena]
personas: [architect, analyzer, frontend, backend, security, devops, project-manager]
---
# /sc:workflow - Implementation Workflow Generator
## Triggers
- PRD and feature specification analysis for implementation planning
- Structured workflow generation for development projects
- Multi-persona coordination for complex implementation strategies
- Cross-session workflow management and dependency mapping
## Usage
```
/sc:workflow [prd-file|feature-description] [--strategy systematic|agile|enterprise] [--depth shallow|normal|deep] [--parallel]
```
## Behavioral Flow
1. **Analyze**: Parse PRD and feature specifications to understand implementation requirements
2. **Plan**: Generate comprehensive workflow structure with dependency mapping and task orchestration
3. **Coordinate**: Activate multiple personas for domain expertise and implementation strategy
4. **Execute**: Create structured step-by-step workflows with automated task coordination
5. **Validate**: Apply quality gates and ensure workflow completeness across domains
Key behaviors:
- Multi-persona orchestration across architecture, frontend, backend, security, and devops domains
- Advanced MCP coordination with intelligent routing for specialized workflow analysis
- Systematic execution with progressive workflow enhancement and parallel processing
- Cross-session workflow management with comprehensive dependency tracking
## MCP Integration
- **Sequential MCP**: Complex multi-step workflow analysis and systematic implementation planning
- **Context7 MCP**: Framework-specific workflow patterns and implementation best practices
- **Magic MCP**: UI/UX workflow generation and design system integration strategies
- **Playwright MCP**: Testing workflow integration and quality assurance automation
- **Morphllm MCP**: Large-scale workflow transformation and pattern-based optimization
- **Serena MCP**: Cross-session workflow persistence, memory management, and project context
## Tool Coordination
- **Read/Write/Edit**: PRD analysis and workflow documentation generation
- **TodoWrite**: Progress tracking for complex multi-phase workflow execution
- **Task**: Advanced delegation for parallel workflow generation and multi-agent coordination
- **WebSearch**: Technology research, framework validation, and implementation strategy analysis
- **sequentialthinking**: Structured reasoning for complex workflow dependency analysis
## Key Patterns
- **PRD Analysis**: Document parsing → requirement extraction → implementation strategy development
- **Workflow Generation**: Task decomposition → dependency mapping → structured implementation planning
- **Multi-Domain Coordination**: Cross-functional expertise → comprehensive implementation strategies
- **Quality Integration**: Workflow validation → testing strategies → deployment planning
## Examples
### Systematic PRD Workflow
```
/sc:workflow Claudedocs/PRD/feature-spec.md --strategy systematic --depth deep
# Comprehensive PRD analysis with systematic workflow generation
# Multi-persona coordination for complete implementation strategy
```
### Agile Feature Workflow
```
/sc:workflow "user authentication system" --strategy agile --parallel
# Agile workflow generation with parallel task coordination
# Context7 and Magic MCP for framework and UI workflow patterns
```
### Enterprise Implementation Planning
```
/sc:workflow enterprise-prd.md --strategy enterprise --validate
# Enterprise-scale workflow with comprehensive validation
# Security, devops, and architect personas for compliance and scalability
```
### Cross-Session Workflow Management
```
/sc:workflow project-brief.md --depth normal
# Serena MCP manages cross-session workflow context and persistence
# Progressive workflow enhancement with memory-driven insights
```
## Boundaries
**Will:**
- Generate comprehensive implementation workflows from PRD and feature specifications
- Coordinate multiple personas and MCP servers for complete implementation strategies
- Provide cross-session workflow management and progressive enhancement capabilities
**Will Not:**
- Execute actual implementation tasks beyond workflow planning and strategy
- Override established development processes without proper analysis and validation
- Generate workflows without comprehensive requirement analysis and dependency mapping
## CRITICAL BOUNDARIES
**STOP AFTER PLAN CREATION**
This command produces an IMPLEMENTATION PLAN ONLY - no code execution.
**Explicitly Will NOT**:
- Execute any implementation tasks
- Write or modify code
- Create files (except the workflow plan document)
- Make architectural changes
- Run builds or tests
**Output**: Workflow plan document (`claudedocs/workflow_*.md`) containing:
- Implementation phases
- Task dependencies
- Execution order
- Checkpoints and validation steps
**Next Step**: After workflow completes, use `/sc:implement` to execute the plan step by step.

View File

@@ -0,0 +1,80 @@
---
description: Configure your preferred package manager (npm/pnpm/yarn/bun)
disable-model-invocation: true
---
# Package Manager Setup
Configure your preferred package manager for this project or globally.
## Usage
```bash
# Detect current package manager
node scripts/setup-package-manager.js --detect
# Set global preference
node scripts/setup-package-manager.js --global pnpm
# Set project preference
node scripts/setup-package-manager.js --project bun
# List available package managers
node scripts/setup-package-manager.js --list
```
## Detection Priority
When determining which package manager to use, the following order is checked:
1. **Environment variable**: `CLAUDE_PACKAGE_MANAGER`
2. **Project config**: `.claude/package-manager.json`
3. **package.json**: `packageManager` field
4. **Lock file**: Presence of package-lock.json, yarn.lock, pnpm-lock.yaml, or bun.lockb
5. **Global config**: `~/.claude/package-manager.json`
6. **Fallback**: First available package manager (pnpm > bun > yarn > npm)
## Configuration Files
### Global Configuration
```json
// ~/.claude/package-manager.json
{
"packageManager": "pnpm"
}
```
### Project Configuration
```json
// .claude/package-manager.json
{
"packageManager": "bun"
}
```
### package.json
```json
{
"packageManager": "pnpm@8.6.0"
}
```
## Environment Variable
Set `CLAUDE_PACKAGE_MANAGER` to override all other detection methods:
```bash
# Windows (PowerShell)
$env:CLAUDE_PACKAGE_MANAGER = "pnpm"
# macOS/Linux
export CLAUDE_PACKAGE_MANAGER=pnpm
```
## Run the Detection
To see current package manager detection results, run:
```bash
node scripts/setup-package-manager.js --detect
```

View File

@@ -0,0 +1,324 @@
---
description: Enforce test-driven development workflow. Scaffold interfaces, generate tests FIRST, then implement minimal code to pass. Ensure 80%+ coverage.
---
# TDD Command
This command enforces a test-driven development methodology directly.
## What This Command Does
1. **Scaffold Interfaces** - Define types/interfaces first
2. **Generate Tests First** - Write failing tests (RED)
3. **Implement Minimal Code** - Write just enough to pass (GREEN)
4. **Refactor** - Improve code while keeping tests green (REFACTOR)
5. **Verify Coverage** - Ensure 80%+ test coverage
## When to Use
Use `/tdd` when:
- Implementing new features
- Adding new functions/components
- Fixing bugs (write test that reproduces bug first)
- Refactoring existing code
- Building critical business logic
## How It Works
This command should:
1. **Define interfaces** for inputs/outputs
2. **Write tests that will FAIL** (because code doesn't exist yet)
3. **Run tests** and verify they fail for the right reason
4. **Write minimal implementation** to make tests pass
5. **Run tests** and verify they pass
6. **Refactor** code while keeping tests green
7. **Check coverage** and add more tests if below 80%
## TDD Cycle
```
RED → GREEN → REFACTOR → REPEAT
RED: Write a failing test
GREEN: Write minimal code to pass
REFACTOR: Improve code, keep tests passing
REPEAT: Next feature/scenario
```
## Example Usage
```
User: /tdd I need a function to calculate market liquidity score
Assistant:
# TDD Session: Market Liquidity Score Calculator
## Step 1: Define Interface (SCAFFOLD)
```python
# lib/liquidity.py
from dataclasses import dataclass
from datetime import datetime
from typing import NotRequired
@dataclass
class MarketData:
totalVolume: float
bidAskSpread: float
activeTraders: int
lastTradeTime: datetime
def calculateLiquidityScore(market: MarketData) -> float:
# TODO: Implementation
raise NotImplementedError('Not implemented')
```
## Step 2: Write Failing Test (RED)
```python
# tests/test_liquidity.py
import pytest
from lib.liquidity import calculateLiquidityScore, MarketData
from datetime import datetime
def test_liquid_market_high_score():
"""Test that liquid market gets high score."""
market = MarketData(
totalVolume=100000,
bidAskSpread=0.01,
activeTraders=500,
lastTradeTime=datetime.now()
)
score = calculateLiquidityScore(market)
assert 80 < score <= 100
def test_illiquid_market_low_score():
"""Test that illiquid market gets low score."""
market = MarketData(
totalVolume=100,
bidAskSpread=0.5,
activeTraders=2,
lastTradeTime=datetime.fromtimestamp(datetime.now().timestamp() - 86400) # 1 day ago
)
score = calculateLiquidityScore(market)
assert 0 <= score < 30
def test_zero_volume_edge_case():
"""Test that zero volume returns score of 0."""
market = MarketData(
totalVolume=0,
bidAskSpread=0,
activeTraders=0,
lastTradeTime=datetime.now()
)
score = calculateLiquidityScore(market)
assert score == 0
```
## Step 3: Run Tests - Verify FAIL
```bash
pytest tests/test_liquidity.py -v
FAILED test_liquidity.py::test_liquid_market_high_score
NotImplementedError: Not implemented
1 test failed, 0 passed
```
✅ Tests fail as expected. Ready to implement.
## Step 4: Implement Minimal Code (GREEN)
```python
# lib/liquidity.py
def calculateLiquidityScore(market: MarketData) -> float:
# Handle zero volume edge case
if market.totalVolume == 0:
return 0.0
# Calculate component scores (0-100 scale)
volumeScore = min(market.totalVolume / 1000, 100)
spreadScore = max(100 - (market.bidAskSpread * 1000), 0)
traderScore = min(market.activeTraders / 10, 100)
# Recent activity bonus
hoursSinceLastTrade = (datetime.now().timestamp() - market.lastTradeTime.timestamp()) / 3600
recencyScore = max(100 - (hoursSinceLastTrade * 10), 0)
# Weighted average
score = (
volumeScore * 0.4 +
spreadScore * 0.3 +
traderScore * 0.2 +
recencyScore * 0.1
)
return max(0, min(score, 100)) # Clamp to 0-100
```
## Step 5: Run Tests - Verify PASS
```bash
pytest tests/test_liquidity.py -v
PASSED test_liquidity.py::test_liquid_market_high_score
PASSED test_liquidity.py::test_illiquid_market_low_score
PASSED test_liquidity.py::test_zero_volume_edge_case
3 tests passed
```
✅ All tests passing!
## Step 6: Refactor (IMPROVE)
```python
# lib/liquidity.py - Refactored with constants and better readability
from dataclasses import dataclass
WEIGHTS = {
'VOLUME': 0.4,
'SPREAD': 0.3,
'TRADERS': 0.2,
'RECENCY': 0.1,
}
SCALE_FACTORS = {
'VOLUME': 1000,
'SPREAD': 1000,
'TRADERS': 10,
'RECENCY_PENALTY': 10,
}
def clamp(value: float, min_val: float, max_val: float) -> float:
"""Clamp value between min and max."""
return max(min(value, max_val), min_val)
def calculateLiquidityScore(market: MarketData) -> float:
if market.totalVolume == 0:
return 0.0
volumeScore = min(market.totalVolume / SCALE_FACTORS['VOLUME'], 100)
spreadScore = clamp(100 - (market.bidAskSpread * SCALE_FACTORS['SPREAD']), 0, 100)
traderScore = min(market.activeTraders / SCALE_FACTORS['TRADERS'], 100)
hoursSinceLastTrade = (datetime.now().timestamp() - market.lastTradeTime.timestamp()) / 3600
recencyScore = clamp(100 - (hoursSinceLastTrade * SCALE_FACTORS['RECENCY_PENALTY']), 0, 100)
weightedScore = (
volumeScore * WEIGHTS['VOLUME'] +
spreadScore * WEIGHTS['SPREAD'] +
traderScore * WEIGHTS['TRADERS'] +
recencyScore * WEIGHTS['RECENCY']
)
return clamp(weightedScore, 0, 100)
```
## Step 7: Verify Tests Still Pass
```bash
pytest tests/test_liquidity.py -v
PASSED test_liquidity.py::test_liquid_market_high_score
PASSED test_liquidity.py::test_illiquid_market_low_score
PASSED test_liquidity.py::test_zero_volume_edge_case
3 tests passed
```
✅ Refactoring complete, tests still passing!
## Step 8: Check Coverage
```bash
pytest --cov=lib --cov-report=term-missing tests/test_liquidity.py
File | % Stmts | % Branch | % Funcs | % Lines
---------------|---------|----------|---------|--------
liquidity.py | 100 | 100 | 100 | 100
Coverage: 100% ✅ (Target: 80%)
```
✅ TDD session complete!
```
## TDD Best Practices
**DO:**
- ✅ Write the test FIRST, before any implementation
- ✅ Run tests and verify they FAIL before implementing
- ✅ Write minimal code to make tests pass
- ✅ Refactor only after tests are green
- ✅ Add edge cases and error scenarios
- ✅ Aim for 80%+ coverage (100% for critical code)
**DON'T:**
- ❌ Write implementation before tests
- ❌ Skip running tests after each change
- ❌ Write too much code at once
- ❌ Ignore failing tests
- ❌ Test implementation details (test behavior)
- ❌ Mock everything (prefer integration tests)
## Test Types to Include
**Unit Tests** (Function-level):
- Happy path scenarios
- Edge cases (empty, null, max values)
- Error conditions
- Boundary values
**Integration Tests** (Component-level):
- API endpoints
- Database operations
- External service calls
- React components with hooks
**E2E Tests** (use `/e2e` command):
- Critical user flows
- Multi-step processes
- Full stack integration
## Coverage Requirements
- **80% minimum** for all code
- **100% required** for:
- Financial calculations
- Authentication logic
- Security-critical code
- Core business logic
## Important Notes
**MANDATORY**: Tests must be written BEFORE implementation. The TDD cycle is:
1. **RED** - Write failing test
2. **GREEN** - Implement to pass
3. **REFACTOR** - Improve code
Never skip the RED phase. Never write code before tests.
## Integration with Other Commands
- Use `/plan` first to understand what to build
- Use `/tdd` to implement with tests
- Use `/build-and-fix` if build errors occur
- Use `/code-review` to review implementation
- Use `/test-coverage` to verify coverage
## Related Agents
Use `daily-coding` and `verification-loop` style checks to keep the cycle test-backed and incremental.
And can reference the `tdd-workflow` skill at:
`~/.claude/skills/tdd-workflow/`

View File

@@ -0,0 +1,100 @@
---
description: Commit changes with Conventional Commits format and push to GitHub remote repository.
---
# Update GitHub
Commit uncommitted changes and push to remote GitHub repository.
## Instructions
1. **Check Git Status**
- Run `git status`
- Show all uncommitted changes
2. **Analyze Changes**
- Review changed files
- Determine commit type (feat/fix/docs/refactor/test/chore)
- Determine scope (affected module/component)
3. **Create Commit Message**
Follow Conventional Commits format:
```
<type>(<scope>): <subject>
<body>
<footer>
```
Types:
- `feat`: 新功能
- `fix`: Bug 修复
- `docs`: 文档更新
- `refactor`: 代码重构
- `perf`: 性能优化
- `test`: 测试相关
- `chore`: 其他修改
4. **Stage and Commit**
- Run `git add` for affected files
- Create commit with formatted message
- Do not include `Co-Authored-By` footers unless the user explicitly asks for them
5. **Push to Remote**
- Run `git push`
- If rejected, pull with rebase first:
```bash
git pull --rebase origin $(git branch --show-current)
git push
```
6. **Verify Success**
- Show commit SHA
- Show remote branch status
## Example Usage
```
User: /update-github
1. Checking git status...
Modified: src/utils/helpers.py
Modified: README.md
2. Analyzing changes...
- src/utils/helpers.py: Refactored helper functions
- README.md: Updated documentation
3. Proposed commit:
docs(readme): 更新项目文档
- 添加使用示例
- 更新依赖说明
4. Proceed? (yes/no/modify)
5. Staging files...
git add src/utils/helpers.py README.md
6. Creating commit...
[main abc1234] docs(readme): 更新项目文档
7. Pushing to remote...
git push
To github.com:user/repo.git
abc1234..def5678 main -> main
✅ Successfully pushed to GitHub!
```
## Arguments
$ARGUMENTS can be:
- `--amend` - Amend last commit instead of creating new one
- `--no-verify` - Skip pre-commit hooks
- `<type>(<scope>): <message>` - Use custom commit message
## Integration
This command uses the same Conventional Commits format as the `/commit` skill but focuses on the complete flow: stage → commit → push.

View File

@@ -0,0 +1,126 @@
---
description: Check and update CLAUDE.md memory based on changes to skills, commands, agents, and hooks.
---
# Update Memory
检查并更新 CLAUDE.md 全局记忆文件,确保其内容与 skills、commands、agents、hooks 的源文件保持同步。
## 功能概述
CLAUDE.md 是一个汇总记忆文件,包含:
- 技能目录结构(来自 `skills/`
- 命令列表(来自 `commands/`
- 代理配置(来自 `agents/`
- 钩子定义(来自 `hooks/`
当这些源文件发生变化时CLAUDE.md 需要同步更新。
## 检测逻辑
1. **扫描源文件修改时间**
- `~/.claude/skills/**/skill.md`
- `~/.claude/commands/**/*.md`
- `~/.claude/agents/**/*.md`
- `~/.claude/hooks/**/*.{js,json}`
2. **对比 CLAUDE.md 最后修改时间**
- 如果任意源文件比 CLAUDE.md 新 → 需要更新
- 记录上次同步时间戳(`~/.claude/.last-memory-sync`
3. **生成报告**
- 列出所有变更的源文件
- 显示需要更新的 CLAUDE.md 章节
## 更新流程
### 1. 扫描阶段
```
扫描 Skills: X 个
扫描 Commands: Y 个
扫描 Agents: Z 个
扫描 Hooks: W 个
```
### 2. 对比阶段
```
需要更新的章节:
- [ ] 技能目录结构 (3 个技能变更)
- [ ] 命令列表 (1 个命令新增)
- [ ] 代理配置 (无变更)
- [ ] 钩子定义 (2 个钩子修改)
```
### 3. 确认更新
询问用户是否执行更新:
```
是否更新 CLAUDE.md? (yes/no/diff)
- yes: 执行更新
- no: 取消
- diff: 显示详细差异
```
### 4. 执行更新
- 保留用户手动编辑的内容(如"用户背景"、"技术栈偏好"
- 仅更新 AUTO-GENERATED 标记的章节
- 更新时间戳
## 使用方式
```
/update-memory # 检查并提示更新
/update-memory --check # 仅检查,不更新
/update-memory --force # 强制更新,不询问
/update-memory --diff # 显示差异对比
```
## 输出示例
### 检查结果
```
📋 CLAUDE.md 记忆状态检查
源文件状态:
✅ Skills: 24 个 (最近修改: ml-paper-writing)
✅ Commands: 14 个 (最近修改: update-readme)
✅ Agents: 7 个 (无变更)
✅ Hooks: 5 个 (最近修改: session-summary)
时间对比:
- CLAUDE.md 最后更新: 2024-01-15 10:30
- 源文件最后修改: 2024-01-16 14:22
⚠️ 检测到变更,建议更新 CLAUDE.md
变更详情:
1. skills/ml-paper-writing/skill.md (修改于 14:22)
2. commands/update-readme.md (修改于 13:15)
3. hooks/session-summary.js (修改于 11:45)
是否执行更新? (yes/no/diff)
```
### 更新完成
```
✅ CLAUDE.md 已更新
更新内容:
- 技能目录: 同步 24 个技能
- 命令列表: 同步 14 个命令
- 代理配置: 无变更
- 钩子定义: 同步 5 个钩子
下次同步时间戳已更新。
```
## 集成建议
-`session-summary.js` 中集成检查提醒
- 在 PostToolUse 钩子中实时检测
- 建议定期执行(如每次会话结束时)

View File

@@ -0,0 +1,159 @@
---
description: Update README documentation and push changes to GitHub.
---
# Update README
Update README.md file with latest project information and push to GitHub.
## Instructions
1. **Analyze Current State**
- Read existing README.md
- Check recent code changes (git log)
- Identify documentation gaps
2. **Determine Updates Needed**
Check for:
- New features added
- Configuration changes
- Dependencies updated
- Installation instructions
- Usage examples
- API changes
3. **Propose README Updates**
Show sections that need updating:
```markdown
Proposed changes:
- [ ] Update Installation section (new dependencies)
- [ ] Add usage example for feature X
- [ ] Update API documentation
- [ ] Fix broken links
```
4. **Update README**
- Apply proposed changes
- Maintain markdown formatting
- Keep language consistent (中文/English)
- Preserve structure
5. **Commit and Push**
- Run `/update-github` with `docs(readme):` type
- Example commit: `docs(readme): 更新 README 文档`
## Example Usage
```
User: /update-readme
1. Analyzing repository state...
Recent changes:
- feat(data): 添加新的数据加载器
- fix(model): 修复训练时的内存泄漏
- chore: 更新依赖到 v2.0.0
2. Checking README.md...
Current README sections:
- Installation
- Usage
- API Reference
- Contributing
3. Proposed updates:
[ ] Installation - 添加新的依赖说明
[ ] Usage - 添加数据加载器示例
[ ] API Reference - 更新模型接口文档
4. Applying updates...
Updating Installation:
+ pip install torch>=2.0.0
+ pip install transformers>=4.30.0
Adding usage example:
## 数据加载示例
```python
from data import DataLoader
loader = DataLoader(batch_size=32)
```
5. Review changes before committing...
[Show diff]
6. Proceed with commit?
> yes
7. Committing with: docs(readme): 更新 README 文档
Co-Authored-By: Claude <noreply@anthropic.com>
✅ README updated and pushed to GitHub!
```
## README Structure Template
When updating README, follow this structure:
```markdown
# 项目名称
简短描述项目用途。
## 安装
### 依赖要求
- Python >= 3.8
- uv 或 pip
### 安装步骤
```bash
uv sync
```
## 使用
### 基本用法
```python
# 示例代码
```
### 配置
说明配置文件位置和格式。
## API 文档
主要接口说明。
## 开发
### 运行测试
```bash
pytest
```
### 代码规范
- 遵循 PEP 8
- 使用 mypy 进行类型检查
- 使用 ruff 进行 linting
## 贡献
欢迎提交 Pull Request。
## 许可证
MIT License
```
## Arguments
$ARGUMENTS can be:
- `--full` - Complete README rewrite
- `--quick` - Only update critical sections (installation, usage)
- `<section>` - Update specific section only
## Integration
After updating README, this command automatically invokes `/update-github` with `docs(readme):` commit type.

View File

@@ -0,0 +1,59 @@
# Verification Command
Run comprehensive verification on current codebase state.
## Instructions
Execute verification in this exact order:
1. **Type Check**
- Run mypy src/
- Report all errors with file:line
2. **Lint Check**
- Run ruff check .
- Report warnings and errors
3. **Test Suite**
- Run pytest
- Report pass/fail count
- Report coverage percentage (pytest --cov)
4. **Security Check**
- Run pip-audit
- Check for hardcoded secrets (grep -r "sk-" etc.)
5. **Print Audit**
- Search for print() in source files
- Report locations
6. **Git Status**
- Show uncommitted changes
- Show files modified since last commit
## Output
Produce a concise verification report:
```
VERIFICATION: [PASS/FAIL]
Types: [OK/X errors]
Lint: [OK/X issues]
Tests: [X/Y passed, Z% coverage]
Security: [OK/X vulnerabilities]
Secrets: [OK/X found]
Prints: [OK/X print() statements]
Ready for commit: [YES/NO]
```
If any critical issues, list them with fix suggestions.
## Arguments
$ARGUMENTS can be:
- `quick` - Only types + lint
- `full` - All checks (default)
- `pre-commit` - Checks relevant for commits
- `pre-pr` - Full checks plus security scan

View File

@@ -0,0 +1,128 @@
---
name: zotero-notes
description: Batch read papers from Zotero and create/update detailed reading notes, preferably inside the bound Obsidian project knowledge base
args:
- name: collection
description: Zotero collection name or keyword
required: true
- name: format
description: Note format (summary/detailed/comparison)
required: false
default: detailed
tags: [Research, Zotero, Obsidian, Reading Notes, Paper Analysis]
---
# /zotero-notes - Zotero to Obsidian Reading Notes
Read papers from the Zotero collection "$collection" and create or update detailed reading notes.
## Default target
- **Preferred target**: the bound Obsidian project knowledge base (`Sources/Papers/*.md`)
- **Fallback target**: `reading-notes-{collection}.md` in the working directory if the current repo is not bound to Obsidian
## Workflow
### Step 0: Resolve whether the current repo is Obsidian-bound
1. If `.claude/project-memory/registry.yaml` exists for the current repo, treat the bound vault as the primary output target.
2. If the repo is a research project but not yet bound, bootstrap it first.
3. If there is no bound project context, fall back to a plain markdown output in the working directory.
4. Treat this command as an explicit agent-first ingestion pass under `$zotero-obsidian-bridge`.
### Step 1: Load papers from Zotero
1. Call `mcp__zotero__zotero_get_collections` to find the matching collection.
2. Call `mcp__zotero__zotero_get_collection_items` to list the papers.
3. For each item, call:
- `mcp__zotero__zotero_get_item_metadata`
- `mcp__zotero__zotero_get_item_fulltext` when a PDF is available
- `mcp__zotero__zotero_get_annotations` when helpful
- `mcp__zotero__zotero_get_notes` when helpful
4. If MCP transport fails but a local `zotero-mcp` checkout is available, use the local Python fallback instead of stopping the pass.
5. Treat Zotero `webpage` items as weak-source inputs unless they clearly expose full paper metadata and useful full text. Abstract-only or placeholder pages must stay `To-Read` and cannot support `Knowledge` or `Writing` claims.
### Step 2: Create/update the canonical paper note
If the project is Obsidian-bound, create or update one canonical note per paper under `Sources/Papers/`.
Each detailed note should contain:
- `Claim`
- `Research question`
- `Method`
- `Evidence`
- `Strengths`
- `Limitation`
- `Direct relevance to repo`
- `Relation to other papers`
- `Knowledge links`
- `Optional downstream hooks`
- canonical `Evidence Record` with `Source type` and `Claim strength` when the paper has reusable claims
Recommended frontmatter fields:
- `title`, `authors`, `year`, `venue`, `doi`, `url`, `citekey`, `zotero_key`
- `keywords`, `concepts`, `methods`
- `related_papers`, `linked_knowledge`, `argument_claims`, `argument_methods`, `argument_gaps`, `paper_relationships`
Prefer updating the existing note over creating a sibling note.
### Step 3: Collection coverage and synthesis
After the paper-note pass:
- update a collection inventory note when the source is a named collection
- record item -> canonical note mapping and coverage counts such as `16 / 16`
- verify coverage against expected Zotero keys, DOI values, or arXiv IDs when the user supplied them
- label abstract-only and webpage-placeholder items separately in the inventory
- synthesize durable literature knowledge under `Knowledge/`, for example:
- `Knowledge/Literature Overview.md`
- `Knowledge/Method Taxonomy.md`
- `Knowledge/Research Gaps.md`
Prefer updating existing canonical knowledge notes over creating parallel summaries.
### Step 4: Refresh the default literature canvas
After batch note creation or substantial note updates, refresh:
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/skills/obsidian-literature-workflow/scripts/build_literature_canvas.py" --cwd "$PWD"
```
This rebuilds `Maps/literature.canvas` from paper-note and knowledge-note links.
### Step 5: Optional synthesis outputs
- If `format=comparison` and promoted claims pass the evidence gate, also update `Writing/comparison-matrix.md`.
- If the paper batch already supports a thematic synthesis and promoted claims pass the evidence gate, update `Writing/related-work-draft.md`.
If not, write only a coverage warning or claim map.
### Step 6: Minimal write-back
Always update:
- today's `Daily/YYYY-MM-DD.md`
- repo-local binding summary when project state changes
### Step 7: Final response
Include:
- collection size and coverage summary
- created / updated note paths
- optional `obsidian://open` links
- optional `obsidian open ...` suggestions when CLI is available
## Fallback behavior
If the repo is not bound to Obsidian:
- create `reading-notes-{collection}.md`
- if `format=comparison` and promoted claims pass the evidence gate, also create `comparison-matrix.md`
## Notes
- Zotero remains the source of truth for collection structure, metadata, attachments, PDF full text, and annotations.
- Obsidian remains the durable project knowledge surface for reading notes, project relevance, and cross-note linking.
- Default bridge targets are `Sources/Papers/` and `Knowledge/`.
- Do not dump raw full text into Obsidian paper notes.
- Do not create `Concepts/` or `Datasets/` trees by default.
- Refresh `Maps/literature.canvas` by default after a substantial Zotero ingestion pass.
- Treat `Experiments/` and `Results/` as later project workflows, not the default Zotero-import destination.
- Do not let abstract-only or webpage-placeholder items support durable claims.

View File

@@ -0,0 +1,102 @@
---
name: zotero-review
description: Read and analyze papers from a Zotero collection, then synthesize them into the bound Obsidian project knowledge base or markdown review outputs
args:
- name: collection
description: Zotero collection name or keyword to search
required: true
- name: depth
description: Analysis depth (quick/deep)
required: false
default: deep
tags: [Research, Zotero, Obsidian, Literature Review, Paper Analysis]
---
# /zotero-review - Zotero Collection Literature Analysis
Read and analyze papers in the Zotero collection "$collection", with analysis depth "$depth".
## Default target
- **Preferred target**: the bound Obsidian project knowledge base
- **Fallback target**: `related-work-draft.md` in the current working directory
## Workflow
### Step 0: Resolve the project context
1. If the current repo is already bound to an Obsidian project KB, use that project root.
2. If the repo looks like a research project but is not bound yet, bootstrap it first.
3. If there is no project binding, generate the review in the working directory.
### Step 1: Locate and read the Zotero collection
1. Call `mcp__zotero__zotero_get_collections` to find the matching collection.
2. Call `mcp__zotero__zotero_get_collection_items` to get all papers.
3. For each paper:
- call `mcp__zotero__zotero_get_item_metadata` with `include_abstract: true`
- call `mcp__zotero__zotero_get_item_fulltext` when available
- use abstract metadata as fallback when PDF full text is unavailable
4. If MCP transport fails but a local `zotero-mcp` checkout is available, use the local Python fallback instead of aborting.
5. Treat Zotero `webpage` items as weak-source entries unless they clearly expose full paper metadata and useful full text. Abstract-only or placeholder pages can appear in coverage summaries, but cannot support `Knowledge`, `Writing`, manuscript, or rebuttal claims.
### Step 2: Ensure detailed paper notes exist
Before high-level synthesis, ensure the collection has durable paper notes.
If the project is Obsidian-bound:
- create or update `Sources/Papers/*.md` canonical notes first
- keep one canonical paper note per paper whenever possible
- align notes to the canonical schema (`Claim / Method / Evidence / Limitation / Direct relevance to repo / Relation to other papers`)
- update the best matching `Knowledge/` literature synthesis notes
- refresh `Maps/literature.canvas`
- update a collection inventory note with item -> note mapping and coverage summary
If not Obsidian-bound:
- create intermediate `paper-notes/*.md` files in the working directory when `depth=deep`
### Step 3: Synthesize across paper notes
Create or update:
- `Knowledge/Literature Overview.md`
- `Knowledge/Method Taxonomy.md` when useful
- `Knowledge/Research Gaps.md` when useful
- `Writing/related-work-draft.md` only when the user wants writing-facing synthesis and the promoted claims pass the evidence gate
- `Writing/comparison-matrix.md` when useful and promoted claims pass the evidence gate
The synthesis should include:
- thematic grouping
- method families
- key findings and tensions
- research gaps
- direct relevance to the current project
- explicit links across `Sources/Papers/` and `Knowledge/`
- Evidence Record IDs, source type, claim strength, allowed wording, and forbidden stronger wording for claims that may later enter writing or rebuttal
If core papers lack full text or Evidence Records, stop at a collection audit / claim map and state what is missing. Do not generate a polished related-work draft from weak notes.
### Step 4: Push downstream only when justified
- keep the default review surface in `Sources/Papers/`, `Knowledge/`, and `Maps/literature.canvas`
- update `Writing/` only when the user wants a manuscript-facing review or comparison narrative and promoted claims pass the evidence gate
- only update `Experiments/` or `Results/` in a later project workflow when the user explicitly wants that handoff
### Step 5: Minimal write-back
Always update:
- today's `Daily/YYYY-MM-DD.md`
- repo-local binding summary when project state changes
### Step 6: Final response
Include:
- collection size and coverage summary
- updated note paths
- optional `obsidian://open` links
- optional `obsidian open ...` suggestions when CLI is available
## Notes
- Prefer the Obsidian-bound project workflow over loose markdown files when available.
- Keep `Sources/Papers/` first-class; the review should be grounded in canonical paper notes rather than only one-shot synthesis.
- The default graph artifact is `Maps/literature.canvas`.