compact
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMemory Compact Command (/memory:compact)
内存压缩命令 (/memory:compact)
1. Overview
1. 概述
The command compresses current session working memory into structured text optimized for session recovery, extracts critical information, and saves it to persistent storage via MCP tool.
memory:compactcore_memoryCore 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
memory:compactcore_memory核心理念:
- 会话恢复优先:捕获无缝恢复工作所需的所有信息
- 最小化重复探索:包含文件路径、决策和状态,避免冗余分析
- 保留思路轨迹:保存复杂调试过程中的笔记和假设
- 可执行状态:记录最后一次操作的结果和已知问题
2. Parameters
2. 参数
- : Custom session description (optional)
--description- Example: "completed core-memory module"
- Example: "debugging JWT refresh - suspected memory leak"
- : Comma-separated tags for categorization (optional)
--tags - : Skip confirmation, save directly
--force
- : 自定义会话描述(可选)
--description- 示例: "completed core-memory module"
- 示例: "debugging JWT refresh - suspected memory leak"
- : 用于分类的逗号分隔标签(可选)
--tags - : 跳过确认,直接保存
--force
3. Structured Output Format
3. 结构化输出格式
markdown
undefinedmarkdown
undefinedSession ID
Session ID
[WFS-ID if workflow session active, otherwise (none)]
[WFS-ID if workflow session active, otherwise (none)]
Project Root
Project Root
[Absolute path to project root, e.g., D:\Claude_dms3]
[Absolute path to project root, e.g., D:\Claude_dms3]
Objective
Objective
[High-level goal - the "North Star" of this session]
[High-level goal - the "North Star" of this session]
Execution Plan
Execution Plan
[CRITICAL: Embed the LATEST plan in its COMPLETE and DETAILED form]
[CRITICAL: Embed the LATEST plan in its COMPLETE and DETAILED form]
Source: [workflow | todo | user-stated | inferred]
Source: [workflow | todo | user-stated | inferred]
<details>
<summary>Full Execution Plan (Click to expand)</summary>
[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:
<details>
<summary>Full Execution Plan (Click to expand)</summary>
[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
Phase 1: Setup
- Initialize project structure
- Created D:\Claude_dms3\src\core\index.ts
- Added dependencies: lodash, zod
- Configure TypeScript
- Update tsconfig.json for strict mode
- 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
Phase 2: Implementation
- Implement core API
- Target: D:\Claude_dms3\src\api\handler.ts
- Dependencies: Phase 1 complete
- Acceptance: All tests pass
- Implement core API
- Target: D:\Claude_dms3\src\api\handler.ts
- Dependencies: Phase 1 complete
- Acceptance: All tests pass
Working Files (Modified)
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)
[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)
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)
[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 Action
[Last significant action and its result/status]
[Last significant action and its result/status]
Decisions
Decisions
Constraints
Constraints
- [User-specified limitation or preference]
- [User-specified limitation or preference]
Dependencies
Dependencies
- [Added/changed packages or environment requirements]
- [Added/changed packages or environment requirements]
Known Issues
Known Issues
- [Deferred bug or edge case]
- [Deferred bug or edge case]
Changes Made
Changes Made
- [Completed modification]
- [Completed modification]
Pending
Pending
- [Next step] or (none)
- [Next step] or (none)
Notes
Notes
[Unstructured thoughts, hypotheses, debugging trails]
undefined[Unstructured thoughts, hypotheses, debugging trails]
undefined4. Field Definitions
4. 字段定义
| 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" |
| 字段 | 用途 | 恢复价值 |
|---|---|---|
| Session ID | 工作流会话标识符(WFS-*) | 将内存与特定的有状态任务执行关联 |
| Project Root | 项目目录的绝对路径 | 支持在新会话中正确解析路径 |
| Objective | 会话的最终目标 | 避免偏离整体功能方向 |
| Execution Plan | 来自任意来源的完整计划(原文保留) | 保留完整的规划上下文,避免重新规划 |
| Working Files | 正在修改的文件(绝对路径) | 立即确定工作开展的位置 |
| Reference Files | 只读上下文文件(绝对路径) | 消除对关键上下文的重复探索 |
| Last Action | 最终工具输出/状态 | 即时了解状态(成功/失败) |
| Decisions | 架构选择及推理过程 | 避免重新讨论已确定的决策 |
| Constraints | 用户设定的限制条件 | 保持个性化的编码风格 |
| Dependencies | 包/环境变更 | 避免缺失依赖导致的错误 |
| Known Issues | 延后处理的Bug/边缘情况 | 确保问题不会被遗忘 |
| Changes Made | 已完成的修改 | 清晰记录已执行的操作 |
| Pending | 下一步计划 | 即时获取行动项 |
| Notes | 假设、调试轨迹 | 保留“思路轨迹” |
5. Execution Flow
5. 执行流程
Step 1: Analyze Current Session
步骤1:分析当前会话
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
}从对话历史中提取以下信息:
javascript
const sessionAnalysis = {
sessionId: "", // 若工作流会话激活则为WFS-*,否则为null
projectRoot: "", // 绝对路径: D:\Claude_dms3
objective: "", // 高层次目标(1-2句话)
executionPlan: {
source: "workflow" | "todo" | "user-stated" | "inferred",
content: "" // 完整计划内容 - 始终保留完整详细的形式
},
workingFiles: [], // {absolutePath, role} - 已修改文件
referenceFiles: [], // {absolutePath, role} - 只读上下文文件
lastAction: "", // 最后一次重要操作 + 结果
decisions: [], // {decision, reasoning}
constraints: [], // 用户指定的限制
dependencies: [], // 新增/变更的包
knownIssues: [], // 延后处理的Bug
changesMade: [], // 已完成的修改
pending: [], // 下一步计划
notes: "" // 非结构化想法
}Step 2: Generate Structured Text
步骤2:生成结构化文本
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}
<details>
<summary>Full Execution Plan (Click to expand)</summary>
${plan.content}
</details>`;
};
const structuredText = `## Session ID
${sessionAnalysis.sessionId || '(none)'}javascript
// 辅助函数:生成执行计划部分
const generateExecutionPlan = (plan) => {
const sourceLabels = {
'workflow': 'workflow (IMPL_PLAN.md)',
'todo': 'todo (TodoWrite)',
'user-stated': 'user-stated',
'inferred': 'inferred'
};
// 关键要求:完整保留计划内容原文 - 请勿总结
return `### Source: ${sourceLabels[plan.source] || plan.source}
<details>
<summary>Full Execution Plan (Click to expand)</summary>
${plan.content}
</details>`;
};
const structuredText = `## Session ID
${sessionAnalysis.sessionId || '(none)'}Project Root
Project Root
${sessionAnalysis.projectRoot}
${sessionAnalysis.projectRoot}
Objective
Objective
${sessionAnalysis.objective}
${sessionAnalysis.objective}
Execution Plan
Execution Plan
${generateExecutionPlan(sessionAnalysis.executionPlan)}
${generateExecutionPlan(sessionAnalysis.executionPlan)}
Working Files (Modified)
Working Files (Modified)
${sessionAnalysis.workingFiles.map(f => ).join('\n') || '(none)'}
- ${f.absolutePath} (role: ${f.role})${sessionAnalysis.workingFiles.map(f => ).join('\n') || '(none)'}
- ${f.absolutePath} (role: ${f.role})Reference Files (Read-Only)
Reference Files (Read-Only)
${sessionAnalysis.referenceFiles.map(f => ).join('\n') || '(none)'}
- ${f.absolutePath} (role: ${f.role})${sessionAnalysis.referenceFiles.map(f => ).join('\n') || '(none)'}
- ${f.absolutePath} (role: ${f.role})Last Action
Last Action
${sessionAnalysis.lastAction}
${sessionAnalysis.lastAction}
Decisions
Decisions
${sessionAnalysis.decisions.map(d => ).join('\n') || '(none)'}
- ${d.decision}: ${d.reasoning}${sessionAnalysis.decisions.map(d => ).join('\n') || '(none)'}
- ${d.decision}: ${d.reasoning}Constraints
Constraints
${sessionAnalysis.constraints.map(c => ).join('\n') || '(none)'}
- ${c}${sessionAnalysis.constraints.map(c => ).join('\n') || '(none)'}
- ${c}Dependencies
Dependencies
${sessionAnalysis.dependencies.map(d => ).join('\n') || '(none)'}
- ${d}${sessionAnalysis.dependencies.map(d => ).join('\n') || '(none)'}
- ${d}Known Issues
Known Issues
${sessionAnalysis.knownIssues.map(i => ).join('\n') || '(none)'}
- ${i}${sessionAnalysis.knownIssues.map(i => ).join('\n') || '(none)'}
- ${i}Changes Made
Changes Made
${sessionAnalysis.changesMade.map(c => ).join('\n') || '(none)'}
- ${c}${sessionAnalysis.changesMade.map(c => ).join('\n') || '(none)'}
- ${c}Pending
Pending
${sessionAnalysis.pending.length > 0
? sessionAnalysis.pending.map(p => ).join('\n')
: '(none)'}
- ${p}${sessionAnalysis.pending.length > 0
? sessionAnalysis.pending.map(p => ).join('\n')
: '(none)'}
- ${p}Notes
Notes
${sessionAnalysis.notes || '(none)'}`
undefined${sessionAnalysis.notes || '(none)'}`
undefinedStep 3: Import to Core Memory via MCP
步骤3:通过MCP导入到核心内存
Use the MCP tool to save the structured text:
core_memoryjavascript
mcp__ccw-tools__core_memory({
operation: "import",
text: structuredText
})Or via CLI (pipe structured text to import):
bash
undefined使用MCP 工具保存结构化文本:
core_memoryjavascript
mcp__ccw-tools__core_memory({
operation: "import",
text: structuredText
})或通过CLI(将结构化文本管道传输到导入命令):
bash
undefinedWrite structured text to temp file, then import
将结构化文本写入临时文件,然后导入
echo "$structuredText" | ccw core-memory 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"
}ccw core-memory import --file /path/to/session-memory.md
**响应格式**:
```json
{
"operation": "import",
"id": "CMEM-YYYYMMDD-HHMMSS",
"message": "Created memory: CMEM-YYYYMMDD-HHMMSS"
}Step 4: Report Recovery ID
步骤4:报告恢复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 <ID>" ║
║ (MCP: core_memory export | CLI: ccw core-memory export --id <ID>) ║
╚════════════════════════════════════════════════════════════════════════════╝成功导入后,向用户清晰显示恢复ID:
╔════════════════════════════════════════════════════════════════════════════╗
║ ✓ 会话内存已保存 ║
║ ║
║ 恢复ID: CMEM-YYYYMMDD-HHMMSS ║
║ ║
║ 恢复方式: "请导入内存 <ID>" ║
║ (MCP: core_memory export | CLI: ccw core-memory export --id <ID>) ║
╚════════════════════════════════════════════════════════════════════════════╝6. Quality Checklist
6. 质量检查清单
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
生成前需确认:
- 若工作流会话激活,已捕获Session ID(WFS-*)
- Project Root为绝对路径(例如:D:\Claude_dms3)
- Objective清晰表述了核心目标
- Execution Plan:完整保留计划原文(未总结)
- Plan Source:已明确标识(workflow | todo | user-stated | inferred)
- Plan Details:包含所有阶段、任务、文件路径、依赖项、状态标记
- 所有文件路径均为绝对路径(非相对路径)
- Working Files:包含3-8个带角色说明的已修改文件
- Reference Files:包含关键上下文文件(CLAUDE.md、类型文件、配置文件)
- Last Action捕获了最终状态(成功/失败)
- Decisions包含推理过程,而非仅选择结果
- Known Issues区分了延后处理和已遗忘的Bug
- Notes保留了调试假设(如有)
7. Path Resolution Rules
7. 路径解析规则
Project Root Detection
项目根目录检测
- Check current working directory from environment
- Look for project markers: ,
.git/,package.json.claude/ - Use the topmost directory containing these markers
- 从环境变量中检查当前工作目录
- 查找项目标记:、
.git/、package.json.claude/ - 使用包含这些标记的最顶层目录
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"javascript
// 将相对路径转换为绝对路径
const toAbsolutePath = (relativePath, projectRoot) => {
if (path.isAbsolute(relativePath)) return relativePath;
return path.join(projectRoot, relativePath);
};
// 示例: "src/api/auth.ts" → "D:\Claude_dms3\src\api\auth.ts"Reference File Categories
参考文件分类
| Category | Examples | Priority |
|---|---|---|
| Project Config | | High |
| Type Definitions | | High |
| Related Modules | Parent/sibling modules with shared interfaces | Medium |
| Test Files | Corresponding test files for modified code | Medium |
| Documentation | | Low |
| 分类 | 示例 | 优先级 |
|---|---|---|
| 项目配置 | | 高 |
| 类型定义 | | 高 |
| 关联模块 | 具有共享接口的父/兄弟模块 | 中 |
| 测试文件 | 对应修改代码的测试文件 | 中 |
| 文档 | | 低 |
8. Plan Detection (Priority Order)
8. 计划检测(优先级顺序)
Priority 1: Workflow Session (IMPL_PLAN.md)
优先级1:工作流会话(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;
}javascript
// 检查是否有激活的工作流会话
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)
优先级2:TodoWrite(当前会话待办事项)
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');
}javascript
// 从对话中提取 - 查找TodoWrite工具调用
// 保留完整待办事项列表及所有细节
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
优先级3:用户指定的计划
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;
}javascript
// 在用户消息中查找明确的计划表述:
// - "我的计划是:1. ... 2. ... 3. ..."
// - "我想要:首先...,然后...,最后..."
// - 描述步骤的编号或项目符号列表
const userPlan = extractUserStatedPlan();
if (userPlan) {
sessionAnalysis.executionPlan.source = "user-stated";
sessionAnalysis.executionPlan.content = userPlan;
}Priority 4: Inferred Plan
优先级4:推断的计划
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;
}javascript
// 若无明确计划,从以下内容推断:
// - 任务描述和分解讨论
// - 已执行的操作序列
// - 提及的未完成工作
const inferredPlan = inferPlanFromDiscussion();
if (inferredPlan) {
sessionAnalysis.executionPlan.source = "inferred";
sessionAnalysis.executionPlan.content = inferredPlan;
}9. Notes
9. 注意事项
- 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
- 时机:在任务完成时或上下文切换前执行
- 频率:每个独立任务或里程碑执行一次
- 恢复:新会话可立即借助完整上下文继续工作
- 知识图谱:自动提取实体关系用于可视化
- 绝对路径:对于在不同机器上跨会话恢复至关重要