diff --git a/.claude/commands/memory/compact.md b/.claude/commands/memory/compact.md deleted file mode 100644 index 2146bbf2..00000000 --- a/.claude/commands/memory/compact.md +++ /dev/null @@ -1,383 +0,0 @@ ---- -name: compact -description: Compact current session memory into structured text for session recovery, extracting objective/plan/files/decisions/constraints/state, and save via MCP core_memory tool -argument-hint: "[optional: session description]" -allowed-tools: mcp__ccw-tools__core_memory(*), Read(*) -examples: - - /memory:compact - - /memory:compact "completed core-memory module" ---- - -# Memory Compact Command (/memory:compact) - -## 1. Overview - -The `memory:compact` command **compresses current session working memory** into structured text optimized for **session recovery**, extracts critical information, and saves it to persistent storage via MCP `core_memory` tool. - -**Core Philosophy**: -- **Session Recovery First**: Capture everything needed to resume work seamlessly -- **Minimize Re-exploration**: Include file paths, decisions, and state to avoid redundant analysis -- **Preserve Train of Thought**: Keep notes and hypotheses for complex debugging -- **Actionable State**: Record last action result and known issues - -## 2. Parameters - -- `"session description"` (Optional): Session description to supplement objective - - Example: "completed core-memory module" - - Example: "debugging JWT refresh - suspected memory leak" - -## 3. Structured Output Format - -```markdown -## Session ID -[WFS-ID if workflow session active, otherwise (none)] - -## Project Root -[Absolute path to project root, e.g., D:\Claude_dms3] - -## Objective -[High-level goal - the "North Star" of this session] - -## Execution Plan -[CRITICAL: Embed the LATEST plan in its COMPLETE and DETAILED form] - -### Source: [workflow | todo | user-stated | inferred] - -
-Full Execution Plan (Click to expand) - -[PRESERVE COMPLETE PLAN VERBATIM - DO NOT SUMMARIZE] -- ALL phases, tasks, subtasks -- ALL file paths (absolute) -- ALL dependencies and prerequisites -- ALL acceptance criteria -- ALL status markers ([x] done, [ ] pending) -- ALL notes and context - -Example: -## Phase 1: Setup -- [x] Initialize project structure - - Created D:\Claude_dms3\src\core\index.ts - - Added dependencies: lodash, zod -- [ ] Configure TypeScript - - Update tsconfig.json for strict mode - -## Phase 2: Implementation -- [ ] Implement core API - - Target: D:\Claude_dms3\src\api\handler.ts - - Dependencies: Phase 1 complete - - Acceptance: All tests pass - -
- -## Working Files (Modified) -[Absolute paths to actively modified files] -- D:\Claude_dms3\src\file1.ts (role: main implementation) -- D:\Claude_dms3\tests\file1.test.ts (role: unit tests) - -## Reference Files (Read-Only) -[Absolute paths to context files - NOT modified but essential for understanding] -- D:\Claude_dms3\.claude\CLAUDE.md (role: project instructions) -- D:\Claude_dms3\src\types\index.ts (role: type definitions) -- D:\Claude_dms3\package.json (role: dependencies) - -## Last Action -[Last significant action and its result/status] - -## Decisions -- [Decision]: [Reasoning] -- [Decision]: [Reasoning] - -## Constraints -- [User-specified limitation or preference] - -## Dependencies -- [Added/changed packages or environment requirements] - -## Known Issues -- [Deferred bug or edge case] - -## Changes Made -- [Completed modification] - -## Pending -- [Next step] or (none) - -## Notes -[Unstructured thoughts, hypotheses, debugging trails] -``` - -## 4. Field Definitions - -| Field | Purpose | Recovery Value | -|-------|---------|----------------| -| **Session ID** | Workflow session identifier (WFS-*) | Links memory to specific stateful task execution | -| **Project Root** | Absolute path to project directory | Enables correct path resolution in new sessions | -| **Objective** | Ultimate goal of the session | Prevents losing track of broader feature | -| **Execution Plan** | Complete plan from any source (verbatim) | Preserves full planning context, avoids re-planning | -| **Working Files** | Actively modified files (absolute paths) | Immediately identifies where work was happening | -| **Reference Files** | Read-only context files (absolute paths) | Eliminates re-exploration for critical context | -| **Last Action** | Final tool output/status | Immediate state awareness (success/failure) | -| **Decisions** | Architectural choices + reasoning | Prevents re-litigating settled decisions | -| **Constraints** | User-imposed limitations | Maintains personalized coding style | -| **Dependencies** | Package/environment changes | Prevents missing dependency errors | -| **Known Issues** | Deferred bugs/edge cases | Ensures issues aren't forgotten | -| **Changes Made** | Completed modifications | Clear record of what was done | -| **Pending** | Next steps | Immediate action items | -| **Notes** | Hypotheses, debugging trails | Preserves "train of thought" | - -## 5. Execution Flow - -### Step 1: Analyze Current Session - -Extract the following from conversation history: - -```javascript -const sessionAnalysis = { - sessionId: "", // WFS-* if workflow session active, null otherwise - projectRoot: "", // Absolute path: D:\Claude_dms3 - objective: "", // High-level goal (1-2 sentences) - executionPlan: { - source: "workflow" | "todo" | "user-stated" | "inferred", - content: "" // Full plan content - ALWAYS preserve COMPLETE and DETAILED form - }, - workingFiles: [], // {absolutePath, role} - modified files - referenceFiles: [], // {absolutePath, role} - read-only context files - lastAction: "", // Last significant action + result - decisions: [], // {decision, reasoning} - constraints: [], // User-specified limitations - dependencies: [], // Added/changed packages - knownIssues: [], // Deferred bugs - changesMade: [], // Completed modifications - pending: [], // Next steps - notes: "" // Unstructured thoughts -} -``` - -### Step 2: Generate Structured Text - -```javascript -// Helper: Generate execution plan section -const generateExecutionPlan = (plan) => { - const sourceLabels = { - 'workflow': 'workflow (IMPL_PLAN.md)', - 'todo': 'todo (TodoWrite)', - 'user-stated': 'user-stated', - 'inferred': 'inferred' - }; - - // CRITICAL: Preserve complete plan content verbatim - DO NOT summarize - return `### Source: ${sourceLabels[plan.source] || plan.source} - -
-Full Execution Plan (Click to expand) - -${plan.content} - -
`; -}; - -const structuredText = `## Session ID -${sessionAnalysis.sessionId || '(none)'} - -## Project Root -${sessionAnalysis.projectRoot} - -## Objective -${sessionAnalysis.objective} - -## Execution Plan -${generateExecutionPlan(sessionAnalysis.executionPlan)} - -## Working Files (Modified) -${sessionAnalysis.workingFiles.map(f => `- ${f.absolutePath} (role: ${f.role})`).join('\n') || '(none)'} - -## Reference Files (Read-Only) -${sessionAnalysis.referenceFiles.map(f => `- ${f.absolutePath} (role: ${f.role})`).join('\n') || '(none)'} - -## Last Action -${sessionAnalysis.lastAction} - -## Decisions -${sessionAnalysis.decisions.map(d => `- ${d.decision}: ${d.reasoning}`).join('\n') || '(none)'} - -## Constraints -${sessionAnalysis.constraints.map(c => `- ${c}`).join('\n') || '(none)'} - -## Dependencies -${sessionAnalysis.dependencies.map(d => `- ${d}`).join('\n') || '(none)'} - -## Known Issues -${sessionAnalysis.knownIssues.map(i => `- ${i}`).join('\n') || '(none)'} - -## Changes Made -${sessionAnalysis.changesMade.map(c => `- ${c}`).join('\n') || '(none)'} - -## Pending -${sessionAnalysis.pending.length > 0 - ? sessionAnalysis.pending.map(p => `- ${p}`).join('\n') - : '(none)'} - -## Notes -${sessionAnalysis.notes || '(none)'}` -``` - -### Step 3: Import to Core Memory via MCP - -Use the MCP `core_memory` tool to save the structured text: - -```javascript -mcp__ccw-tools__core_memory({ - operation: "import", - text: structuredText -}) -``` - -Or via CLI (pipe structured text to import): - -```bash -# Write structured text to temp file, then import -echo "$structuredText" | ccw core-memory import - -# Or from a file -ccw core-memory import --file /path/to/session-memory.md -``` - -**Response Format**: -```json -{ - "operation": "import", - "id": "CMEM-YYYYMMDD-HHMMSS", - "message": "Created memory: CMEM-YYYYMMDD-HHMMSS" -} -``` - -### Step 4: Report Recovery ID - -After successful import, **clearly display the Recovery ID** to the user: - -``` -╔════════════════════════════════════════════════════════════════════════════╗ -║ ✓ Session Memory Saved ║ -║ ║ -║ Recovery ID: CMEM-YYYYMMDD-HHMMSS ║ -║ ║ -║ To restore: "Please import memory " ║ -║ (MCP: core_memory export | CLI: ccw core-memory export --id ) ║ -╚════════════════════════════════════════════════════════════════════════════╝ -``` - -## 6. Quality Checklist - -Before generating: -- [ ] Session ID captured if workflow session active (WFS-*) -- [ ] Project Root is absolute path (e.g., D:\Claude_dms3) -- [ ] Objective clearly states the "North Star" goal -- [ ] Execution Plan: COMPLETE plan preserved VERBATIM (no summarization) -- [ ] Plan Source: Clearly identified (workflow | todo | user-stated | inferred) -- [ ] Plan Details: ALL phases, tasks, file paths, dependencies, status markers included -- [ ] All file paths are ABSOLUTE (not relative) -- [ ] Working Files: 3-8 modified files with roles -- [ ] Reference Files: Key context files (CLAUDE.md, types, configs) -- [ ] Last Action captures final state (success/failure) -- [ ] Decisions include reasoning, not just choices -- [ ] Known Issues separates deferred from forgotten bugs -- [ ] Notes preserve debugging hypotheses if any - -## 7. Path Resolution Rules - -### Project Root Detection -1. Check current working directory from environment -2. Look for project markers: `.git/`, `package.json`, `.claude/` -3. Use the topmost directory containing these markers - -### Absolute Path Conversion -```javascript -// Convert relative to absolute -const toAbsolutePath = (relativePath, projectRoot) => { - if (path.isAbsolute(relativePath)) return relativePath; - return path.join(projectRoot, relativePath); -}; - -// Example: "src/api/auth.ts" → "D:\Claude_dms3\src\api\auth.ts" -``` - -### Reference File Categories -| Category | Examples | Priority | -|----------|----------|----------| -| Project Config | `.claude/CLAUDE.md`, `package.json`, `tsconfig.json` | High | -| Type Definitions | `src/types/*.ts`, `*.d.ts` | High | -| Related Modules | Parent/sibling modules with shared interfaces | Medium | -| Test Files | Corresponding test files for modified code | Medium | -| Documentation | `README.md`, `ARCHITECTURE.md` | Low | - -## 8. Plan Detection (Priority Order) - -### Priority 1: Workflow Session (IMPL_PLAN.md) -```javascript -// Check for active workflow session -const manifest = await mcp__ccw-tools__session_manager({ - operation: "list", - location: "active" -}); - -if (manifest.sessions?.length > 0) { - const session = manifest.sessions[0]; - const plan = await mcp__ccw-tools__session_manager({ - operation: "read", - session_id: session.id, - content_type: "plan" - }); - sessionAnalysis.sessionId = session.id; - sessionAnalysis.executionPlan.source = "workflow"; - sessionAnalysis.executionPlan.content = plan.content; -} -``` - -### Priority 2: TodoWrite (Current Session Todos) -```javascript -// Extract from conversation - look for TodoWrite tool calls -// Preserve COMPLETE todo list with all details -const todos = extractTodosFromConversation(); -if (todos.length > 0) { - sessionAnalysis.executionPlan.source = "todo"; - // Format todos with full context - preserve status markers - sessionAnalysis.executionPlan.content = todos.map(t => - `- [${t.status === 'completed' ? 'x' : t.status === 'in_progress' ? '>' : ' '}] ${t.content}` - ).join('\n'); -} -``` - -### Priority 3: User-Stated Plan -```javascript -// Look for explicit plan statements in user messages: -// - "Here's my plan: 1. ... 2. ... 3. ..." -// - "I want to: first..., then..., finally..." -// - Numbered or bulleted lists describing steps -const userPlan = extractUserStatedPlan(); -if (userPlan) { - sessionAnalysis.executionPlan.source = "user-stated"; - sessionAnalysis.executionPlan.content = userPlan; -} -``` - -### Priority 4: Inferred Plan -```javascript -// If no explicit plan, infer from: -// - Task description and breakdown discussion -// - Sequence of actions taken -// - Outstanding work mentioned -const inferredPlan = inferPlanFromDiscussion(); -if (inferredPlan) { - sessionAnalysis.executionPlan.source = "inferred"; - sessionAnalysis.executionPlan.content = inferredPlan; -} -``` - -## 9. Notes - -- **Timing**: Execute at task completion or before context switch -- **Frequency**: Once per independent task or milestone -- **Recovery**: New session can immediately continue with full context -- **Knowledge Graph**: Entity relationships auto-extracted for visualization -- **Absolute Paths**: Critical for cross-session recovery on different machines diff --git a/.claude/commands/memory/tips.md b/.claude/commands/memory/tips.md deleted file mode 100644 index 52082a81..00000000 --- a/.claude/commands/memory/tips.md +++ /dev/null @@ -1,332 +0,0 @@ ---- -name: tips -description: Quick note-taking command to capture ideas, snippets, reminders, and insights for later reference -argument-hint: " [--tag ] [--context ]" -allowed-tools: mcp__ccw-tools__core_memory(*), Read(*) -examples: - - /memory:tips "Remember to use Redis for rate limiting" - - /memory:tips "Auth pattern: JWT with refresh tokens" --tag architecture,auth - - /memory:tips "Bug: memory leak in WebSocket handler after 24h" --context websocket-service - - /memory:tips "Performance: lazy loading reduced bundle by 40%" --tag performance ---- - -# Memory Tips Command (/memory:tips) - -## 1. Overview - -The `memory:tips` command provides **quick note-taking** for capturing: -- Quick ideas and insights -- Code snippets and patterns -- Reminders and follow-ups -- Bug notes and debugging hints -- Performance observations -- Architecture decisions -- Library/tool recommendations - -**Core Philosophy**: -- **Speed First**: Minimal friction for capturing thoughts -- **Searchable**: Tagged for easy retrieval -- **Context-Aware**: Optional context linking -- **Lightweight**: No complex session analysis - -## 2. Parameters - -- `` (Required): The tip/note content to save -- `--tag ` (Optional): Comma-separated tags for categorization -- `--context ` (Optional): Related context (file, module, feature) - -**Examples**: -```bash -/memory:tips "Use Zod for runtime validation - better DX than class-validator" -/memory:tips "Redis connection pool: max 10, min 2" --tag config,redis -/memory:tips "Fix needed: race condition in payment processor" --tag bug,payment --context src/payments -``` - -## 3. Structured Output Format - -```markdown -## Tip ID -TIP-YYYYMMDD-HHMMSS - -## Timestamp -YYYY-MM-DD HH:MM:SS - -## Project Root -[Absolute path to project root, e.g., D:\Claude_dms3] - -## Content -[The tip/note content exactly as provided] - -## Tags -[Comma-separated tags, or (none)] - -## Context -[Optional context linking - file, module, or feature reference] - -## Session Link -[WFS-ID if workflow session active, otherwise (none)] - -## Auto-Detected Context -[Files/topics from current conversation if relevant] -``` - -## 4. Field Definitions - -| Field | Purpose | Example | -|-------|---------|---------| -| **Tip ID** | Unique identifier with timestamp | TIP-20260128-143052 | -| **Timestamp** | When tip was created | 2026-01-28 14:30:52 | -| **Project Root** | Current project path | D:\Claude_dms3 | -| **Content** | The actual tip/note | "Use Redis for rate limiting" | -| **Tags** | Categorization labels | architecture, auth, performance | -| **Context** | Related code/feature | src/auth/**, payment-module | -| **Session Link** | Link to workflow session | WFS-auth-20260128 | -| **Auto-Detected Context** | Files from conversation | src/api/handler.ts | - -## 5. Execution Flow - -### Step 1: Parse Arguments - -```javascript -const parseTipsCommand = (input) => { - // Extract note content (everything before flags) - const contentMatch = input.match(/^"([^"]+)"|^([^\s-]+)/); - const content = contentMatch ? (contentMatch[1] || contentMatch[2]) : ''; - - // Extract tags - const tagsMatch = input.match(/--tag\s+([^\s-]+)/); - const tags = tagsMatch ? tagsMatch[1].split(',').map(t => t.trim()) : []; - - // Extract context - const contextMatch = input.match(/--context\s+([^\s-]+)/); - const context = contextMatch ? contextMatch[1] : ''; - - return { content, tags, context }; -}; -``` - -### Step 2: Gather Context - -```javascript -const gatherTipContext = async () => { - // Get project root - const projectRoot = process.cwd(); // or detect from environment - - // Get current session if active - const manifest = await mcp__ccw-tools__session_manager({ - operation: "list", - location: "active" - }); - const sessionId = manifest.sessions?.[0]?.id || null; - - // Auto-detect files from recent conversation - const recentFiles = extractRecentFilesFromConversation(); // Last 5 messages - - return { - projectRoot, - sessionId, - autoDetectedContext: recentFiles - }; -}; -``` - -### Step 3: Generate Structured Text - -```javascript -const generateTipText = (parsed, context) => { - const timestamp = new Date().toISOString().replace('T', ' ').slice(0, 19); - const tipId = `TIP-${new Date().toISOString().slice(0,10).replace(/-/g, '')}-${new Date().toTimeString().slice(0,8).replace(/:/g, '')}`; - - return `## Tip ID -${tipId} - -## Timestamp -${timestamp} - -## Project Root -${context.projectRoot} - -## Content -${parsed.content} - -## Tags -${parsed.tags.length > 0 ? parsed.tags.join(', ') : '(none)'} - -## Context -${parsed.context || '(none)'} - -## Session Link -${context.sessionId || '(none)'} - -## Auto-Detected Context -${context.autoDetectedContext.length > 0 - ? context.autoDetectedContext.map(f => `- ${f}`).join('\n') - : '(none)'}`; -}; -``` - -### Step 4: Save to Core Memory - -```javascript -mcp__ccw-tools__core_memory({ - operation: "import", - text: structuredText -}) -``` - -**Response Format**: -```json -{ - "operation": "import", - "id": "CMEM-YYYYMMDD-HHMMSS", - "message": "Created memory: CMEM-YYYYMMDD-HHMMSS" -} -``` - -### Step 5: Confirm to User - -``` -✓ Tip saved successfully - - ID: CMEM-YYYYMMDD-HHMMSS - Tags: architecture, auth - Context: src/auth/** - - To retrieve: /memory:search "auth patterns" - Or via MCP: core_memory(operation="search", query="auth") -``` - -## 6. Tag Categories (Suggested) - -**Technical**: -- `architecture` - Design decisions and patterns -- `performance` - Optimization insights -- `security` - Security considerations -- `bug` - Bug notes and fixes -- `config` - Configuration settings -- `api` - API design patterns - -**Development**: -- `testing` - Test strategies and patterns -- `debugging` - Debugging techniques -- `refactoring` - Refactoring notes -- `documentation` - Doc improvements - -**Domain Specific**: -- `auth` - Authentication/authorization -- `database` - Database patterns -- `frontend` - UI/UX patterns -- `backend` - Backend logic -- `devops` - Infrastructure and deployment - -**Organizational**: -- `reminder` - Follow-up items -- `research` - Research findings -- `idea` - Feature ideas -- `review` - Code review notes - -## 7. Search Integration - -Tips can be retrieved using: - -```bash -# Via command (if /memory:search exists) -/memory:search "rate limiting" - -# Via MCP tool -mcp__ccw-tools__core_memory({ - operation: "search", - query: "rate limiting", - source_type: "core_memory", - top_k: 10 -}) - -# Via CLI -ccw core-memory search --query "rate limiting" --top-k 10 -``` - -## 8. Quality Checklist - -Before saving: -- [ ] Content is clear and actionable -- [ ] Tags are relevant and consistent -- [ ] Context provides enough reference -- [ ] Auto-detected context is accurate -- [ ] Project root is absolute path -- [ ] Timestamp is properly formatted - -## 9. Best Practices - -### Good Tips Examples - -✅ **Specific and Actionable**: -``` -"Use connection pooling for Redis: { max: 10, min: 2, acquireTimeoutMillis: 30000 }" ---tag config,redis -``` - -✅ **With Context**: -``` -"Auth middleware must validate both access and refresh tokens" ---tag security,auth --context src/middleware/auth.ts -``` - -✅ **Problem + Solution**: -``` -"Memory leak fixed by unsubscribing event listeners in componentWillUnmount" ---tag bug,react --context src/components/Chat.tsx -``` - -### Poor Tips Examples - -❌ **Too Vague**: -``` -"Fix the bug" --tag bug -``` - -❌ **Too Long** (use /memory:compact instead): -``` -"Here's the complete implementation plan for the entire auth system... [3 paragraphs]" -``` - -❌ **No Context**: -``` -"Remember to update this later" -``` - -## 10. Use Cases - -### During Development -```bash -/memory:tips "JWT secret must be 256-bit minimum" --tag security,auth -/memory:tips "Use debounce (300ms) for search input" --tag performance,ux -``` - -### After Bug Fixes -```bash -/memory:tips "Race condition in payment: lock with Redis SETNX" --tag bug,payment -``` - -### Code Review Insights -```bash -/memory:tips "Prefer early returns over nested ifs" --tag style,readability -``` - -### Architecture Decisions -```bash -/memory:tips "Chose PostgreSQL over MongoDB for ACID compliance" --tag architecture,database -``` - -### Library Recommendations -```bash -/memory:tips "Zod > Yup for TypeScript validation - better type inference" --tag library,typescript -``` - -## 11. Notes - -- **Frequency**: Use liberally - capture all valuable insights -- **Retrieval**: Search by tags, content, or context -- **Lifecycle**: Tips persist across sessions -- **Organization**: Tags enable filtering and categorization -- **Integration**: Can reference tips in later workflows -- **Lightweight**: No complex session analysis required diff --git a/.claude/skills/memory-capture/SKILL.md b/.claude/skills/memory-capture/SKILL.md new file mode 100644 index 00000000..57a5281c --- /dev/null +++ b/.claude/skills/memory-capture/SKILL.md @@ -0,0 +1,129 @@ +--- +name: memory-capture +description: Unified memory capture with routing - session compact or quick tips. Triggers on "memory capture", "compact session", "save session", "quick tip", "memory tips", "记录", "压缩会话". +allowed-tools: mcp__ccw-tools__core_memory(*), Read(*), AskUserQuestion +--- + +# Memory Capture Skill + +Unified memory capture skill that routes to two execution modes: +- **Compact**: Compress full session memory into structured text for recovery +- **Tips**: Quick note-taking for ideas, snippets, and insights + +## Architecture Overview + +``` +┌─────────────────────────────────────────────────────┐ +│ Memory Capture (Router) │ +│ → Parse input → Detect mode → Route to phase │ +└───────────────┬─────────────────────────────────────┘ + │ + ┌───────┴───────┐ + ↓ ↓ + ┌───────────┐ ┌───────────┐ + │ Compact │ │ Tips │ + │ (Phase1) │ │ (Phase2) │ + │ Full │ │ Quick │ + │ Session │ │ Note │ + └─────┬─────┘ └─────┬─────┘ + │ │ + └───────┬───────┘ + ↓ + ┌───────────────┐ + │ core_memory │ + │ (import) │ + └───────────────┘ +``` + +## Execution Flow + +### Step 1: Parse Input & Route + +Detect execution mode from user input: + +**Auto-Route Rules** (priority order): + +| Signal | Route | Examples | +|--------|-------|---------| +| Keyword: compact, session, 压缩, recovery, 保存会话 | → Compact | "compact current session" | +| Keyword: tip, note, 记录, 快速 | → Tips | "记录一个想法" | +| Has `--tag` or `--context` flags | → Tips | `"note content" --tag bug` | +| Short text (<100 chars) + no session keywords | → Tips | "Remember to use Redis" | +| Ambiguous or no arguments | → **AskUserQuestion** | `/memory-capture` | + +**When ambiguous**, use AskUserQuestion: + +``` +Question: "选择记忆捕获模式" +Options: + 1. Compact - 压缩当前完整会话记忆(用于会话恢复) + 2. Tips - 快速记录一条笔记/想法/提示 +``` + +### Step 2: Execute Selected Phase + +Based on routing result, read and execute the corresponding phase: + +- **Compact mode** → Ref: [phases/01-compact.md](phases/01-compact.md) +- **Tips mode** → Ref: [phases/02-tips.md](phases/02-tips.md) + +**Phase Reference Documents** (read on-demand when phase executes): + +| Mode | Document | Purpose | +|------|----------|---------| +| Compact | [phases/01-compact.md](phases/01-compact.md) | Full session memory compression and structured export | +| Tips | [phases/02-tips.md](phases/02-tips.md) | Quick note-taking with tags and context | + +### Step 3: Save via core_memory + +Both phases converge on the same storage mechanism: + +```javascript +mcp__ccw-tools__core_memory({ + operation: "import", + text: structuredText // Generated by the selected phase +}) +``` + +## Core Rules + +1. **Single Phase Execution**: Only ONE phase executes per invocation - never both +2. **Content Faithful**: Phase files contain full execution detail - follow them verbatim +3. **Absolute Paths**: All file paths in output must be absolute +4. **No Summarization**: Compact mode preserves complete plan verbatim - never abbreviate +5. **Speed Priority**: Tips mode should be fast - minimal analysis overhead + +## Input Processing + +### Compact Mode Input +- Optional: `"session description"` as supplementary context +- Example: `/memory-capture compact` or `/memory-capture "completed auth module"` + +### Tips Mode Input +- Required: `` - the tip/note text +- Optional: `--tag ` for categorization +- Optional: `--context ` for related code/feature reference +- Example: `/memory-capture tip "Use Redis for rate limiting" --tag config` + +## Data Flow + +``` +User Input + │ + ├─ [compact detected] → Read phases/01-compact.md + │ → Analyze session → Generate structured text + │ → core_memory import → Report Recovery ID + │ + └─ [tips detected] → Read phases/02-tips.md + → Parse args → Gather context → Generate tip text + → core_memory import → Confirm with ID + tags +``` + +## Error Handling + +| Error | Action | +|-------|--------| +| core_memory import fails | Retry once, then report error with structured text for manual save | +| No session context (compact) | Warn user, generate with available info | +| Empty note content (tips) | Ask user to provide content via AskUserQuestion | +| Ambiguous routing | Default to AskUserQuestion - never guess | diff --git a/.claude/skills/memory-capture/phases/01-compact.md b/.claude/skills/memory-capture/phases/01-compact.md new file mode 100644 index 00000000..7862bf40 --- /dev/null +++ b/.claude/skills/memory-capture/phases/01-compact.md @@ -0,0 +1,254 @@ +# Phase 1: Compact - Session Memory Compression + +Compress current session working memory into structured text optimized for session recovery, extract critical information, and save to persistent storage via MCP `core_memory` tool. + +## Objective + +- Capture everything needed to resume work seamlessly in a new session +- Minimize re-exploration by including file paths, decisions, and state +- Preserve train of thought for complex debugging +- Record actionable state (last action, known issues, pending) + +## Input + +- `sessionDescription` (Optional): User-provided session description string + - Example: `"completed core-memory module"` + - Example: `"debugging JWT refresh - suspected memory leak"` + +## Execution + +### Step 1.1: Analyze Current Session + +Extract the following from conversation history: + +```javascript +const sessionAnalysis = { + sessionId: "", // WFS-* if workflow session active, null otherwise + projectRoot: "", // Absolute path: D:\Claude_dms3 + objective: "", // High-level goal (1-2 sentences) + executionPlan: { + source: "workflow" | "todo" | "user-stated" | "inferred", + content: "" // Full plan content - ALWAYS preserve COMPLETE and DETAILED form + }, + workingFiles: [], // {absolutePath, role} - modified files + referenceFiles: [], // {absolutePath, role} - read-only context files + lastAction: "", // Last significant action + result + decisions: [], // {decision, reasoning} + constraints: [], // User-specified limitations + dependencies: [], // Added/changed packages + knownIssues: [], // Deferred bugs + changesMade: [], // Completed modifications + pending: [], // Next steps + notes: "" // Unstructured thoughts +} +``` + +**Core Philosophy**: +- **Session Recovery First**: Capture everything needed to resume work seamlessly +- **Minimize Re-exploration**: Include file paths, decisions, and state to avoid redundant analysis +- **Preserve Train of Thought**: Keep notes and hypotheses for complex debugging +- **Actionable State**: Record last action result and known issues + +### Step 1.2: Plan Detection (Priority Order) + +**Priority 1: Workflow Session (IMPL_PLAN.md)** +```javascript +// Check for active workflow session +const manifest = await mcp__ccw-tools__session_manager({ + operation: "list", + location: "active" +}); + +if (manifest.sessions?.length > 0) { + const session = manifest.sessions[0]; + const plan = await mcp__ccw-tools__session_manager({ + operation: "read", + session_id: session.id, + content_type: "plan" + }); + sessionAnalysis.sessionId = session.id; + sessionAnalysis.executionPlan.source = "workflow"; + sessionAnalysis.executionPlan.content = plan.content; +} +``` + +**Priority 2: TodoWrite (Current Session Todos)** +```javascript +// Extract from conversation - look for TodoWrite tool calls +// Preserve COMPLETE todo list with all details +const todos = extractTodosFromConversation(); +if (todos.length > 0) { + sessionAnalysis.executionPlan.source = "todo"; + sessionAnalysis.executionPlan.content = todos.map(t => + `- [${t.status === 'completed' ? 'x' : t.status === 'in_progress' ? '>' : ' '}] ${t.content}` + ).join('\n'); +} +``` + +**Priority 3: User-Stated Plan** +```javascript +// Look for explicit plan statements in user messages: +// - "Here's my plan: 1. ... 2. ... 3. ..." +// - "I want to: first..., then..., finally..." +// - Numbered or bulleted lists describing steps +const userPlan = extractUserStatedPlan(); +if (userPlan) { + sessionAnalysis.executionPlan.source = "user-stated"; + sessionAnalysis.executionPlan.content = userPlan; +} +``` + +**Priority 4: Inferred Plan** +```javascript +// If no explicit plan, infer from: +// - Task description and breakdown discussion +// - Sequence of actions taken +// - Outstanding work mentioned +const inferredPlan = inferPlanFromDiscussion(); +if (inferredPlan) { + sessionAnalysis.executionPlan.source = "inferred"; + sessionAnalysis.executionPlan.content = inferredPlan; +} +``` + +### Step 1.3: Generate Structured Text + +```javascript +const generateExecutionPlan = (plan) => { + const sourceLabels = { + 'workflow': 'workflow (IMPL_PLAN.md)', + 'todo': 'todo (TodoWrite)', + 'user-stated': 'user-stated', + 'inferred': 'inferred' + }; + + // CRITICAL: Preserve complete plan content verbatim - DO NOT summarize + return `### Source: ${sourceLabels[plan.source] || plan.source} + +
+Full Execution Plan (Click to expand) + +${plan.content} + +
`; +}; + +const structuredText = `## Session ID +${sessionAnalysis.sessionId || '(none)'} + +## Project Root +${sessionAnalysis.projectRoot} + +## Objective +${sessionAnalysis.objective} + +## Execution Plan +${generateExecutionPlan(sessionAnalysis.executionPlan)} + +## Working Files (Modified) +${sessionAnalysis.workingFiles.map(f => `- ${f.absolutePath} (role: ${f.role})`).join('\n') || '(none)'} + +## Reference Files (Read-Only) +${sessionAnalysis.referenceFiles.map(f => `- ${f.absolutePath} (role: ${f.role})`).join('\n') || '(none)'} + +## Last Action +${sessionAnalysis.lastAction} + +## Decisions +${sessionAnalysis.decisions.map(d => `- ${d.decision}: ${d.reasoning}`).join('\n') || '(none)'} + +## Constraints +${sessionAnalysis.constraints.map(c => `- ${c}`).join('\n') || '(none)'} + +## Dependencies +${sessionAnalysis.dependencies.map(d => `- ${d}`).join('\n') || '(none)'} + +## Known Issues +${sessionAnalysis.knownIssues.map(i => `- ${i}`).join('\n') || '(none)'} + +## Changes Made +${sessionAnalysis.changesMade.map(c => `- ${c}`).join('\n') || '(none)'} + +## Pending +${sessionAnalysis.pending.length > 0 + ? sessionAnalysis.pending.map(p => `- ${p}`).join('\n') + : '(none)'} + +## Notes +${sessionAnalysis.notes || '(none)'}`; +``` + +### Step 1.4: Import to Core Memory + +```javascript +mcp__ccw-tools__core_memory({ + operation: "import", + text: structuredText +}) +``` + +### Step 1.5: Report Recovery ID + +After successful import, display the Recovery ID: + +``` ++============================================================================+ +| Session Memory Saved | +| | +| Recovery ID: CMEM-YYYYMMDD-HHMMSS | +| | +| To restore: "Please import memory " | +| (MCP: core_memory export | CLI: ccw core-memory export --id ) | ++============================================================================+ +``` + +## Path Resolution Rules + +### Project Root Detection +1. Check current working directory from environment +2. Look for project markers: `.git/`, `package.json`, `.claude/` +3. Use the topmost directory containing these markers + +### Absolute Path Conversion +```javascript +const toAbsolutePath = (relativePath, projectRoot) => { + if (path.isAbsolute(relativePath)) return relativePath; + return path.join(projectRoot, relativePath); +}; +``` + +### Reference File Categories +| Category | Examples | Priority | +|----------|----------|----------| +| Project Config | `.claude/CLAUDE.md`, `package.json`, `tsconfig.json` | High | +| Type Definitions | `src/types/*.ts`, `*.d.ts` | High | +| Related Modules | Parent/sibling modules with shared interfaces | Medium | +| Test Files | Corresponding test files for modified code | Medium | +| Documentation | `README.md`, `ARCHITECTURE.md` | Low | + +## Quality Checklist + +Before generating: +- [ ] Session ID captured if workflow session active (WFS-*) +- [ ] Project Root is absolute path (e.g., D:\Claude_dms3) +- [ ] Objective clearly states the "North Star" goal +- [ ] Execution Plan: COMPLETE plan preserved VERBATIM (no summarization) +- [ ] Plan Source: Clearly identified (workflow | todo | user-stated | inferred) +- [ ] Plan Details: ALL phases, tasks, file paths, dependencies, status markers included +- [ ] All file paths are ABSOLUTE (not relative) +- [ ] Working Files: 3-8 modified files with roles +- [ ] Reference Files: Key context files (CLAUDE.md, types, configs) +- [ ] Last Action captures final state (success/failure) +- [ ] Decisions include reasoning, not just choices +- [ ] Known Issues separates deferred from forgotten bugs +- [ ] Notes preserve debugging hypotheses if any + +## Output + +- **Variable**: `structuredText` - the generated markdown string +- **MCP Result**: `{ operation: "import", id: "CMEM-YYYYMMDD-HHMMSS" }` +- **User Display**: Recovery ID banner with restore instructions + +## Next Phase + +N/A - Compact is a terminal phase. Return to SKILL.md orchestrator. diff --git a/.claude/skills/memory-capture/phases/02-tips.md b/.claude/skills/memory-capture/phases/02-tips.md new file mode 100644 index 00000000..c40c5d1d --- /dev/null +++ b/.claude/skills/memory-capture/phases/02-tips.md @@ -0,0 +1,206 @@ +# Phase 2: Tips - Quick Note Taking + +Quick note-taking for capturing ideas, snippets, reminders, and insights with optional tagging and context linking. + +## Objective + +- Provide minimal-friction note capture +- Support tagging for categorization and search +- Auto-detect context from current conversation +- Save to core_memory for persistent retrieval + +## Input + +- `noteContent` (Required): The tip/note content to save +- `tags` (Optional): Comma-separated tags for categorization +- `context` (Optional): Related context (file, module, feature) + +**Examples**: +```bash +"Use Zod for runtime validation - better DX than class-validator" +"Redis connection pool: max 10, min 2" --tag config,redis +"Fix needed: race condition in payment processor" --tag bug,payment --context src/payments +``` + +## Execution + +### Step 2.1: Parse Arguments + +```javascript +const parseTipsCommand = (input) => { + // Extract note content (everything before flags) + const contentMatch = input.match(/^"([^"]+)"|^([^\s-]+)/); + const content = contentMatch ? (contentMatch[1] || contentMatch[2]) : ''; + + // Extract tags + const tagsMatch = input.match(/--tag\s+([^\s-]+)/); + const tags = tagsMatch ? tagsMatch[1].split(',').map(t => t.trim()) : []; + + // Extract context + const contextMatch = input.match(/--context\s+([^\s-]+)/); + const context = contextMatch ? contextMatch[1] : ''; + + return { content, tags, context }; +}; +``` + +### Step 2.2: Gather Context + +```javascript +const gatherTipContext = async () => { + // Get project root + const projectRoot = process.cwd(); // or detect from environment + + // Get current session if active + const manifest = await mcp__ccw-tools__session_manager({ + operation: "list", + location: "active" + }); + const sessionId = manifest.sessions?.[0]?.id || null; + + // Auto-detect files from recent conversation + const recentFiles = extractRecentFilesFromConversation(); // Last 5 messages + + return { + projectRoot, + sessionId, + autoDetectedContext: recentFiles + }; +}; +``` + +### Step 2.3: Generate Structured Text + +```javascript +const generateTipText = (parsed, context) => { + const timestamp = new Date().toISOString().replace('T', ' ').slice(0, 19); + const tipId = `TIP-${new Date().toISOString().slice(0,10).replace(/-/g, '')}-${new Date().toTimeString().slice(0,8).replace(/:/g, '')}`; + + return `## Tip ID +${tipId} + +## Timestamp +${timestamp} + +## Project Root +${context.projectRoot} + +## Content +${parsed.content} + +## Tags +${parsed.tags.length > 0 ? parsed.tags.join(', ') : '(none)'} + +## Context +${parsed.context || '(none)'} + +## Session Link +${context.sessionId || '(none)'} + +## Auto-Detected Context +${context.autoDetectedContext.length > 0 + ? context.autoDetectedContext.map(f => `- ${f}`).join('\n') + : '(none)'}`; +}; +``` + +### Step 2.4: Save to Core Memory + +```javascript +mcp__ccw-tools__core_memory({ + operation: "import", + text: structuredText +}) +``` + +### Step 2.5: Confirm to User + +``` +Tip saved successfully + + ID: CMEM-YYYYMMDD-HHMMSS + Tags: architecture, auth + Context: src/auth/** + + To retrieve: core_memory(operation="search", query="") +``` + +## Tag Categories (Suggested) + +**Technical**: +- `architecture` - Design decisions and patterns +- `performance` - Optimization insights +- `security` - Security considerations +- `bug` - Bug notes and fixes +- `config` - Configuration settings +- `api` - API design patterns + +**Development**: +- `testing` - Test strategies and patterns +- `debugging` - Debugging techniques +- `refactoring` - Refactoring notes +- `documentation` - Doc improvements + +**Domain Specific**: +- `auth` - Authentication/authorization +- `database` - Database patterns +- `frontend` - UI/UX patterns +- `backend` - Backend logic +- `devops` - Infrastructure and deployment + +**Organizational**: +- `reminder` - Follow-up items +- `research` - Research findings +- `idea` - Feature ideas +- `review` - Code review notes + +## Search Integration + +Tips can be retrieved using: + +```javascript +// Via MCP tool +mcp__ccw-tools__core_memory({ + operation: "search", + query: "rate limiting", + source_type: "core_memory", + top_k: 10 +}) + +// Via CLI +// ccw core-memory search --query "rate limiting" --top-k 10 +``` + +## Quality Checklist + +Before saving: +- [ ] Content is clear and actionable +- [ ] Tags are relevant and consistent +- [ ] Context provides enough reference +- [ ] Auto-detected context is accurate +- [ ] Project root is absolute path +- [ ] Timestamp is properly formatted + +## Best Practices + +### Good Tips + +- **Specific and Actionable**: `"Use connection pooling for Redis: { max: 10, min: 2, acquireTimeoutMillis: 30000 }" --tag config,redis` +- **With Context**: `"Auth middleware must validate both access and refresh tokens" --tag security,auth --context src/middleware/auth.ts` +- **Problem + Solution**: `"Memory leak fixed by unsubscribing event listeners in componentWillUnmount" --tag bug,react --context src/components/Chat.tsx` + +### Poor Tips (Avoid) + +- Too Vague: `"Fix the bug" --tag bug` +- Too Long (use Compact instead): Multi-paragraph implementation plans +- No Context: `"Remember to update this later"` + +## Output + +- **Variable**: `structuredText` - the generated tip markdown string +- **MCP Result**: `{ operation: "import", id: "CMEM-YYYYMMDD-HHMMSS" }` +- **User Display**: Confirmation with ID, tags, and retrieval hint + +## Next Phase + +N/A - Tips is a terminal phase. Return to SKILL.md orchestrator.