├── .gitignore ├── CLAUDE.md ├── README.md ├── docs ├── API.md ├── QUICK-START.md ├── ROO-INTEGRATION.md ├── USAGE.md └── USER-GUIDE.md ├── memory-bank ├── README.md ├── archive │ └── .gitkeep ├── daily │ └── .gitkeep └── sessions │ └── .gitkeep ├── package-lock.json ├── package.json ├── scripts ├── generate-roo-rules.js ├── init-memory-bank.js ├── install-git-hooks.js ├── setup-roo-integration.js ├── test-memory-bank.js ├── umb.js ├── update-context.js └── update-memory-bank.js ├── src ├── enhanced-memory-bank.ts ├── index.ts ├── memory-bank.ts └── roo-integration.ts ├── templates └── roo-rules │ ├── 01-memory-bank-reference.md │ ├── 02-active-context.md │ └── 03-product-context.md └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Claude settings 2 | **/.claude/settings.local.json 3 | 4 | # Dependency directories 5 | node_modules/ 6 | jspm_packages/ 7 | 8 | # Build outputs 9 | dist/ 10 | build/ 11 | lib/ 12 | out/ 13 | *.js.map 14 | 15 | # TypeScript cache 16 | *.tsbuildinfo 17 | 18 | # Environment variables 19 | .env 20 | .env.local 21 | .env.development.local 22 | .env.test.local 23 | .env.production.local 24 | 25 | # Logs 26 | logs 27 | *.log 28 | npm-debug.log* 29 | yarn-debug.log* 30 | yarn-error.log* 31 | 32 | # Coverage directory 33 | coverage/ 34 | 35 | # IDE specific files 36 | .idea/ 37 | .vscode/* 38 | !.vscode/settings.json 39 | !.vscode/tasks.json 40 | !.vscode/launch.json 41 | !.vscode/extensions.json 42 | 43 | # Memory Bank content (exclude user-specific data) 44 | memory-bank/* 45 | memory-bank/**/*.md 46 | memory-bank/.last_update 47 | 48 | # But keep the skeleton structure 49 | !memory-bank/ 50 | !memory-bank/README.md 51 | !memory-bank/archive/ 52 | !memory-bank/archive/.gitkeep 53 | !memory-bank/daily/ 54 | !memory-bank/daily/.gitkeep 55 | !memory-bank/sessions/ 56 | !memory-bank/sessions/.gitkeep 57 | test-memory-bank-init.ts 58 | updated-init-test-area/ 59 | -------------------------------------------------------------------------------- /CLAUDE.md: -------------------------------------------------------------------------------- 1 | # CLAUDE.md 2 | 3 | This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. 4 | 5 | ## Build/Test Commands 6 | - Build: `npm run build` 7 | - Dev: `npm run dev` 8 | - Test: `npm run test` 9 | - Run single test: `npx jest path/to/test-file.test.ts` 10 | - Memory bank test: `npm run test-memory-bank` 11 | - CLI tool: `npm run umb` 12 | - Roo integration: `npm run roo-setup`, `npm run roo-sync` 13 | 14 | ## Code Style Guidelines 15 | - TypeScript with strict typing (`strict: true`) 16 | - Use ES2020 features and NodeNext module system 17 | - Use async/await for asynchronous operations 18 | - Comprehensive error handling with try/catch blocks 19 | - Document errors with format: 'Error :
' 20 | - Use descriptive interface names (e.g., `MemoryBankConfig`) 21 | - Class methods should have JSDoc comments 22 | - Use path.join() for cross-platform path construction 23 | - Imports: group by source (node modules first, then local) 24 | - Error handling: catch specific errors, log details 25 | - Documentation: maintain user guides in docs/ directory 26 | - Maintain backward compatibility where possible -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Roocode Memory Bank Optimized 2 | 3 | A powerful system for project context retention and documentation that helps developers maintain a persistent memory of their work, with Roo-Code integration. 4 | May work with other tools as well, or change it so it does 5 | 6 | ![Version](https://img.shields.io/badge/version-1.0.0-blue) 7 | ![License](https://img.shields.io/badge/license-MIT-green) 8 | 9 | ## Overview 10 | 11 | The Memory Bank system is designed to solve the problem of context loss during software development. It provides a structured way to document and track: 12 | 13 | - **Active Context**: What you're currently working on 14 | - **Product Context**: Project overview, goals, features 15 | - **System Patterns**: Architectural and design patterns 16 | - **Decision Logs**: Important decisions and their rationale 17 | - **Progress Tracking**: Current, completed, and upcoming tasks 18 | 19 | The system automatically tracks statistics like time spent, estimated cost, files modified, and lines of code changed. 20 | 21 | ## Features 22 | 23 | - **Daily Context Files**: Automatically creates and manages daily context files 24 | - **Session Tracking**: Tracks development sessions based on time gaps 25 | - **Statistics Tracking**: Monitors development metrics like time spent and code changes 26 | - **Git Integration**: Uses Git history to track file changes and reconstruct context 27 | - **Archiving**: Automatically archives old files to keep the system organized 28 | - **Command Line Interface**: Simple CLI for updating and managing the memory bank 29 | - **Roo-Code Integration**: Seamlessly integrates with Roo-Code AI assistant 30 | 31 | ## Quick Start 32 | 33 | ### Installation 34 | 35 | The Memory Bank system can be installed and used in several ways, depending on your needs: 36 | 37 | #### Option 1: Install in a separate directory (Recommended) 38 | 39 | This approach keeps the Memory Bank separate from your projects but still allows you to use it with any project. 40 | 41 | ```bash 42 | # Clone the repository in a dedicated directory 43 | git clone https://github.com/shipdocs/roocode-memorybank-optimized.git 44 | cd roocode-memorybank-optimized 45 | npm install 46 | npm run build 47 | npm link # Makes the tool available globally 48 | ``` 49 | 50 | Then, in any project where you want to use it: 51 | 52 | ```bash 53 | # Initialize the memory bank in your project 54 | cd /path/to/your/project 55 | npx umb init 56 | ``` 57 | 58 | #### Option 2: Download as a ZIP file 59 | 60 | ```bash 61 | # 1. Download the ZIP from GitHub: 62 | # https://github.com/shipdocs/roocode-memorybank-optimized/archive/refs/heads/main.zip 63 | # 2. Extract to a directory of your choice 64 | # 3. Navigate to the directory and run: 65 | cd path/to/extracted/directory 66 | npm install 67 | npm run build 68 | npm link # Makes the tool available globally 69 | ``` 70 | 71 | #### Option 3: Install directly in your project (Advanced) 72 | 73 | If you want to include the Memory Bank directly in your project: 74 | 75 | ```bash 76 | # 1. Navigate to your project root 77 | cd /path/to/your/project 78 | 79 | # 2. Clone the repository 80 | git clone https://github.com/shipdocs/roocode-memorybank-optimized.git 81 | 82 | # 3. Remove the .git directory to avoid git-in-git issues 83 | cd roocode-memorybank-optimized 84 | rm -rf .git 85 | 86 | # 4. Install and build 87 | npm install 88 | npm run build 89 | ``` 90 | 91 | > **Note:** This package is not currently registered on npm. The Memory Bank can be used with any project regardless of where it's installed, as it creates its own directory structure in the project where you run `npx umb init`. 92 | 93 | ### Initialize the Memory Bank 94 | 95 | ```bash 96 | # If installed globally or via npx 97 | npx umb init 98 | 99 | # If installed locally 100 | npm run umb init 101 | ``` 102 | 103 | ### Update the Memory Bank 104 | 105 | ```bash 106 | # Auto-update based on Git history 107 | npx umb 108 | 109 | # Update specific sections 110 | npx umb update activeContext currentFocus='Implementing new feature X' 111 | npx umb update productContext coreFeatures='- Feature A\n- Feature B' 112 | ``` 113 | 114 | ### Roo-Code Integration 115 | 116 | Set up and use the Roo-Code integration to provide project context to the AI assistant: 117 | 118 | ```bash 119 | # Set up Roo-Code integration 120 | npx umb roo-setup 121 | 122 | # After updating memory bank, sync with Roo-Code 123 | npx umb roo-sync 124 | ``` 125 | 126 | ### Install Git Hooks 127 | 128 | ```bash 129 | # Install Git hooks for automatic reminders 130 | npm run install-hooks 131 | ``` 132 | 133 | ## Detailed Usage 134 | 135 | ### Command Line Interface 136 | 137 | The `umb` command provides a simple interface to the memory bank: 138 | 139 | ```bash 140 | # Show help 141 | npx umb help 142 | 143 | # Initialize the memory bank 144 | npx umb init 145 | 146 | # Archive old files 147 | npx umb archive 148 | 149 | # Reconstruct from Git history (default: 30 days) 150 | npx umb reconstruct 60 151 | 152 | # Update active context 153 | npx umb update activeContext currentFocus='Implementing enhanced memory bank' 154 | 155 | # Add a decision 156 | npx umb add decision title='Switch to TypeScript' rationale='Better type safety' implications='Need to refactor existing code' status='Implemented' 157 | 158 | # Roo-Code integration commands 159 | npx umb roo-setup 160 | npx umb roo-sync 161 | ``` 162 | 163 | ### Programmatic Usage 164 | 165 | ```javascript 166 | import { MemoryBank, RooIntegration } from 'roocode-memorybank-optimized'; 167 | 168 | // Create a new memory bank instance 169 | const memoryBank = new MemoryBank('/path/to/memory-bank'); 170 | 171 | // Initialize the memory bank 172 | await memoryBank.initialize(); 173 | 174 | // Update active context 175 | await memoryBank.updateActiveContext({ 176 | currentFocus: 'Implementing new feature', 177 | recentChanges: 'Added unit tests', 178 | openQuestions: 'How to handle edge cases?' 179 | }); 180 | 181 | // Set up Roo-Code integration 182 | const rooIntegration = new RooIntegration({ 183 | memoryBankDir: '/path/to/memory-bank', 184 | workspaceDir: '/path/to/workspace' 185 | }); 186 | await rooIntegration.initialize(); 187 | await rooIntegration.syncMemoryBankToRoo(); 188 | ``` 189 | 190 | ## Directory Structure 191 | 192 | ``` 193 | memory-bank/ 194 | ├── .last_update # Timestamp of last update 195 | ├── activeContext.md # Master active context file 196 | ├── productContext.md # Product context file 197 | ├── systemPatterns.md # System patterns file 198 | ├── decisionLog.md # Decision log file 199 | ├── progress.md # Progress tracking file 200 | ├── daily/ # Daily context files 201 | │ ├── activeContext-YYYY-MM-DD.md 202 | │ └── ... 203 | ├── sessions/ # Session tracking files 204 | │ ├── session-YYYY-MM-DD-1.md 205 | │ └── ... 206 | └── archive/ # Archived files 207 | └── YYYY-MM/ # Organized by year-month 208 | ├── activeContext-YYYY-MM-DD.md 209 | └── ... 210 | ``` 211 | 212 | ## Configuration 213 | 214 | You can configure the memory bank by passing options to the `MemoryBank` constructor: 215 | 216 | ```javascript 217 | const memoryBank = new MemoryBank({ 218 | baseDir: '/path/to/memory-bank', 219 | dailyDirName: 'daily', 220 | sessionsDirName: 'sessions', 221 | archiveDirName: 'archive', 222 | sessionTimeoutHours: 2, 223 | archiveThresholdDays: 7, 224 | developerHourlyRate: 60 225 | }); 226 | ``` 227 | 228 | For Roo-Code integration, you can configure: 229 | 230 | ```javascript 231 | const rooIntegration = new RooIntegration({ 232 | memoryBankDir: '/path/to/memory-bank', 233 | rooRulesDir: '/path/to/.roo/rules', 234 | autoGenerateRules: true, 235 | workspaceDir: '/path/to/workspace' 236 | }); 237 | ``` 238 | 239 | ## Integration with Other Tools 240 | 241 | The memory bank system can be integrated with other tools: 242 | 243 | - **Git Hooks**: Automatically remind you to update the memory bank before commits 244 | - **CI/CD Pipelines**: Update the memory bank as part of your CI/CD process 245 | - **Project Management Tools**: Link memory bank updates to your project management workflow 246 | - **Roo-Code**: Integrate with Roo-Code to provide context to the AI assistant 247 | 248 | ### Roo-Code Integration 249 | 250 | The memory bank system integrates seamlessly with Roo-Code, an AI-powered autonomous coding agent. This integration allows Roo-Code to access your project context, decisions, and patterns. 251 | 252 | #### Smart Integration - Just Type "UMB" 253 | 254 | Using Memory Bank with Roo is as simple as typing: 255 | 256 | ``` 257 | UMB 258 | ``` 259 | 260 | The system will: 261 | - Automatically set up Memory Bank if it's not already installed 262 | - Guide you through context updates with simple questions 263 | - Suggest relevant context updates based on your current work 264 | 265 | No complex commands to remember - just type "UMB" and let Roo handle the rest. 266 | 267 | ```bash 268 | # Traditional setup (optional, handled automatically when you type "UMB") 269 | npx umb roo-setup 270 | npx umb roo-sync 271 | ``` 272 | 273 | This creates a frictionless workflow where Roo handles the complexity of maintaining your project context, allowing you to focus on coding. 274 | 275 | For detailed instructions, see [Roo-Code Integration](docs/ROO-INTEGRATION.md). 276 | 277 | ## Documentation 278 | 279 | - [Quick Start Guide](docs/QUICK-START.md) - Get started quickly 280 | - [User Guide](docs/USER-GUIDE.md) - Complete usage instructions 281 | - [API Reference](docs/API.md) - API documentation for developers 282 | - [Roo-Code Integration](docs/ROO-INTEGRATION.md) - Integration with Roo-Code 283 | 284 | ## Contributing 285 | 286 | Contributions are welcome! Please feel free to submit a Pull Request. 287 | 288 | 1. Fork the repository 289 | 2. Create your feature branch (`git checkout -b feature/amazing-feature`) 290 | 3. Commit your changes (`git commit -m 'Add some amazing feature'`) 291 | 4. Push to the branch (`git push origin feature/amazing-feature`) 292 | 5. Open a Pull Request 293 | 294 | ## License 295 | 296 | Distributed under the MIT License. See `LICENSE` for more information. 297 | -------------------------------------------------------------------------------- /docs/API.md: -------------------------------------------------------------------------------- 1 | # API Reference 2 | 3 | This document provides a comprehensive reference for developers who want to use the Roocode Memory Bank Optimized programmatically. It covers all the available classes, interfaces, methods, and their parameters. 4 | 5 | ## Table of Contents 6 | 7 | 1. [MemoryBank Class](#memorybank-class) 8 | 2. [EnhancedMemoryBank Class](#enhancedmemorybank-class) 9 | 3. [RooIntegration Class](#roointegration-class) 10 | 4. [Interfaces](#interfaces) 11 | 5. [Utility Functions](#utility-functions) 12 | 6. [Error Handling](#error-handling) 13 | 7. [Best Practices](#best-practices) 14 | 15 | ## MemoryBank Class 16 | 17 | The `MemoryBank` class is the primary interface for interacting with the memory bank system. 18 | 19 | ### Constructor 20 | 21 | ```typescript 22 | constructor(baseDir?: string) 23 | ``` 24 | 25 | Creates a new Memory Bank instance. 26 | 27 | **Parameters:** 28 | - `baseDir` (optional): Base directory for the memory bank (default: `process.cwd()/memory-bank`) 29 | 30 | **Example:** 31 | ```javascript 32 | import { MemoryBank } from 'roocode-memorybank-optimized'; 33 | 34 | // With default directory 35 | const memoryBank = new MemoryBank(); 36 | 37 | // With custom directory 38 | const customMemoryBank = new MemoryBank('/path/to/memory-bank'); 39 | ``` 40 | 41 | ### Methods 42 | 43 | #### initialize 44 | 45 | ```typescript 46 | public async initialize(): Promise 47 | ``` 48 | 49 | Initializes the memory bank by creating necessary directories and files. 50 | 51 | **Returns:** `Promise` - True if initialization was successful 52 | 53 | **Example:** 54 | ```javascript 55 | const success = await memoryBank.initialize(); 56 | if (success) { 57 | console.log('Memory bank initialized successfully'); 58 | } 59 | ``` 60 | 61 | #### updateProductContext 62 | 63 | ```typescript 64 | public async updateProductContext(update: { 65 | projectOverview?: string; 66 | goalsAndObjectives?: string; 67 | coreFeatures?: string; 68 | architectureOverview?: string; 69 | }): Promise 70 | ``` 71 | 72 | Updates the product context with the specified information. 73 | 74 | **Parameters:** 75 | - `update`: Object containing sections to update 76 | - `projectOverview` (optional): Project overview text 77 | - `goalsAndObjectives` (optional): Goals and objectives text 78 | - `coreFeatures` (optional): Core features text 79 | - `architectureOverview` (optional): Architecture overview text 80 | 81 | **Returns:** `Promise` - True if update was successful 82 | 83 | **Example:** 84 | ```javascript 85 | const success = await memoryBank.updateProductContext({ 86 | projectOverview: 'A web application for managing customer relationships', 87 | coreFeatures: '- User authentication\n- Contact management\n- Email integration' 88 | }); 89 | ``` 90 | 91 | #### updateActiveContext 92 | 93 | ```typescript 94 | public async updateActiveContext(update: { 95 | currentFocus?: string; 96 | recentChanges?: string; 97 | openQuestions?: string; 98 | }): Promise 99 | ``` 100 | 101 | Updates the active context with the specified information. 102 | 103 | **Parameters:** 104 | - `update`: Object containing sections to update 105 | - `currentFocus` (optional): Current focus text 106 | - `recentChanges` (optional): Recent changes text 107 | - `openQuestions` (optional): Open questions text 108 | 109 | **Returns:** `Promise` - True if update was successful 110 | 111 | **Example:** 112 | ```javascript 113 | const success = await memoryBank.updateActiveContext({ 114 | currentFocus: 'Implementing user authentication', 115 | recentChanges: 'Added login form validation', 116 | openQuestions: 'How should we handle password reset?' 117 | }); 118 | ``` 119 | 120 | #### handleUMBCommand 121 | 122 | ```typescript 123 | public async handleUMBCommand(updates: { 124 | productContext?: { /* ... */ }; 125 | activeContext?: { /* ... */ }; 126 | systemPatterns?: { /* ... */ }; 127 | decision?: { /* ... */ }; 128 | progress?: { /* ... */ }; 129 | }): Promise<{ success: boolean; message: string }> 130 | ``` 131 | 132 | Handles a UMB command by updating multiple parts of the memory bank. 133 | 134 | **Parameters:** 135 | - `updates`: Object containing updates for different parts of the memory bank 136 | - `productContext` (optional): Product context updates 137 | - `activeContext` (optional): Active context updates 138 | - `systemPatterns` (optional): System patterns updates 139 | - `decision` (optional): Decision to add 140 | - `progress` (optional): Progress updates 141 | 142 | **Returns:** `Promise<{ success: boolean; message: string }>` - Result object with success status and message 143 | 144 | **Example:** 145 | ```javascript 146 | const result = await memoryBank.handleUMBCommand({ 147 | activeContext: { 148 | currentFocus: 'Implementing authentication' 149 | }, 150 | decision: { 151 | title: 'Use JWT', 152 | rationale: 'Better for scalability', 153 | implications: 'Need to handle token refresh', 154 | status: 'Implemented' 155 | } 156 | }); 157 | 158 | console.log(result.message); 159 | ``` 160 | 161 | ## EnhancedMemoryBank Class 162 | 163 | The `EnhancedMemoryBank` class provides the core functionality for the memory bank system. 164 | 165 | ### Constructor 166 | 167 | ```typescript 168 | constructor(config: MemoryBankConfig) 169 | ``` 170 | 171 | Creates a new Enhanced Memory Bank instance. 172 | 173 | **Parameters:** 174 | - `config`: Configuration options for the memory bank 175 | 176 | **Example:** 177 | ```javascript 178 | import { EnhancedMemoryBank, MemoryBankConfig } from 'roocode-memorybank-optimized'; 179 | 180 | const config: MemoryBankConfig = { 181 | baseDir: '/path/to/memory-bank', 182 | dailyDirName: 'daily', 183 | sessionTimeoutHours: 3 184 | }; 185 | 186 | const enhancedMemoryBank = new EnhancedMemoryBank(config); 187 | ``` 188 | 189 | ### Methods 190 | 191 | #### initialize 192 | 193 | ```typescript 194 | public async initialize(): Promise 195 | ``` 196 | 197 | Initializes the enhanced memory bank by creating necessary directories. 198 | 199 | **Returns:** `Promise` - True if initialization was successful 200 | 201 | #### getDateString 202 | 203 | ```typescript 204 | public getDateString(date: Date = new Date()): string 205 | ``` 206 | 207 | Gets the current date in YYYY-MM-DD format. 208 | 209 | **Parameters:** 210 | - `date` (optional): Date to format (defaults to current date) 211 | 212 | **Returns:** `string` - Formatted date string 213 | 214 | #### getTimestamp 215 | 216 | ```typescript 217 | public getTimestamp(): string 218 | ``` 219 | 220 | Gets the current timestamp in a consistent format. 221 | 222 | **Returns:** `string` - Formatted timestamp string 223 | 224 | #### readFile 225 | 226 | ```typescript 227 | public async readFile(filePath: string): Promise 228 | ``` 229 | 230 | Reads a file and returns its content. 231 | 232 | **Parameters:** 233 | - `filePath`: Path to the file 234 | 235 | **Returns:** `Promise` - File content as string 236 | 237 | #### writeFile 238 | 239 | ```typescript 240 | public async writeFile(filePath: string, content: string): Promise 241 | ``` 242 | 243 | Writes content to a file. 244 | 245 | **Parameters:** 246 | - `filePath`: Path to the file 247 | - `content`: Content to write 248 | 249 | **Returns:** `Promise` - True if write was successful 250 | 251 | #### extractSection 252 | 253 | ```typescript 254 | public extractSection(content: string, sectionHeader: string): string 255 | ``` 256 | 257 | Extracts a section from markdown content. 258 | 259 | **Parameters:** 260 | - `content`: Markdown content 261 | - `sectionHeader`: Section header to extract 262 | 263 | **Returns:** `string` - Extracted section content 264 | 265 | #### updateSection 266 | 267 | ```typescript 268 | public updateSection(content: string, sectionHeader: string, newContent: string): string 269 | ``` 270 | 271 | Updates a section in markdown content. 272 | 273 | **Parameters:** 274 | - `content`: Markdown content 275 | - `sectionHeader`: Section header to update 276 | - `newContent`: New content for the section 277 | 278 | **Returns:** `string` - Updated markdown content 279 | 280 | #### Other Methods 281 | 282 | The `EnhancedMemoryBank` class provides additional methods for managing daily files, sessions, and statistics: 283 | 284 | - `createDailyFile(date: Date = new Date()): Promise` 285 | - `getLatestDailyFile(pattern: string): Promise` 286 | - `shouldStartNewSession(): Promise` 287 | - `createSessionFile(): Promise` 288 | - `getCurrentSessionFile(): Promise` 289 | - `updateSessionEndTime(sessionFile: string): Promise` 290 | - `archiveOldFiles(): Promise` 291 | - `loadContext(): Promise` 292 | - `trackStatistics(): Promise` 293 | - `updateDailyActiveContext(update: { /* ... */ }): Promise` 294 | - `aggregateDailyFiles(): Promise` 295 | - `reconstructMemoryBank(days: number = 30): Promise<{ success: boolean; message: string }>` 296 | 297 | ## RooIntegration Class 298 | 299 | The `RooIntegration` class provides integration between the Memory Bank system and Roo-Code. 300 | 301 | ### Constructor 302 | 303 | ```typescript 304 | constructor(config: RooIntegrationConfig = {}) 305 | ``` 306 | 307 | Creates a new Roo-Code integration instance. 308 | 309 | **Parameters:** 310 | - `config` (optional): Configuration options for the integration 311 | 312 | **Example:** 313 | ```javascript 314 | import { RooIntegration } from 'roocode-memorybank-optimized'; 315 | 316 | // With default configuration 317 | const rooIntegration = new RooIntegration(); 318 | 319 | // With custom configuration 320 | const customRooIntegration = new RooIntegration({ 321 | memoryBankDir: '/path/to/memory-bank', 322 | rooRulesDir: '/path/to/.roo/rules', 323 | autoGenerateRules: true, 324 | workspaceDir: '/path/to/workspace' 325 | }); 326 | ``` 327 | 328 | ### Methods 329 | 330 | #### initialize 331 | 332 | ```typescript 333 | public async initialize(): Promise 334 | ``` 335 | 336 | Initializes the Roo-Code integration. 337 | 338 | **Returns:** `Promise` - True if initialization was successful 339 | 340 | **Example:** 341 | ```javascript 342 | const success = await rooIntegration.initialize(); 343 | ``` 344 | 345 | #### generateRooRules 346 | 347 | ```typescript 348 | public async generateRooRules(): Promise 349 | ``` 350 | 351 | Generates Roo-Code custom instruction files from memory bank content. 352 | 353 | **Returns:** `Promise` - True if generation was successful 354 | 355 | **Example:** 356 | ```javascript 357 | const success = await rooIntegration.generateRooRules(); 358 | ``` 359 | 360 | #### updateRooRules 361 | 362 | ```typescript 363 | public async updateRooRules(): Promise 364 | ``` 365 | 366 | Updates Roo-Code rules with current memory bank content. 367 | 368 | **Returns:** `Promise` - True if update was successful 369 | 370 | **Example:** 371 | ```javascript 372 | const success = await rooIntegration.updateRooRules(); 373 | ``` 374 | 375 | #### syncMemoryBankToRoo 376 | 377 | ```typescript 378 | public async syncMemoryBankToRoo(): Promise 379 | ``` 380 | 381 | Syncs memory bank changes to Roo-Code rules. 382 | 383 | **Returns:** `Promise` - True if sync was successful 384 | 385 | **Example:** 386 | ```javascript 387 | const success = await rooIntegration.syncMemoryBankToRoo(); 388 | ``` 389 | 390 | #### getMemoryBank 391 | 392 | ```typescript 393 | public getMemoryBank(): MemoryBank 394 | ``` 395 | 396 | Gets the memory bank instance. 397 | 398 | **Returns:** `MemoryBank` - The memory bank instance 399 | 400 | **Example:** 401 | ```javascript 402 | const memoryBank = rooIntegration.getMemoryBank(); 403 | await memoryBank.updateActiveContext({ currentFocus: 'New focus' }); 404 | ``` 405 | 406 | #### autoConfigureForWorkspace (static) 407 | 408 | ```typescript 409 | public static async autoConfigureForWorkspace( 410 | workspacePath: string = process.cwd() 411 | ): Promise 412 | ``` 413 | 414 | Auto-detects and configures for a Roo-Code workspace. 415 | 416 | **Parameters:** 417 | - `workspacePath` (optional): Path to the workspace root (defaults to current directory) 418 | 419 | **Returns:** `Promise` - Configured integration instance or null if not a Roo-Code workspace 420 | 421 | **Example:** 422 | ```javascript 423 | const integration = await RooIntegration.autoConfigureForWorkspace('/path/to/workspace'); 424 | if (integration) { 425 | await integration.syncMemoryBankToRoo(); 426 | } 427 | ``` 428 | 429 | ## Interfaces 430 | 431 | ### MemoryBankConfig 432 | 433 | ```typescript 434 | interface MemoryBankConfig { 435 | /** Base directory for the memory bank */ 436 | baseDir: string; 437 | /** Directory name for daily files */ 438 | dailyDirName?: string; 439 | /** Directory name for session files */ 440 | sessionsDirName?: string; 441 | /** Directory name for archived files */ 442 | archiveDirName?: string; 443 | /** Session timeout in hours */ 444 | sessionTimeoutHours?: number; 445 | /** Archive threshold in days */ 446 | archiveThresholdDays?: number; 447 | /** Developer hourly rate for cost estimation */ 448 | developerHourlyRate?: number; 449 | } 450 | ``` 451 | 452 | ### RooIntegrationConfig 453 | 454 | ```typescript 455 | interface RooIntegrationConfig { 456 | /** Base directory for the memory bank (defaults to ./memory-bank) */ 457 | memoryBankDir?: string; 458 | /** Directory where Roo rules will be stored (defaults to .roo/rules) */ 459 | rooRulesDir?: string; 460 | /** Automatically generate Roo rules from memory bank content */ 461 | autoGenerateRules?: boolean; 462 | /** Workspace root directory */ 463 | workspaceDir?: string; 464 | } 465 | ``` 466 | 467 | ### Statistics 468 | 469 | ```typescript 470 | interface Statistics { 471 | timeSpent: string; 472 | estimatedCost: number; 473 | filesCreated: number; 474 | filesModified: number; 475 | filesDeleted: number; 476 | linesAdded: number; 477 | linesRemoved: number; 478 | totalLines: number; 479 | } 480 | ``` 481 | 482 | ## Utility Functions 483 | 484 | The following utility functions are re-exported from the memory bank for convenience: 485 | 486 | ```typescript 487 | import { 488 | getDateString, 489 | getTimestamp, 490 | createDailyFile, 491 | getLatestDailyFile, 492 | shouldStartNewSession, 493 | createSessionFile, 494 | getCurrentSessionFile, 495 | updateSessionEndTime, 496 | archiveOldFiles, 497 | loadContext, 498 | trackStatistics, 499 | updateDailyActiveContext, 500 | aggregateDailyFiles, 501 | reconstructMemoryBank 502 | } from 'vibecoding-memory-bank'; 503 | ``` 504 | 505 | These functions provide direct access to specific functionality without needing to create a memory bank instance. 506 | 507 | ## Error Handling 508 | 509 | The Memory Bank system uses try-catch blocks for error handling and returns boolean values to indicate success or failure for most operations. 510 | 511 | ```javascript 512 | try { 513 | const success = await memoryBank.updateActiveContext({ 514 | currentFocus: 'Implementing new feature' 515 | }); 516 | 517 | if (!success) { 518 | console.error('Failed to update active context'); 519 | } 520 | } catch (error) { 521 | console.error('Error updating active context:', error); 522 | } 523 | ``` 524 | 525 | For more complex operations, a result object with success status and message is returned: 526 | 527 | ```javascript 528 | const result = await memoryBank.handleUMBCommand({ 529 | activeContext: { 530 | currentFocus: 'Implementing new feature' 531 | } 532 | }); 533 | 534 | if (!result.success) { 535 | console.error(result.message); 536 | } 537 | ``` 538 | 539 | ## Best Practices 540 | 541 | ### Initialization 542 | 543 | Always initialize the memory bank before using it: 544 | 545 | ```javascript 546 | const memoryBank = new MemoryBank('/path/to/memory-bank'); 547 | await memoryBank.initialize(); 548 | ``` 549 | 550 | ### Update Operations 551 | 552 | For better performance, batch updates when possible: 553 | 554 | ```javascript 555 | // Good: Batch updates 556 | await memoryBank.handleUMBCommand({ 557 | activeContext: { 558 | currentFocus: 'New feature', 559 | openQuestions: 'How to handle edge cases?' 560 | }, 561 | productContext: { 562 | coreFeatures: 'Updated feature list' 563 | } 564 | }); 565 | 566 | // Less efficient: Separate updates 567 | await memoryBank.updateActiveContext({ currentFocus: 'New feature' }); 568 | await memoryBank.updateActiveContext({ openQuestions: 'How to handle edge cases?' }); 569 | await memoryBank.updateProductContext({ coreFeatures: 'Updated feature list' }); 570 | ``` 571 | 572 | ### Error Handling 573 | 574 | Always check the result of operations: 575 | 576 | ```javascript 577 | const success = await memoryBank.updateActiveContext({ 578 | currentFocus: 'New feature' 579 | }); 580 | 581 | if (!success) { 582 | // Handle failure 583 | } 584 | ``` 585 | 586 | ### Path Handling 587 | 588 | Use `path.join()` for cross-platform path construction: 589 | 590 | ```javascript 591 | import path from 'path'; 592 | 593 | const filePath = path.join(baseDir, 'activeContext.md'); 594 | ``` 595 | 596 | ### Roo-Code Integration 597 | 598 | When integrating with Roo-Code, update rules after significant changes: 599 | 600 | ```javascript 601 | // Update memory bank 602 | await memoryBank.updateActiveContext({ currentFocus: 'New focus' }); 603 | 604 | // Sync changes to Roo-Code 605 | await rooIntegration.syncMemoryBankToRoo(); 606 | ``` -------------------------------------------------------------------------------- /docs/QUICK-START.md: -------------------------------------------------------------------------------- 1 | # Quick Start Guide 2 | 3 | This guide will help you quickly set up and start using the Roocode Memory Bank Optimized, including the Roo-Code integration. 4 | 5 | ## Installation 6 | 7 | The Memory Bank system can be installed and used in several ways: 8 | 9 | ### Option 1: Install in a separate directory (Recommended) 10 | 11 | This approach keeps the Memory Bank separate from your projects but still allows you to use it with any project. 12 | 13 | ```bash 14 | # Clone the repository in a dedicated directory 15 | git clone https://github.com/shipdocs/roocode-memorybank-optimized.git 16 | cd roocode-memorybank-optimized 17 | npm install 18 | npm run build 19 | npm link # Makes the tool available globally 20 | ``` 21 | 22 | Then, in any project where you want to use it: 23 | 24 | ```bash 25 | # Initialize the memory bank in your project 26 | cd /path/to/your/project 27 | npx umb init 28 | ``` 29 | 30 | ### Option 2: Download as a ZIP file 31 | 32 | 1. Download the ZIP from GitHub: https://github.com/shipdocs/roocode-memorybank-optimized/archive/refs/heads/main.zip 33 | 2. Extract to a directory of your choice 34 | 3. Navigate to the directory and run: 35 | ```bash 36 | cd path/to/extracted/directory 37 | npm install 38 | npm run build 39 | npm link # Makes the tool available globally 40 | ``` 41 | 42 | ### Option 3: Install directly in your project (Advanced) 43 | 44 | If you want to include the Memory Bank directly in your project: 45 | 46 | ```bash 47 | # 1. Navigate to your project root 48 | cd /path/to/your/project 49 | 50 | # 2. Clone the repository 51 | git clone https://github.com/shipdocs/roocode-memorybank-optimized.git 52 | 53 | # 3. Remove the .git directory to avoid git-in-git issues 54 | cd roocode-memorybank-optimized 55 | rm -rf .git 56 | 57 | # 4. Install and build 58 | npm install 59 | npm run build 60 | ``` 61 | 62 | > **Note:** The Memory Bank can be used with any project regardless of where it's installed, as it creates its own directory structure in the project where you run `npx umb init`. 63 | 64 | ## Basic Setup 65 | 66 | ### Initialize the Memory Bank 67 | 68 | First, initialize the memory bank to create the necessary directory structure: 69 | 70 | ```bash 71 | npx umb init 72 | ``` 73 | 74 | This creates a `memory-bank` directory in your current workspace with the following structure: 75 | 76 | ``` 77 | memory-bank/ 78 | ├── activeContext.md 79 | ├── productContext.md 80 | ├── systemPatterns.md 81 | ├── decisionLog.md 82 | ├── progress.md 83 | ├── daily/ 84 | ├── sessions/ 85 | └── archive/ 86 | ``` 87 | 88 | ## Daily Usage 89 | 90 | ### Record Your Current Focus 91 | 92 | When starting work on a new task or feature, update your active context: 93 | 94 | ```bash 95 | npx umb update activeContext currentFocus='Implementing feature X' 96 | ``` 97 | 98 | ### Document Open Questions 99 | 100 | Keep track of questions that arise during development: 101 | 102 | ```bash 103 | npx umb update activeContext openQuestions='How should we handle error states?' 104 | ``` 105 | 106 | ### Record Important Decisions 107 | 108 | When you make a significant decision, add it to the decision log: 109 | 110 | ```bash 111 | npx umb add decision title='Use React hooks' rationale='Better component composition' implications='Need to refactor class components' status='Implemented' 112 | ``` 113 | 114 | ### Auto-Update Based on Git 115 | 116 | To automatically update the memory bank based on Git history: 117 | 118 | ```bash 119 | npx umb 120 | ``` 121 | 122 | This analyzes your Git history to track changes, time spent, and files modified. 123 | 124 | ## Roo-Code Integration 125 | 126 | ### Setup Roo-Code Integration 127 | 128 | To integrate with Roo-Code: 129 | 130 | ```bash 131 | npx umb roo-setup 132 | ``` 133 | 134 | This sets up the necessary files and directories for Roo-Code to access your memory bank. 135 | 136 | ### Update Roo-Code Rules 137 | 138 | After updating your memory bank, sync the changes to Roo-Code: 139 | 140 | ```bash 141 | npx umb roo-sync 142 | ``` 143 | 144 | ## Examples 145 | 146 | ### Complete Workflow Example 147 | 148 | ```bash 149 | # Initialize memory bank 150 | npx umb init 151 | 152 | # Start working on a new feature 153 | npx umb update activeContext currentFocus='Adding authentication system' 154 | npx umb update activeContext openQuestions='What authentication provider should we use?' 155 | 156 | # Make a decision 157 | npx umb add decision title='Use JWT for authentication' rationale='Better scalability' implications='Need to handle token refresh' status='Implemented' 158 | 159 | # Update product context 160 | npx umb update productContext coreFeatures='- User authentication\n- Role-based access control\n- Password reset' 161 | 162 | # Set up Roo-Code integration 163 | npx umb roo-setup 164 | 165 | # After making changes, sync with Roo-Code 166 | npx umb roo-sync 167 | ``` 168 | 169 | ## Next Steps 170 | 171 | - Read the full [User Guide](USER-GUIDE.md) for complete usage instructions 172 | - Check out the [Roo-Code Integration](ROO-INTEGRATION.md) documentation for advanced integration options 173 | - Explore the [API Reference](API.md) if you want to use the memory bank programmatically -------------------------------------------------------------------------------- /docs/ROO-INTEGRATION.md: -------------------------------------------------------------------------------- 1 | # Roo-Code Integration 2 | 3 | This document provides detailed information about integrating the Memory Bank system with Roo-Code, an AI-powered autonomous coding agent. 4 | 5 | ## Table of Contents 6 | 7 | 1. [Overview](#overview) 8 | 2. [Quick Start](#quick-start) 9 | 3. [Detailed Setup](#detailed-setup) 10 | 4. [How It Works](#how-it-works) 11 | 5. [Integration with Existing Roo-Code Configuration](#integration-with-existing-roo-code-configuration) 12 | 6. [Advanced Usage](#advanced-usage) 13 | 7. [Automated Integration](#automated-integration) 14 | 8. [Example Scenarios](#example-scenarios) 15 | 9. [Troubleshooting](#troubleshooting) 16 | 10. [Best Practices](#best-practices) 17 | 18 | ## Overview 19 | 20 | The Memory Bank system provides structured documentation and context retention for your projects. Integrating it with Roo-Code allows the AI agent to access this context, improving its understanding of your codebase and project goals. 21 | 22 | The integration works by generating custom instruction files for Roo-Code that reference the content stored in your memory bank. These instructions are stored in the `.roo/rules` directory, which Roo-Code automatically reads when providing assistance. 23 | 24 | ## Quick Start 25 | 26 | To quickly set up the integration: 27 | 28 | ```bash 29 | # Initialize the memory bank if you haven't already 30 | npx umb init 31 | 32 | # Set up Roo-Code integration 33 | npx umb roo-setup 34 | 35 | # Update your memory bank with project context 36 | npx umb update activeContext currentFocus='Current development focus' 37 | npx umb update productContext projectOverview='Project overview and goals' 38 | 39 | # Sync memory bank changes to Roo-Code 40 | npx umb roo-sync 41 | ``` 42 | 43 | ## Detailed Setup 44 | 45 | ### 1. Install and Initialize 46 | 47 | First, install the Memory Bank system following one of the methods in the [README.md](../README.md): 48 | 49 | ```bash 50 | # Option 1: Install in a separate directory (Recommended) 51 | git clone https://github.com/shipdocs/roocode-memorybank-optimized.git 52 | cd roocode-memorybank-optimized 53 | npm install 54 | npm run build 55 | npm link # Makes the tool available globally 56 | 57 | # Then, in your project directory 58 | cd /path/to/your/project 59 | npx umb init 60 | ``` 61 | 62 | > **Note:** The Memory Bank can be used with any project regardless of where it's installed, as it creates its own directory structure in the project where you run `npx umb init`. See the [README.md](../README.md) for all installation options. 63 | 64 | ### 2. Set Up Roo-Code Integration 65 | 66 | Set up the integration with Roo-Code: 67 | 68 | ```bash 69 | npx umb roo-setup 70 | ``` 71 | 72 | This command: 73 | - Detects if Roo-Code is configured in your workspace 74 | - Creates a `.roo/rules` directory if needed 75 | - Generates initial custom instruction files based on memory bank contents 76 | 77 | ### 3. Update Your Memory Bank 78 | 79 | Populate your memory bank with relevant context: 80 | 81 | ```bash 82 | # Update active context 83 | npx umb update activeContext currentFocus='Implementing feature X' 84 | npx umb update activeContext openQuestions='How should we handle edge case Y?' 85 | 86 | # Update product context 87 | npx umb update productContext projectOverview='A system for managing...' 88 | npx umb update productContext coreFeatures='- Feature A\n- Feature B' 89 | 90 | # Add important decisions 91 | npx umb add decision title='Use TypeScript' rationale='Type safety' implications='Learning curve' status='Implemented' 92 | ``` 93 | 94 | ### 4. Sync to Roo-Code 95 | 96 | After updating your memory bank, sync the changes to Roo-Code: 97 | 98 | ```bash 99 | npx umb roo-sync 100 | ``` 101 | 102 | This generates updated custom instruction files in the `.roo/rules` directory based on your memory bank content. 103 | 104 | ## How It Works 105 | 106 | The integration: 107 | 108 | 1. **Creates Custom Instructions**: Generates Markdown files in `.roo/rules` that Roo-Code reads to understand project context 109 | 2. **Maintains References**: Keeps references to memory bank files so Roo-Code knows where context is stored 110 | 3. **Auto-updates**: Can automatically update Roo-Code rules when memory bank content changes 111 | 112 | The generated files include: 113 | - `01-memory-bank-reference.md`: General reference to the memory bank 114 | - `02-active-context.md`: Current development focus and open questions 115 | - `03-product-context.md`: Project overview, goals, and features 116 | 117 | ### Generated Files Example 118 | 119 | Here's what the generated files typically contain: 120 | 121 | #### 01-memory-bank-reference.md 122 | 123 | ```markdown 124 | # Memory Bank Reference 125 | 126 | This file provides Roo with context from the memory bank located at: 127 | `/path/to/memory-bank` 128 | 129 | ## Active Context 130 | The active context is the current focus of development and recent changes. 131 | Refer to this when working on the codebase to understand the current state. 132 | 133 | ## Product Context 134 | The product context provides an overview of the project, its goals, features, 135 | and architecture. Use this information to ensure your responses align with 136 | the project vision. 137 | 138 | ## System Patterns 139 | System patterns describe the architectural and design patterns used in the project. 140 | Follow these patterns when suggesting code changes. 141 | 142 | ## Decision Log 143 | The decision log contains important decisions and their rationale. 144 | Respect these decisions when making suggestions. 145 | ``` 146 | 147 | #### 02-active-context.md 148 | 149 | ```markdown 150 | # Active Development Context 151 | 152 | ## Current Focus 153 | - Implementing memory bank integration with Roo-Code 154 | - Creating a seamless experience for Roo users 155 | 156 | ## Recent Changes 157 | - Added Roo-Code integration module 158 | - Created templates for Roo rules 159 | - Implemented auto-configuration for workspaces 160 | 161 | ## Open Questions/Issues 162 | - What is the best way to keep Roo rules updated when memory bank changes? 163 | - How can we provide a smooth setup experience for new users? 164 | 165 | --- 166 | This file is automatically generated from the memory bank. Do not edit directly. 167 | Last updated: 2023-05-05T12:34:56Z 168 | ``` 169 | 170 | #### 03-product-context.md 171 | 172 | ```markdown 173 | # Product Context 174 | 175 | ## Project Overview 176 | The Memory Bank system is designed to solve the problem of context loss during 177 | software development. It provides a structured way to document and track 178 | active context, product information, system patterns, and decisions. 179 | 180 | ## Goals and Objectives 181 | - Maintain persistent memory of development work 182 | - Provide structured documentation for projects 183 | - Track statistics like time spent and code changes 184 | - Integrate with development tools like Roo-Code 185 | 186 | ## Core Features 187 | - Daily context files for tracking current work 188 | - Session tracking based on time gaps 189 | - Statistics tracking for development metrics 190 | - Git integration for tracking changes 191 | - Roo-Code integration for AI assistance 192 | 193 | ## Architecture Overview 194 | - TypeScript-based implementation 195 | - File-based storage using Markdown 196 | - Hierarchical organization (daily files, sessions, archives) 197 | 198 | --- 199 | This file is automatically generated from the memory bank. Do not edit directly. 200 | Last updated: 2023-05-05T12:34:56Z 201 | ``` 202 | 203 | ## Integration with Existing Roo-Code Configuration 204 | 205 | If you already have custom rules in `.roomodes` or `.roo/rules`, this integration will not interfere with them. The memory bank rules are added alongside your existing rules, following Roo-Code's instruction combination order: 206 | 207 | 1. Language preferences 208 | 2. Global instructions 209 | 3. Mode-specific instructions 210 | 4. Mode-specific file instructions 211 | 5. Workspace-wide file instructions 212 | 213 | Your existing custom rules will still be applied according to this hierarchy. 214 | 215 | ### Example: Combining with Existing Rules 216 | 217 | If you have an existing rule file like `.roo/rules/coding-standards.md`: 218 | 219 | ```markdown 220 | # Coding Standards 221 | 222 | - Use 2-space indentation 223 | - Prefer arrow functions 224 | - Use TypeScript for all new code 225 | ``` 226 | 227 | It will work alongside the memory bank rules: 228 | 229 | ``` 230 | .roo/rules/ 231 | ├── 01-memory-bank-reference.md # From memory bank 232 | ├── 02-active-context.md # From memory bank 233 | ├── 03-product-context.md # From memory bank 234 | └── coding-standards.md # Your existing rule 235 | ``` 236 | 237 | Roo-Code will consider both your coding standards and the project context from the memory bank. 238 | 239 | ## Advanced Usage 240 | 241 | ### Programmatic Integration 242 | 243 | You can use the Roo-Code integration programmatically: 244 | 245 | ```javascript 246 | import { RooIntegration } from 'roocode-memorybank-optimized'; 247 | 248 | // Auto-configure for the current workspace 249 | const integration = await RooIntegration.autoConfigureForWorkspace(); 250 | 251 | // Or with custom configuration 252 | const customIntegration = new RooIntegration({ 253 | memoryBankDir: '/path/to/memory-bank', 254 | rooRulesDir: '/path/to/.roo/rules', 255 | autoGenerateRules: true, 256 | workspaceDir: '/path/to/workspace' 257 | }); 258 | 259 | await customIntegration.initialize(); 260 | await customIntegration.syncMemoryBankToRoo(); 261 | ``` 262 | 263 | ### Custom Rule Generation 264 | 265 | You can customize how rules are generated by extending the `RooIntegration` class: 266 | 267 | ```javascript 268 | import { RooIntegration } from 'roocode-memorybank-optimized'; 269 | import fs from 'fs-extra'; 270 | import path from 'path'; 271 | 272 | class CustomRooIntegration extends RooIntegration { 273 | async generateRooRules() { 274 | // Call the parent implementation 275 | await super.generateRooRules(); 276 | 277 | // Add your custom rule 278 | const customRule = `# Custom Development Guidelines 279 | 280 | Based on our memory bank context, follow these additional guidelines: 281 | - Focus on the current task: ${await this.getCurrentFocus()} 282 | - Follow our established patterns 283 | - Consider our recent decisions 284 | 285 | --- 286 | Custom rule generated: ${new Date().toISOString()} 287 | `; 288 | 289 | await fs.writeFile( 290 | path.join(this.config.rooRulesDir, '04-custom-guidelines.md'), 291 | customRule 292 | ); 293 | 294 | return true; 295 | } 296 | 297 | async getCurrentFocus() { 298 | // Get memory bank instance 299 | const memoryBank = this.getMemoryBank(); 300 | const activeContextPath = path.join(memoryBank.baseDir, 'activeContext.md'); 301 | 302 | if (await fs.pathExists(activeContextPath)) { 303 | const content = await fs.readFile(activeContextPath, 'utf8'); 304 | const focusRegex = /## Current Focus\n([^#]*)/; 305 | const match = content.match(focusRegex); 306 | return match ? match[1].trim() : 'No current focus specified'; 307 | } 308 | 309 | return 'No active context found'; 310 | } 311 | } 312 | 313 | // Use your custom integration 314 | const customIntegration = new CustomRooIntegration(); 315 | await customIntegration.initialize(); 316 | ``` 317 | 318 | ## Automated Integration 319 | 320 | For a fully automated workflow, consider: 321 | 322 | ### 1. Post-commit Hook 323 | 324 | Create a Git post-commit hook to update Roo-Code rules: 325 | 326 | ```bash 327 | #!/bin/sh 328 | # .git/hooks/post-commit 329 | 330 | # Update the memory bank 331 | npx umb 332 | 333 | # Sync to Roo-Code 334 | npx umb roo-sync 335 | ``` 336 | 337 | Make it executable: 338 | ```bash 339 | chmod +x .git/hooks/post-commit 340 | ``` 341 | 342 | ### 2. Scheduled Updates 343 | 344 | Use cron jobs to periodically sync content: 345 | 346 | ```bash 347 | # Example crontab entry - sync every hour 348 | 0 * * * * cd /path/to/project && npx umb roo-sync 349 | ``` 350 | 351 | ### 3. Editor Integration 352 | 353 | Create editor plugins that trigger sync on save. For example, with VS Code: 354 | 355 | ```json 356 | // .vscode/settings.json 357 | { 358 | "emeraldwalk.runonsave": { 359 | "commands": [ 360 | { 361 | "match": ".*\\.(js|ts|jsx|tsx)$", 362 | "cmd": "npx umb roo-sync" 363 | } 364 | ] 365 | } 366 | } 367 | ``` 368 | 369 | ## Example Scenarios 370 | 371 | ### Scenario 1: New Project Setup 372 | 373 | ```bash 374 | # Initialize a new project 375 | mkdir my-project 376 | cd my-project 377 | npm init -y 378 | git init 379 | 380 | # Install memory bank 381 | npm install roocode-memorybank-optimized 382 | 383 | # Initialize memory bank 384 | npx umb init 385 | 386 | # Set up core project context 387 | npx umb update productContext projectOverview='A web application for tracking fitness goals' 388 | npx umb update productContext goalsAndObjectives='- Help users track workouts\n- Provide progress visualization\n- Support goal setting' 389 | npx umb update productContext coreFeatures='- User authentication\n- Workout logging\n- Progress charts\n- Goal setting' 390 | 391 | # Document initial architectural decisions 392 | npx umb add decision title='Use React' rationale='Team expertise and component reusability' implications='Need to set up React environment' status='Implemented' 393 | npx umb add decision title='Express backend' rationale='Simplicity and scalability' implications='Need to design REST API' status='Implemented' 394 | 395 | # Set up initial active context 396 | npx umb update activeContext currentFocus='Setting up project structure and dev environment' 397 | 398 | # Set up Roo-Code integration 399 | npx umb roo-setup 400 | ``` 401 | 402 | ### Scenario 2: Daily Development Workflow 403 | 404 | ```bash 405 | # Start of day - update active context 406 | npx umb update activeContext currentFocus='Implementing user authentication' 407 | npx umb update activeContext openQuestions='Should we use JWT or session-based auth?' 408 | 409 | # Make a decision after research 410 | npx umb add decision title='Use JWT for authentication' rationale='Better for scalability and mobile clients' implications='Need to handle token refresh' status='Implemented' 411 | 412 | # Update active context after implementing 413 | npx umb update activeContext currentFocus='Adding token refresh logic to auth system' 414 | npx umb update activeContext recentChanges='Implemented JWT authentication' 415 | 416 | # End of day - sync to Roo-Code 417 | npx umb roo-sync 418 | ``` 419 | 420 | ### Scenario 3: Team Onboarding 421 | 422 | ```bash 423 | # Clone project repository 424 | git clone https://github.com/example/project.git 425 | cd project 426 | 427 | # Install dependencies 428 | npm install 429 | 430 | # Explore memory bank content 431 | cat memory-bank/productContext.md 432 | cat memory-bank/activeContext.md 433 | cat memory-bank/decisionLog.md 434 | 435 | # Set up personal Roo-Code integration 436 | npx umb roo-setup 437 | 438 | # Start contributing with context 439 | npx umb update activeContext currentFocus='Learning codebase and fixing initial bugs' 440 | ``` 441 | 442 | ## Troubleshooting 443 | 444 | ### Common Issues 445 | 446 | #### Roo-Code Not Detecting Rules 447 | 448 | ``` 449 | Roo-Code doesn't seem to be using the memory bank context 450 | ``` 451 | 452 | Solutions: 453 | 1. Verify rules are in the correct `.roo/rules` directory 454 | 2. Check if the rules files have the correct format 455 | 3. Restart Roo-Code to reload the rules 456 | 457 | #### Rules Not Updating 458 | 459 | ``` 460 | Rules files aren't updating when memory bank changes 461 | ``` 462 | 463 | Solutions: 464 | 1. Make sure you run `npx umb roo-sync` after updating the memory bank 465 | 2. Check for file permission issues 466 | 3. Verify the Roo integration is properly configured 467 | 468 | #### Integration Setup Failing 469 | 470 | ``` 471 | Failed to set up Roo-Code integration 472 | ``` 473 | 474 | Solutions: 475 | 1. Check if Roo-Code is installed 476 | 2. Verify you have write permissions for the `.roo/rules` directory 477 | 3. Run with verbose logging: `DEBUG=* npx umb roo-setup` 478 | 479 | ### Checking Configuration 480 | 481 | To verify your setup: 482 | 483 | ```bash 484 | # Check if .roo/rules directory exists 485 | ls -la .roo/rules 486 | 487 | # Check generated rule files 488 | cat .roo/rules/01-memory-bank-reference.md 489 | cat .roo/rules/02-active-context.md 490 | cat .roo/rules/03-product-context.md 491 | ``` 492 | 493 | ## Best Practices 494 | 495 | ### 1. Contextual Completeness 496 | 497 | Provide comprehensive context in your memory bank: 498 | - Document all major decisions with clear rationale 499 | - Keep current focus up-to-date 500 | - Include architectural patterns and project structure 501 | 502 | ### 2. Regular Updates 503 | 504 | Keep context fresh: 505 | - Update the memory bank at least daily 506 | - Sync to Roo-Code after significant changes 507 | - Document decisions as they happen, not after 508 | 509 | ### 3. Clear Descriptions 510 | 511 | Write clear content for Roo-Code: 512 | - Use concise, descriptive language 513 | - Format content with proper Markdown 514 | - Organize information logically 515 | 516 | ### 4. Automated Workflow 517 | 518 | Set up automation: 519 | - Use Git hooks for automatic updates 520 | - Schedule regular sync operations 521 | - Integrate with your CI/CD pipeline 522 | 523 | ### 5. Smart Integration with Roo 524 | 525 | Make Roo context-aware with minimal effort: 526 | - Just type "UMB" in Roo chat to activate Memory Bank features 527 | - Let Roo guide you through context updates with simple questions 528 | - Maintain project context without leaving your coding environment 529 | 530 | ## Smart Memory Bank Integration with Roo 531 | 532 | The Memory Bank system is designed to work seamlessly with Roo, requiring minimal effort from users. Simply type "UMB" in the Roo chat, and the system will intelligently handle the rest. 533 | 534 | ### Just Type "UMB" in Roo Chat 535 | 536 | Using Memory Bank with Roo is as simple as typing: 537 | 538 | ``` 539 | UMB 540 | ``` 541 | 542 | The system will: 543 | 1. Automatically detect if Memory Bank is set up 544 | 2. Install and configure it if needed 545 | 3. Guide you through context updates with simple questions 546 | 4. Suggest relevant context updates based on your current work 547 | 548 | ### First-Time Setup 549 | 550 | When you first type "UMB" in Roo chat, the system will: 551 | 552 | 1. Check if Memory Bank is installed 553 | 2. Set up the necessary directory structure 554 | 3. Initialize the Memory Bank for your project 555 | 4. Guide you through creating your initial context 556 | 557 | No manual installation or configuration required - just type "UMB" and follow the prompts. 558 | 559 | ### Smart Context Updates 560 | 561 | The system intelligently handles context updates: 562 | 563 | 1. **Automatic focus detection**: 564 | ``` 565 | UMB 566 | > I notice you're working on authentication. Update your active context? 567 | > [Yes] [No] [Show me what you detected] 568 | ``` 569 | 570 | 2. **Guided decision recording**: 571 | ``` 572 | UMB decision 573 | > Let's record a decision. What's the title? 574 | > After you type the title, I'll ask for rationale and implications. 575 | ``` 576 | 577 | 3. **Context-aware suggestions**: 578 | ``` 579 | UMB 580 | > Based on your recent commits, should I update your active context to 581 | > "Implementing user authentication" and add "JWT vs. session-based auth" 582 | > to open questions? 583 | > [Yes] [No] [Edit suggestion] 584 | ``` 585 | 586 | This integration creates a frictionless workflow where Roo handles the complexity of maintaining your project context, allowing you to focus on coding. 587 | 588 | ### 5. Team Alignment 589 | 590 | Ensure team consistency: 591 | - Establish team conventions for memory bank updates 592 | - Review memory bank content in team meetings 593 | - Use the memory bank during onboarding -------------------------------------------------------------------------------- /docs/USAGE.md: -------------------------------------------------------------------------------- 1 | # Roocode Memory Bank Optimized - Usage Guide 2 | 3 | This guide provides detailed instructions on how to use the Enhanced Memory Bank system effectively. 4 | 5 | ## Table of Contents 6 | 7 | 1. [Introduction](#introduction) 8 | 2. [Installation](#installation) 9 | 3. [Basic Usage](#basic-usage) 10 | 4. [Advanced Usage](#advanced-usage) 11 | 5. [File Structure](#file-structure) 12 | 6. [Best Practices](#best-practices) 13 | 7. [Troubleshooting](#troubleshooting) 14 | 15 | ## Introduction 16 | 17 | The Enhanced Memory Bank system is designed to solve the problem of context loss during software development. It provides a structured way to document and track your work, making it easier to resume tasks after interruptions and maintain a clear understanding of the project's state. 18 | 19 | ### Key Concepts 20 | 21 | - **Active Context**: What you're currently working on, recent changes, and open questions 22 | - **Product Context**: Project overview, goals, features, and architecture 23 | - **System Patterns**: Architectural and design patterns used in the project 24 | - **Decision Log**: Important decisions and their rationale 25 | - **Progress Tracking**: Current, completed, and upcoming tasks 26 | 27 | ## Installation 28 | 29 | The Memory Bank system can be installed and used in several ways: 30 | 31 | ### Option 1: Install in a separate directory (Recommended) 32 | 33 | This approach keeps the Memory Bank separate from your projects but still allows you to use it with any project. 34 | 35 | ```bash 36 | # Clone the repository 37 | git clone https://github.com/shipdocs/roocode-memorybank-optimized.git 38 | 39 | # Navigate to the directory 40 | cd roocode-memorybank-optimized 41 | 42 | # Install dependencies 43 | npm install 44 | 45 | # Build the project 46 | npm run build 47 | 48 | # Link for global usage 49 | npm link 50 | ``` 51 | 52 | Then, in any project where you want to use it: 53 | 54 | ```bash 55 | # Initialize the memory bank in your project 56 | cd /path/to/your/project 57 | npx umb init 58 | ``` 59 | 60 | ### Option 2: Download as a ZIP file 61 | 62 | 1. Download the ZIP from GitHub: https://github.com/shipdocs/roocode-memorybank-optimized/archive/refs/heads/main.zip 63 | 2. Extract to a directory of your choice 64 | 3. Navigate to the directory and run: 65 | ```bash 66 | cd path/to/extracted/directory 67 | npm install 68 | npm run build 69 | npm link # Makes the tool available globally 70 | ``` 71 | 72 | ### Option 3: Install directly in your project (Advanced) 73 | 74 | If you want to include the Memory Bank directly in your project: 75 | 76 | ```bash 77 | # 1. Navigate to your project root 78 | cd /path/to/your/project 79 | 80 | # 2. Clone the repository 81 | git clone https://github.com/shipdocs/roocode-memorybank-optimized.git 82 | 83 | # 3. Remove the .git directory to avoid git-in-git issues 84 | cd roocode-memorybank-optimized 85 | rm -rf .git 86 | 87 | # 4. Install and build 88 | npm install 89 | npm run build 90 | ``` 91 | 92 | > **Note:** The Memory Bank can be used with any project regardless of where it's installed, as it creates its own directory structure in the project where you run `npx umb init`. 93 | 94 | ## Basic Usage 95 | 96 | ### Initializing the Memory Bank 97 | 98 | Before using the memory bank, you need to initialize it: 99 | 100 | ```bash 101 | # If installed globally 102 | umb init 103 | 104 | # If installed locally 105 | npx umb init 106 | ``` 107 | 108 | This creates the necessary directory structure and initial files. 109 | 110 | ### Updating the Memory Bank 111 | 112 | The simplest way to update the memory bank is to run the `umb` command without arguments: 113 | 114 | ```bash 115 | umb 116 | ``` 117 | 118 | This automatically updates the memory bank based on Git history and tracks statistics. 119 | 120 | ### Updating Specific Sections 121 | 122 | You can update specific sections of the memory bank: 123 | 124 | ```bash 125 | # Update active context 126 | umb update activeContext currentFocus='Implementing new feature X' 127 | umb update activeContext recentChanges='Added unit tests for feature X' 128 | umb update activeContext openQuestions='How to handle edge case Y?' 129 | 130 | # Update product context 131 | umb update productContext projectOverview='A system for project context retention' 132 | umb update productContext goalsAndObjectives='Improve developer productivity' 133 | umb update productContext coreFeatures='- Feature A\n- Feature B' 134 | umb update productContext architectureOverview='Uses a modular design' 135 | 136 | # Update system patterns 137 | umb update systemPatterns architecturalPatterns='- MVC\n- Repository Pattern' 138 | umb update systemPatterns designPatterns='- Singleton\n- Factory' 139 | umb update systemPatterns technicalDecisions='- TypeScript for type safety' 140 | ``` 141 | 142 | ### Adding Decisions 143 | 144 | You can add decisions to the decision log: 145 | 146 | ```bash 147 | umb add decision title='Switch to TypeScript' rationale='Better type safety' implications='Need to refactor existing code' status='Implemented' 148 | ``` 149 | 150 | ## Advanced Usage 151 | 152 | ### Git Hooks 153 | 154 | You can install Git hooks to automatically remind you to update the memory bank before commits: 155 | 156 | ```bash 157 | npm run install-hooks 158 | ``` 159 | 160 | This adds a pre-commit hook that checks if the memory bank has been updated recently. 161 | 162 | ### Archiving Old Files 163 | 164 | You can manually archive old files: 165 | 166 | ```bash 167 | umb archive 168 | ``` 169 | 170 | This moves files older than the threshold (default: 7 days) to the archive directory. 171 | 172 | ### Reconstructing from Git History 173 | 174 | You can reconstruct the memory bank from Git history: 175 | 176 | ```bash 177 | # Reconstruct from the last 30 days (default) 178 | umb reconstruct 179 | 180 | # Reconstruct from the last 60 days 181 | umb reconstruct 60 182 | ``` 183 | 184 | ### Programmatic Usage 185 | 186 | You can use the memory bank programmatically in your Node.js applications: 187 | 188 | ```javascript 189 | import { MemoryBank } from 'roocode-memorybank-optimized'; 190 | 191 | // Create a new memory bank instance 192 | const memoryBank = new MemoryBank('/path/to/memory-bank'); 193 | 194 | // Initialize the memory bank 195 | await memoryBank.initialize(); 196 | 197 | // Update active context 198 | await memoryBank.updateActiveContext({ 199 | currentFocus: 'Implementing new feature', 200 | recentChanges: 'Added unit tests', 201 | openQuestions: 'How to handle edge cases?' 202 | }); 203 | 204 | // Update product context 205 | await memoryBank.updateProductContext({ 206 | projectOverview: 'A system for project context retention', 207 | goalsAndObjectives: 'Improve developer productivity', 208 | coreFeatures: '- Feature A\n- Feature B', 209 | architectureOverview: 'Uses a modular design' 210 | }); 211 | 212 | // Handle UMB command 213 | const result = await memoryBank.handleUMBCommand({ 214 | activeContext: { 215 | currentFocus: 'Implementing new feature' 216 | } 217 | }); 218 | ``` 219 | 220 | ## File Structure 221 | 222 | The memory bank creates the following directory structure: 223 | 224 | ``` 225 | memory-bank/ 226 | ├── .last_update # Timestamp of last update 227 | ├── activeContext.md # Master active context file 228 | ├── productContext.md # Product context file 229 | ├── systemPatterns.md # System patterns file 230 | ├── decisionLog.md # Decision log file 231 | ├── progress.md # Progress tracking file 232 | ├── daily/ # Daily context files 233 | │ ├── activeContext-YYYY-MM-DD.md 234 | │ └── ... 235 | ├── sessions/ # Session tracking files 236 | │ ├── session-YYYY-MM-DD-1.md 237 | │ └── ... 238 | └── archive/ # Archived files 239 | └── YYYY-MM/ # Organized by year-month 240 | ├── activeContext-YYYY-MM-DD.md 241 | └── ... 242 | ``` 243 | 244 | ### File Descriptions 245 | 246 | - **activeContext.md**: Contains information about what you're currently working on, recent changes, and open questions. 247 | - **productContext.md**: Contains information about the project's overview, goals, features, and architecture. 248 | - **systemPatterns.md**: Contains information about architectural and design patterns used in the project. 249 | - **decisionLog.md**: Contains a log of important decisions, their rationale, and implications. 250 | - **progress.md**: Contains information about current, completed, and upcoming tasks. 251 | 252 | ## Best Practices 253 | 254 | ### Regular Updates 255 | 256 | Update the memory bank regularly, ideally: 257 | - At the start of each work session 258 | - After completing a significant task 259 | - Before ending a work session 260 | - Before committing code 261 | 262 | ### Detailed Context 263 | 264 | Provide detailed context in your updates: 265 | - Be specific about what you're working on 266 | - Document recent changes with clear descriptions 267 | - Note any open questions or issues 268 | - Record important decisions and their rationale 269 | 270 | ### Integration with Workflow 271 | 272 | Integrate the memory bank into your workflow: 273 | - Use Git hooks to remind you to update the memory bank 274 | - Include memory bank updates in your code review process 275 | - Reference memory bank entries in commit messages 276 | 277 | ## Troubleshooting 278 | 279 | ### Common Issues 280 | 281 | #### Memory Bank Not Updating 282 | 283 | If the memory bank is not updating, check: 284 | - If you have the necessary permissions to write to the memory bank directory 285 | - If the memory bank has been initialized (`umb init`) 286 | - If there are any errors in the console output 287 | 288 | #### Git Hooks Not Working 289 | 290 | If Git hooks are not working, check: 291 | - If the hooks have been installed (`npm run install-hooks`) 292 | - If the hooks have the correct permissions (executable) 293 | - If the hooks are in the correct location (`.git/hooks`) 294 | 295 | #### Reconstruction Failing 296 | 297 | If reconstruction from Git history is failing, check: 298 | - If the repository has a valid Git history 299 | - If you have the necessary permissions to access the Git history 300 | - If there are any errors in the console output 301 | 302 | ### Getting Help 303 | 304 | If you encounter any issues not covered in this guide, please: 305 | - Check the [GitHub repository](https://github.com/shipdocs/roocode-memorybank-optimized) for known issues 306 | - Open a new issue on GitHub with a detailed description of the problem 307 | - Contact the maintainers for support -------------------------------------------------------------------------------- /docs/USER-GUIDE.md: -------------------------------------------------------------------------------- 1 | # User Guide 2 | 3 | This comprehensive guide explains how to use the Roocode Memory Bank Optimized system efficiently for project context retention and documentation. 4 | 5 | ## Table of Contents 6 | 7 | 1. [Installation](#installation) 8 | 2. [Initialization](#initialization) 9 | 3. [Basic Concepts](#basic-concepts) 10 | 4. [Command Line Interface](#command-line-interface) 11 | 5. [Managing Active Context](#managing-active-context) 12 | 6. [Product Context](#product-context) 13 | 7. [System Patterns](#system-patterns) 14 | 8. [Decision Logging](#decision-logging) 15 | 9. [Progress Tracking](#progress-tracking) 16 | 10. [Git Integration](#git-integration) 17 | 11. [Session Tracking](#session-tracking) 18 | 12. [Statistics](#statistics) 19 | 13. [Archiving](#archiving) 20 | 14. [Roo-Code Integration](#roo-code-integration) 21 | 15. [Programmatic Usage](#programmatic-usage) 22 | 16. [Best Practices](#best-practices) 23 | 17. [Troubleshooting](#troubleshooting) 24 | 25 | ## Installation 26 | 27 | The Memory Bank system can be installed and used in several ways: 28 | 29 | ### Option 1: Install in a separate directory (Recommended) 30 | 31 | This approach keeps the Memory Bank separate from your projects but still allows you to use it with any project. 32 | 33 | ```bash 34 | # Clone the repository in a dedicated directory 35 | git clone https://github.com/shipdocs/roocode-memorybank-optimized.git 36 | cd roocode-memorybank-optimized 37 | npm install 38 | npm run build 39 | npm link # Makes the tool available globally 40 | ``` 41 | 42 | Then, in any project where you want to use it: 43 | 44 | ```bash 45 | # Initialize the memory bank in your project 46 | cd /path/to/your/project 47 | npx umb init 48 | ``` 49 | 50 | ### Option 2: Download as a ZIP file 51 | 52 | 1. Download the ZIP from GitHub: https://github.com/shipdocs/roocode-memorybank-optimized/archive/refs/heads/main.zip 53 | 2. Extract to a directory of your choice 54 | 3. Navigate to the directory and run: 55 | ```bash 56 | cd path/to/extracted/directory 57 | npm install 58 | npm run build 59 | npm link # Makes the tool available globally 60 | ``` 61 | 62 | ### Option 3: Install directly in your project (Advanced) 63 | 64 | If you want to include the Memory Bank directly in your project: 65 | 66 | ```bash 67 | # 1. Navigate to your project root 68 | cd /path/to/your/project 69 | 70 | # 2. Clone the repository 71 | git clone https://github.com/shipdocs/roocode-memorybank-optimized.git 72 | 73 | # 3. Remove the .git directory to avoid git-in-git issues 74 | cd roocode-memorybank-optimized 75 | rm -rf .git 76 | 77 | # 4. Install and build 78 | npm install 79 | npm run build 80 | ``` 81 | 82 | > **Note:** The Memory Bank can be used with any project regardless of where it's installed, as it creates its own directory structure in the project where you run `npx umb init`. 83 | 84 | ## Initialization 85 | 86 | Before using the memory bank, you need to initialize it: 87 | 88 | ```bash 89 | npx umb init 90 | ``` 91 | 92 | This creates the memory bank directory structure in your current workspace: 93 | 94 | ``` 95 | memory-bank/ 96 | ├── .last_update # Timestamp of last update 97 | ├── activeContext.md # Master active context file 98 | ├── productContext.md # Product context file 99 | ├── systemPatterns.md # System patterns file 100 | ├── decisionLog.md # Decision log file 101 | ├── progress.md # Progress tracking file 102 | ├── daily/ # Daily context files 103 | ├── sessions/ # Session tracking files 104 | └── archive/ # Archived files 105 | ``` 106 | 107 | ## Basic Concepts 108 | 109 | The memory bank is built around several key concepts: 110 | 111 | - **Active Context**: What you're currently working on, recent changes, and open questions 112 | - **Product Context**: Project overview, goals, and features 113 | - **System Patterns**: Architectural and design patterns used in the project 114 | - **Decisions**: Important decisions and their rationale 115 | - **Progress**: Current, completed, and upcoming tasks 116 | 117 | Each concept is stored in its own file and updated through the command line interface. 118 | 119 | ## Command Line Interface 120 | 121 | The `umb` command is the primary interface for interacting with the memory bank. 122 | 123 | ### General Syntax 124 | 125 | ```bash 126 | npx umb [command] [options] 127 | ``` 128 | 129 | ### Available Commands 130 | 131 | - `init`: Initialize the memory bank 132 | - `help`: Show help information 133 | - `update`: Update a specific section in a file 134 | - `add`: Add a new item (like a decision) 135 | - `archive`: Archive old files 136 | - `reconstruct`: Reconstruct memory bank from Git history 137 | - `roo-setup`: Set up Roo-Code integration 138 | - `roo-sync`: Sync memory bank to Roo-Code rules 139 | 140 | ### Examples 141 | 142 | ```bash 143 | # Show help 144 | npx umb help 145 | 146 | # Initialize memory bank 147 | npx umb init 148 | 149 | # Update active context 150 | npx umb update activeContext currentFocus='Implementing new feature' 151 | 152 | # Add a decision 153 | npx umb add decision title='Use Redux' rationale='Centralized state management' implications='Learning curve' status='Implemented' 154 | ``` 155 | 156 | ## Managing Active Context 157 | 158 | The active context tracks what you're currently working on. 159 | 160 | ### Updating Current Focus 161 | 162 | ```bash 163 | npx umb update activeContext currentFocus='Implementing authentication system' 164 | ``` 165 | 166 | ### Recording Recent Changes 167 | 168 | ```bash 169 | npx umb update activeContext recentChanges='Added login form validation' 170 | ``` 171 | 172 | ### Documenting Open Questions 173 | 174 | ```bash 175 | npx umb update activeContext openQuestions='How should we handle session timeout?' 176 | ``` 177 | 178 | The active context is automatically tracked in daily files (`daily/activeContext-YYYY-MM-DD.md`) and aggregated into the master file (`activeContext.md`). 179 | 180 | ## Product Context 181 | 182 | The product context provides an overview of the project. 183 | 184 | ### Updating Project Overview 185 | 186 | ```bash 187 | npx umb update productContext projectOverview='A web application for managing customer relationships' 188 | ``` 189 | 190 | ### Defining Goals and Objectives 191 | 192 | ```bash 193 | npx umb update productContext goalsAndObjectives='- Increase customer retention\n- Streamline communication\n- Automate follow-ups' 194 | ``` 195 | 196 | ### Listing Core Features 197 | 198 | ```bash 199 | npx umb update productContext coreFeatures='- User authentication\n- Contact management\n- Email integration\n- Reporting' 200 | ``` 201 | 202 | ### Describing Architecture 203 | 204 | ```bash 205 | npx umb update productContext architectureOverview='React frontend with Node.js backend and MongoDB database' 206 | ``` 207 | 208 | ## System Patterns 209 | 210 | System patterns document the architectural and design patterns used in the project. 211 | 212 | ### Recording Architectural Patterns 213 | 214 | ```bash 215 | npx umb update systemPatterns architecturalPatterns='- Microservices\n- Event-driven architecture\n- REST API' 216 | ``` 217 | 218 | ### Documenting Design Patterns 219 | 220 | ```bash 221 | npx umb update systemPatterns designPatterns='- Singleton for logging\n- Observer for event handling\n- Factory for component creation' 222 | ``` 223 | 224 | ### Noting Technical Decisions 225 | 226 | ```bash 227 | npx umb update systemPatterns technicalDecisions='- TypeScript for static typing\n- Jest for testing\n- Redux for state management' 228 | ``` 229 | 230 | ## Decision Logging 231 | 232 | The decision log keeps track of important decisions and their rationale. 233 | 234 | ### Adding a Decision 235 | 236 | ```bash 237 | npx umb add decision title='Switch to GraphQL' rationale='More efficient data fetching' implications='Need to learn GraphQL schema design' status='Pending' 238 | ``` 239 | 240 | ### Decision Fields 241 | 242 | - `title`: Short description of the decision 243 | - `rationale`: Why the decision was made 244 | - `implications`: What are the consequences of this decision 245 | - `status`: Current status (Implemented, Pending, Revised) 246 | 247 | ## Progress Tracking 248 | 249 | Progress tracking keeps track of tasks and milestones. 250 | 251 | ### Updating Current Tasks 252 | 253 | ```bash 254 | npx umb update progress currentTasks='- Implement user authentication\n- Design dashboard UI\n- Set up database schema' 255 | ``` 256 | 257 | ### Recording Completed Tasks 258 | 259 | ```bash 260 | npx umb update progress completedTasks='- Project setup\n- Initial wireframes\n- API design' 261 | ``` 262 | 263 | ### Planning Upcoming Tasks 264 | 265 | ```bash 266 | npx umb update progress upcomingTasks='- Implement reporting feature\n- Add user roles\n- Create admin dashboard' 267 | ``` 268 | 269 | ### Setting Milestones 270 | 271 | ```bash 272 | npx umb update progress milestones='- Alpha release: End of month\n- Beta testing: Next quarter\n- V1 launch: Q4' 273 | ``` 274 | 275 | ## Git Integration 276 | 277 | The memory bank integrates with Git to track changes and reconstruct context. 278 | 279 | ### Auto-updating Based on Git History 280 | 281 | ```bash 282 | npx umb 283 | ``` 284 | 285 | This command: 286 | 1. Analyzes your Git history 287 | 2. Tracks files modified since the last update 288 | 3. Updates statistics like time spent and lines changed 289 | 4. Creates or updates the daily context file 290 | 291 | ### Reconstructing from Git History 292 | 293 | ```bash 294 | npx umb reconstruct 30 295 | ``` 296 | 297 | This reconstructs the memory bank based on the last 30 days of Git history. 298 | 299 | ## Session Tracking 300 | 301 | The memory bank tracks development sessions based on time gaps. 302 | 303 | When you run `npx umb`, it: 304 | 1. Checks if a new session should be started (based on time since last update) 305 | 2. Creates a new session file if needed 306 | 3. Updates the end time of the current session 307 | 308 | Session files are stored in the `sessions` directory and named `session-YYYY-MM-DD-N.md`. 309 | 310 | ## Statistics 311 | 312 | The memory bank automatically tracks the following statistics: 313 | 314 | - Time spent on the project 315 | - Estimated cost (based on hourly rate) 316 | - Files created, modified, and deleted 317 | - Lines of code added and removed 318 | - Total lines of code 319 | 320 | These statistics are updated when you run `npx umb` and stored in the active context file. 321 | 322 | ## Archiving 323 | 324 | Old files are automatically archived to keep the system organized. 325 | 326 | ```bash 327 | npx umb archive 328 | ``` 329 | 330 | This command: 331 | 1. Identifies files older than the threshold (default: 7 days) 332 | 2. Moves them to the `archive` directory 333 | 3. Organizes them by year-month 334 | 335 | ## Roo-Code Integration 336 | 337 | The memory bank integrates with Roo-Code to provide AI assistance with project context. 338 | 339 | ### Setting Up the Integration 340 | 341 | ```bash 342 | npx umb roo-setup 343 | ``` 344 | 345 | This command: 346 | 1. Detects if Roo-Code is used in your workspace 347 | 2. Creates the `.roo/rules` directory if needed 348 | 3. Generates initial rules based on memory bank content 349 | 350 | ### Syncing Memory Bank to Roo-Code 351 | 352 | ```bash 353 | npx umb roo-sync 354 | ``` 355 | 356 | This command: 357 | 1. Reads the current memory bank content 358 | 2. Generates custom instruction files for Roo-Code 359 | 3. Places them in the `.roo/rules` directory 360 | 361 | ### How the Integration Works 362 | 363 | The integration creates three main files in the `.roo/rules` directory: 364 | 1. `01-memory-bank-reference.md`: General reference to the memory bank 365 | 2. `02-active-context.md`: Current development focus and open questions 366 | 3. `03-product-context.md`: Project overview, goals, and features 367 | 368 | Roo-Code reads these files to gain context about your project, which helps it provide more relevant assistance. 369 | 370 | ## Programmatic Usage 371 | 372 | You can also use the memory bank programmatically: 373 | 374 | ```javascript 375 | import { MemoryBank, RooIntegration } from 'roocode-memorybank-optimized'; 376 | 377 | // Create and initialize memory bank 378 | const memoryBank = new MemoryBank('/path/to/memory-bank'); 379 | await memoryBank.initialize(); 380 | 381 | // Update active context 382 | await memoryBank.updateActiveContext({ 383 | currentFocus: 'Implementing new feature', 384 | recentChanges: 'Added unit tests', 385 | openQuestions: 'How to handle edge cases?' 386 | }); 387 | 388 | // Set up Roo-Code integration 389 | const rooIntegration = new RooIntegration({ 390 | memoryBankDir: '/path/to/memory-bank', 391 | rooRulesDir: '/path/to/.roo/rules' 392 | }); 393 | await rooIntegration.initialize(); 394 | await rooIntegration.syncMemoryBankToRoo(); 395 | ``` 396 | 397 | ## Best Practices 398 | 399 | ### Regular Updates 400 | 401 | - Update the memory bank at the beginning and end of each work session 402 | - Record important decisions as they happen 403 | - Keep the active context updated when switching tasks 404 | 405 | ### Meaningful Descriptions 406 | 407 | - Use clear, concise descriptions for current focus 408 | - Provide detailed rationale for decisions 409 | - Document open questions as they arise 410 | 411 | ### Integration with Development Workflow 412 | 413 | - Set up Git hooks to remind you to update the memory bank 414 | - Integrate with your project management tool 415 | - Use the Roo-Code integration for AI assistance 416 | 417 | ### Team Usage 418 | 419 | - Create a shared memory bank for team projects 420 | - Include the memory bank in your repository 421 | - Establish team conventions for updates 422 | 423 | ## Troubleshooting 424 | 425 | ### Common Issues 426 | 427 | #### Command Not Found 428 | 429 | ``` 430 | Command not found: umb 431 | ``` 432 | 433 | Solution: Install the package globally or use `npx umb` instead. 434 | 435 | #### Git Integration Not Working 436 | 437 | ``` 438 | Error: Git repository not found 439 | ``` 440 | 441 | Solution: Ensure you're running the command in a Git repository. 442 | 443 | #### Roo-Code Integration Issues 444 | 445 | ``` 446 | Failed to sync memory bank to Roo-Code rules 447 | ``` 448 | 449 | Solution: 450 | 1. Check that Roo-Code is properly set up in your workspace 451 | 2. Ensure the `.roo/rules` directory exists and is writable 452 | 3. Run `npx umb roo-setup` to reconfigure the integration 453 | 454 | #### File Permission Errors 455 | 456 | ``` 457 | Error: EACCES: permission denied 458 | ``` 459 | 460 | Solution: Check the file permissions in your memory bank directory. 461 | 462 | ### Getting Help 463 | 464 | For more help, check the following resources: 465 | 466 | - GitHub repository: [shipdocs/roocode-memorybank-optimized](https://github.com/shipdocs/roocode-memorybank-optimized) 467 | - Issue tracker: [shipdocs/roocode-memorybank-optimized/issues](https://github.com/shipdocs/roocode-memorybank-optimized/issues) 468 | 469 | ## Further Reading 470 | 471 | - [API Reference](API.md): Detailed API documentation 472 | - [Roo-Code Integration](ROO-INTEGRATION.md): In-depth guide to Roo-Code integration 473 | - [Quick Start Guide](QUICK-START.md): Simplified setup instructions -------------------------------------------------------------------------------- /memory-bank/README.md: -------------------------------------------------------------------------------- 1 | # Memory Bank 2 | 3 | This directory contains the memory bank for your project. 4 | It helps maintain context and documentation across development sessions. 5 | 6 | ## Structure 7 | 8 | - daily/: Daily context files 9 | - sessions/: Session tracking files 10 | - archive/: Archived files 11 | 12 | ## Usage 13 | 14 | This directory is automatically populated when you initialize and use the memory bank. 15 | The content of this directory is excluded from git to avoid committing user-specific data. 16 | 17 | To initialize the memory bank, run: 18 | 19 | ```bash 20 | npx umb init 21 | ``` 22 | 23 | Or programmatically: 24 | 25 | ```javascript 26 | const { MemoryBank } = require('roocode-memorybank-optimized'); 27 | const memoryBank = new MemoryBank(); 28 | await memoryBank.initialize(); 29 | -------------------------------------------------------------------------------- /memory-bank/archive/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shipdocs/roocode-memorybank-optimized/77dfea529faf1ade49ee416451251333f86ed545/memory-bank/archive/.gitkeep -------------------------------------------------------------------------------- /memory-bank/daily/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shipdocs/roocode-memorybank-optimized/77dfea529faf1ade49ee416451251333f86ed545/memory-bank/daily/.gitkeep -------------------------------------------------------------------------------- /memory-bank/sessions/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shipdocs/roocode-memorybank-optimized/77dfea529faf1ade49ee416451251333f86ed545/memory-bank/sessions/.gitkeep -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "roocode-memorybank-optimized", 3 | "version": "1.0.0", 4 | "description": "Enhanced Memory Bank System for project context retention and documentation", 5 | "main": "dist/index.js", 6 | "types": "dist/index.d.ts", 7 | "scripts": { 8 | "build": "tsc", 9 | "start": "node dist/index.js", 10 | "dev": "ts-node src/index.ts", 11 | "test": "jest", 12 | "umb": "node scripts/umb.js", 13 | "install-hooks": "node scripts/install-git-hooks.js", 14 | "test-memory-bank": "ts-node scripts/test-memory-bank.ts", 15 | "roo-setup": "node scripts/setup-roo-integration.js", 16 | "roo-sync": "node scripts/generate-roo-rules.js" 17 | }, 18 | "keywords": [ 19 | "memory-bank", 20 | "documentation", 21 | "project-context", 22 | "knowledge-management", 23 | "developer-tools", 24 | "roo-code", 25 | "ai-coding-assistant" 26 | ], 27 | "author": "Shipdocs", 28 | "license": "MIT", 29 | "dependencies": { 30 | "fs-extra": "^11.1.1" 31 | }, 32 | "devDependencies": { 33 | "@types/fs-extra": "^11.0.1", 34 | "@types/jest": "^29.5.3", 35 | "@types/node": "^20.4.5", 36 | "jest": "^29.6.1", 37 | "ts-jest": "^29.1.1", 38 | "ts-node": "^10.9.2", 39 | "typescript": "^5.1.6" 40 | }, 41 | "bin": { 42 | "umb": "./scripts/umb.js" 43 | }, 44 | "files": [ 45 | "dist", 46 | "scripts", 47 | "README.md", 48 | "LICENSE" 49 | ], 50 | "engines": { 51 | "node": ">=14.0.0" 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /scripts/generate-roo-rules.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /** 4 | * Generate Roo-Code Rules 5 | * 6 | * This script generates custom instruction files for Roo-Code based on 7 | * the current memory bank content. It can be run manually or set up 8 | * as a post-update hook for the memory bank. 9 | * 10 | * Usage: 11 | * node scripts/generate-roo-rules.js [memory-bank-dir] [rules-dir] 12 | */ 13 | 14 | import fs from 'fs-extra'; 15 | import path from 'path'; 16 | import { fileURLToPath } from 'url'; 17 | import { RooIntegration } from '../dist/roo-integration.js'; 18 | 19 | // Get current directory 20 | const __filename = fileURLToPath(import.meta.url); 21 | const __dirname = path.dirname(__filename); 22 | 23 | // Parse command line arguments 24 | const args = process.argv.slice(2); 25 | const memoryBankDir = args[0] || path.join(process.cwd(), 'memory-bank'); 26 | const rulesDir = args[1] || path.join(process.cwd(), '.roo', 'rules'); 27 | 28 | /** 29 | * Main function to generate Roo-Code rules 30 | */ 31 | async function generateRooRules() { 32 | console.log('📝 Generating Roo-Code Rules from Memory Bank'); 33 | console.log('=========================================='); 34 | 35 | try { 36 | console.log(`📂 Memory Bank directory: ${memoryBankDir}`); 37 | console.log(`📂 Rules directory: ${rulesDir}`); 38 | 39 | // Check if directories exist 40 | if (!await fs.pathExists(memoryBankDir)) { 41 | console.error(`❌ Memory bank directory does not exist: ${memoryBankDir}`); 42 | console.log(' Run initialization first: npx umb init'); 43 | process.exit(1); 44 | } 45 | 46 | // Create rules directory if it doesn't exist 47 | await fs.ensureDir(rulesDir); 48 | 49 | // Create Roo integration 50 | const integration = new RooIntegration({ 51 | memoryBankDir, 52 | rooRulesDir: rulesDir 53 | }); 54 | 55 | // Generate rules 56 | console.log('🔄 Generating rules from memory bank content...'); 57 | const result = await integration.generateRooRules(); 58 | 59 | if (result) { 60 | console.log('✅ Rules generated successfully!'); 61 | console.log(` Rules are available in: ${rulesDir}`); 62 | } else { 63 | console.error('❌ Failed to generate rules'); 64 | } 65 | 66 | console.log(''); 67 | console.log('📋 Generated Files:'); 68 | const files = await fs.readdir(rulesDir); 69 | files.forEach(file => { 70 | console.log(` - ${file}`); 71 | }); 72 | 73 | } catch (error) { 74 | console.error('❌ Error generating Roo-Code rules:', error); 75 | process.exit(1); 76 | } 77 | } 78 | 79 | // Run the generator 80 | generateRooRules().catch(error => { 81 | console.error('Error:', error); 82 | process.exit(1); 83 | }); -------------------------------------------------------------------------------- /scripts/init-memory-bank.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /** 4 | * Initialize Memory Bank 5 | * 6 | * This script initializes the memory bank with the required files. 7 | */ 8 | 9 | const { MemoryBank } = require('../dist/memory-bank'); 10 | 11 | async function main() { 12 | try { 13 | console.log('Initializing memory bank...'); 14 | 15 | // Create a new memory bank instance 16 | const memoryBank = new MemoryBank(); 17 | 18 | // Initialize the memory bank 19 | const success = await memoryBank.initialize(); 20 | 21 | if (success) { 22 | console.log('Memory bank initialized successfully.'); 23 | console.log('You can now use the UMB command to update the memory bank.'); 24 | } else { 25 | console.error('Failed to initialize memory bank.'); 26 | } 27 | } catch (error) { 28 | console.error('Error initializing memory bank:', error); 29 | } 30 | } 31 | 32 | // Run the main function 33 | main().catch(error => { 34 | console.error('Unhandled error:', error); 35 | process.exit(1); 36 | }); -------------------------------------------------------------------------------- /scripts/install-git-hooks.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /** 4 | * Install Git Hooks for Enhanced Memory Bank 5 | * 6 | * This script installs Git hooks to automatically update the memory bank 7 | * before commits and provide reminders if the memory bank hasn't been 8 | * updated in a while. 9 | * 10 | * Usage: 11 | * node scripts/install-git-hooks.js 12 | */ 13 | 14 | import fs from 'fs'; 15 | import path from 'path'; 16 | import { execSync } from 'child_process'; 17 | import { fileURLToPath } from 'url'; 18 | 19 | // Get current directory 20 | const __filename = fileURLToPath(import.meta.url); 21 | const __dirname = path.dirname(__filename); 22 | const projectRoot = path.resolve(process.cwd()); 23 | 24 | // Define paths 25 | const gitHooksDir = path.join(projectRoot, '.git', 'hooks'); 26 | const preCommitHookPath = path.join(gitHooksDir, 'pre-commit'); 27 | 28 | // Create pre-commit hook content 29 | const preCommitHookContent = `#!/bin/sh 30 | 31 | # Enhanced Memory Bank Pre-Commit Hook 32 | # This hook checks if the memory bank needs updating before committing 33 | 34 | # Get the last update time of the memory bank 35 | LAST_UPDATE_FILE="memory-bank/.last_update" 36 | 37 | if [ -f "$LAST_UPDATE_FILE" ]; then 38 | LAST_UPDATE=$(cat "$LAST_UPDATE_FILE") 39 | 40 | # Count commits since last memory bank update 41 | COMMIT_COUNT=$(git log --since="$LAST_UPDATE" --oneline | wc -l) 42 | 43 | # If there are 5+ commits since last update, remind to update memory bank 44 | if [ $COMMIT_COUNT -ge 5 ]; then 45 | echo "⚠️ Memory bank hasn't been updated in $COMMIT_COUNT commits." 46 | echo "Consider running 'umb' to update the memory bank before committing." 47 | 48 | # Ask if the user wants to update the memory bank now 49 | echo -n "Would you like to update the memory bank now? [y/N] " 50 | read answer 51 | 52 | if [ "$answer" = "y" ] || [ "$answer" = "Y" ]; then 53 | echo "Updating memory bank..." 54 | umb 55 | 56 | # Check if the update was successful 57 | if [ $? -ne 0 ]; then 58 | echo "❌ Failed to update memory bank. Commit aborted." 59 | exit 1 60 | fi 61 | 62 | echo "✅ Memory bank updated successfully." 63 | else 64 | echo "Proceeding with commit without updating memory bank." 65 | fi 66 | fi 67 | else 68 | echo "⚠️ Memory bank has never been initialized." 69 | echo "Consider running 'umb init' to initialize the enhanced memory bank." 70 | 71 | # Ask if the user wants to initialize the memory bank now 72 | echo -n "Would you like to initialize the memory bank now? [y/N] " 73 | read answer 74 | 75 | if [ "$answer" = "y" ] || [ "$answer" = "Y" ]; then 76 | echo "Initializing memory bank..." 77 | umb init 78 | 79 | # Check if the initialization was successful 80 | if [ $? -ne 0 ]; then 81 | echo "❌ Failed to initialize memory bank. Commit aborted." 82 | exit 1 83 | fi 84 | 85 | echo "✅ Memory bank initialized successfully." 86 | else 87 | echo "Proceeding with commit without initializing memory bank." 88 | fi 89 | fi 90 | 91 | # Continue with the commit 92 | exit 0 93 | `; 94 | 95 | // Main function 96 | function main() { 97 | try { 98 | console.log('Installing Git hooks for Enhanced Memory Bank...'); 99 | 100 | // Check if .git directory exists 101 | if (!fs.existsSync(path.join(projectRoot, '.git'))) { 102 | console.error('Error: .git directory not found. Make sure you are in a Git repository.'); 103 | process.exit(1); 104 | } 105 | 106 | // Create hooks directory if it doesn't exist 107 | if (!fs.existsSync(gitHooksDir)) { 108 | fs.mkdirSync(gitHooksDir, { recursive: true }); 109 | } 110 | 111 | // Write pre-commit hook 112 | fs.writeFileSync(preCommitHookPath, preCommitHookContent); 113 | 114 | // Make the hook executable 115 | fs.chmodSync(preCommitHookPath, '755'); 116 | 117 | console.log('✅ Git hooks installed successfully.'); 118 | console.log('Pre-commit hook will now check if the memory bank needs updating before commits.'); 119 | } catch (error) { 120 | console.error('Error installing Git hooks:', error); 121 | process.exit(1); 122 | } 123 | } 124 | 125 | // Run the main function 126 | main(); -------------------------------------------------------------------------------- /scripts/setup-roo-integration.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /** 4 | * Setup Roo-Code Integration 5 | * 6 | * This script sets up the memory bank integration with Roo-Code. 7 | * It creates the necessary directories, configuration, and sample rules. 8 | * 9 | * Usage: 10 | * node scripts/setup-roo-integration.js [workspace-path] 11 | */ 12 | 13 | import fs from 'fs-extra'; 14 | import path from 'path'; 15 | import { fileURLToPath } from 'url'; 16 | import { RooIntegration } from '../dist/roo-integration.js'; 17 | 18 | // Get current directory 19 | const __filename = fileURLToPath(import.meta.url); 20 | const __dirname = path.dirname(__filename); 21 | 22 | // Parse command line arguments 23 | const args = process.argv.slice(2); 24 | const workspacePath = args[0] || process.cwd(); 25 | 26 | /** 27 | * Main function to set up Roo-Code integration 28 | */ 29 | async function setupRooIntegration() { 30 | console.log('🚀 Setting up Roo-Code Integration for Memory Bank'); 31 | console.log('================================================'); 32 | 33 | try { 34 | // Check if the workspace path exists 35 | if (!await fs.pathExists(workspacePath)) { 36 | console.error(`❌ Workspace path does not exist: ${workspacePath}`); 37 | process.exit(1); 38 | } 39 | 40 | console.log(`📂 Using workspace path: ${workspacePath}`); 41 | 42 | // Auto-configure for the workspace 43 | console.log('🔍 Detecting Roo-Code workspace...'); 44 | const integration = await RooIntegration.autoConfigureForWorkspace(workspacePath); 45 | 46 | if (!integration) { 47 | console.log('🔧 Creating Roo-Code configuration...'); 48 | 49 | // Create .roo directory if it doesn't exist 50 | const rooDir = path.join(workspacePath, '.roo'); 51 | await fs.ensureDir(rooDir); 52 | 53 | // Create rules directory 54 | const rulesDir = path.join(rooDir, 'rules'); 55 | await fs.ensureDir(rulesDir); 56 | 57 | // Create memory bank directory 58 | const memoryBankDir = path.join(workspacePath, 'memory-bank'); 59 | 60 | // Create new integration with the configured paths 61 | const manualIntegration = new RooIntegration({ 62 | workspaceDir: workspacePath, 63 | memoryBankDir, 64 | rooRulesDir: rulesDir 65 | }); 66 | 67 | // Initialize the integration 68 | console.log('🏗️ Initializing memory bank...'); 69 | await manualIntegration.initialize(); 70 | 71 | // Generate Roo rules 72 | console.log('📝 Generating Roo-Code rules...'); 73 | await manualIntegration.generateRooRules(); 74 | 75 | console.log(''); 76 | console.log('✅ Setup completed successfully!'); 77 | console.log(''); 78 | console.log('📋 Next steps:'); 79 | console.log(' 1. Update your memory bank with project context:'); 80 | console.log(' npx umb update activeContext currentFocus="Your current focus"'); 81 | console.log(' 2. Update the memory bank whenever context changes'); 82 | console.log(' 3. Roo-Code will now have access to your project context'); 83 | console.log(''); 84 | } else { 85 | console.log('✅ Roo-Code workspace detected and configured!'); 86 | console.log(''); 87 | console.log('📋 Next steps:'); 88 | console.log(' 1. Update your memory bank with project context:'); 89 | console.log(' npx umb update activeContext currentFocus="Your current focus"'); 90 | console.log(' 2. Roo-Code will now have access to your project context'); 91 | console.log(''); 92 | } 93 | } catch (error) { 94 | console.error('❌ Error setting up Roo-Code integration:', error); 95 | process.exit(1); 96 | } 97 | } 98 | 99 | // Run the setup 100 | setupRooIntegration().catch(error => { 101 | console.error('Error:', error); 102 | process.exit(1); 103 | }); -------------------------------------------------------------------------------- /scripts/test-memory-bank.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /** 4 | * Test Memory Bank Script 5 | * 6 | * This script tests the memory bank functionality by initializing it 7 | * and creating all the master files. 8 | */ 9 | 10 | const { MemoryBank } = require('../dist/memory-bank'); 11 | 12 | async function main() { 13 | try { 14 | console.log('Initializing memory bank...'); 15 | 16 | // Create a new memory bank instance 17 | const memoryBank = new MemoryBank(); 18 | 19 | // Initialize the memory bank (this will create all master files) 20 | const success = await memoryBank.initialize(); 21 | 22 | if (success) { 23 | console.log('Memory bank initialized successfully with all master files.'); 24 | 25 | // Update active context as a test 26 | const activeContextUpdate = { 27 | currentFocus: 'Testing the memory bank functionality', 28 | recentChanges: 'Created and initialized the memory bank', 29 | openQuestions: 'How can we extend the memory bank functionality?' 30 | }; 31 | 32 | const updateSuccess = await memoryBank.updateActiveContext(activeContextUpdate); 33 | 34 | if (updateSuccess) { 35 | console.log('Active context updated successfully.'); 36 | } else { 37 | console.error('Failed to update active context.'); 38 | } 39 | } else { 40 | console.error('Failed to initialize memory bank.'); 41 | } 42 | } catch (error) { 43 | console.error('Error:', error); 44 | } 45 | } 46 | 47 | // Run the main function 48 | main().catch(error => { 49 | console.error('Unhandled error:', error); 50 | process.exit(1); 51 | }); -------------------------------------------------------------------------------- /scripts/umb.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /** 4 | * UMB (Update Memory Bank) Command Line Tool 5 | * 6 | * This script allows you to run UMB commands from the command line. 7 | * It's a wrapper around the update-memory-bank.js script. 8 | * 9 | * Usage: 10 | * node scripts/umb.js [command] 11 | * 12 | * Examples: 13 | * node scripts/umb.js 14 | * node scripts/umb.js help 15 | * node scripts/umb.js update activeContext currentFocus='New feature development' 16 | */ 17 | 18 | const { spawn } = require('child_process'); 19 | const path = require('path'); 20 | 21 | // Get command line arguments 22 | const args = process.argv.slice(2); 23 | 24 | // If no arguments are provided, run the update-memory-bank.js script 25 | if (args.length === 0) { 26 | console.log('UMB command received. Updating memory bank...'); 27 | 28 | // Run the update-memory-bank.js script 29 | const updateScript = path.join(__dirname, 'update-memory-bank.js'); 30 | const child = spawn('node', [updateScript], { stdio: 'inherit' }); 31 | 32 | child.on('close', (code) => { 33 | if (code === 0) { 34 | console.log('\nMemory bank updated successfully.'); 35 | console.log('You can view the updated files in the memory-bank directory.'); 36 | } else { 37 | console.error(`\nError updating memory bank. Exit code: ${code}`); 38 | } 39 | }); 40 | } else if (args[0] === 'help') { 41 | // Display help information 42 | console.log(` 43 | UMB Command Help: 44 | ---------------- 45 | UMB commands update the memory bank files in the memory-bank directory. 46 | 47 | Usage: 48 | UMB - Automatically gather information and update the memory bank 49 | UMB help - Show this help message 50 | UMB update
='' - Update a specific section in a file 51 | UMB add decision title='' rationale='<rationale>' implications='<implications>' status='<status>' - Add a new decision 52 | 53 | Examples: 54 | UMB update activeContext currentFocus='Implementing new authentication flow' 55 | UMB update productContext coreFeatures='- Feature 1\\n- Feature 2\\n- Feature 3' 56 | UMB add decision title='Switch to TypeScript' rationale='Better type safety' implications='Need to refactor existing code' status='Implemented' 57 | UMB update progress completedTasks=['Task 1', 'Task 2'] 58 | `); 59 | } else { 60 | // For now, we'll just run the update-memory-bank.js script for all commands 61 | // In a future implementation, we could parse the arguments and call the appropriate functions 62 | console.log('Advanced UMB commands are not yet implemented.'); 63 | console.log('Running the default UMB command to update the memory bank...'); 64 | 65 | // Run the update-memory-bank.js script 66 | const updateScript = path.join(__dirname, 'update-memory-bank.js'); 67 | const child = spawn('node', [updateScript], { stdio: 'inherit' }); 68 | 69 | child.on('close', (code) => { 70 | if (code === 0) { 71 | console.log('\nMemory bank updated successfully.'); 72 | console.log('You can view the updated files in the memory-bank directory.'); 73 | } else { 74 | console.error(`\nError updating memory bank. Exit code: ${code}`); 75 | } 76 | }); 77 | } -------------------------------------------------------------------------------- /scripts/update-context.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /** 4 | * Update Context Script 5 | * 6 | * This script demonstrates how to use the Memory Bank programmatically 7 | * to update the active context. 8 | */ 9 | 10 | const { MemoryBank } = require('../dist/memory-bank'); 11 | 12 | async function main() { 13 | try { 14 | console.log('Updating memory bank...'); 15 | 16 | // Create a new memory bank instance 17 | const memoryBank = new MemoryBank(); 18 | 19 | // Update active context 20 | const activeContextUpdate = { 21 | currentFocus: 'Testing the programmatic API of the memory bank', 22 | recentChanges: 'Updated the memory bank using the JavaScript API', 23 | openQuestions: 'How can we extend the CLI to support all the commands mentioned in the README?' 24 | }; 25 | 26 | const updateSuccess = await memoryBank.updateActiveContext(activeContextUpdate); 27 | 28 | if (updateSuccess) { 29 | console.log('Active context updated successfully.'); 30 | 31 | // Update product context as well 32 | const productContextUpdate = { 33 | projectOverview: 'Enhanced Memory Bank System for project context retention and documentation', 34 | goalsAndObjectives: '- Maintain project context across development sessions\n- Track decisions and their rationale\n- Provide statistics on development effort', 35 | coreFeatures: '- Daily context files\n- Session tracking\n- Statistics tracking\n- Git integration\n- Archiving', 36 | architectureOverview: '- MemoryBank: Main class for memory bank operations\n- EnhancedMemoryBank: Core functionality\n- RooIntegration: Integration with Roo-Code' 37 | }; 38 | 39 | const productUpdateSuccess = await memoryBank.updateProductContext(productContextUpdate); 40 | 41 | if (productUpdateSuccess) { 42 | console.log('Product context updated successfully.'); 43 | } else { 44 | console.error('Failed to update product context.'); 45 | } 46 | } else { 47 | console.error('Failed to update active context.'); 48 | } 49 | } catch (error) { 50 | console.error('Error:', error); 51 | } 52 | } 53 | 54 | // Run the main function 55 | main().catch(error => { 56 | console.error('Unhandled error:', error); 57 | process.exit(1); 58 | }); -------------------------------------------------------------------------------- /scripts/update-memory-bank.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /** 4 | * UMB (Update Memory Bank) Implementation 5 | * 6 | * This script implements the UMB functionality to update the memory bank files. 7 | * It gathers information about the project and updates the memory bank files accordingly 8 | * by using the MemoryBank class from the src/ library. 9 | */ 10 | 11 | const { execSync } = require('child_process'); 12 | // Assuming the compiled output is in 'dist' at the project root 13 | const { MemoryBank } = require('../dist/index'); 14 | 15 | /** 16 | * Retrieves commit hashes and messages from the last 7 days, excluding merge commits. 17 | * 18 | * @returns {string[]} An array of recent commit descriptions, or an empty array if unavailable. 19 | */ 20 | function gatherRecentCommits() { 21 | try { 22 | // Get recent commits (last 7 days) 23 | const recentCommits = execSync('git log --since="7 days ago" --pretty=format:"%h - %s" --no-merges').toString(); 24 | return recentCommits.split('\n').filter(line => line.trim() !== ''); 25 | } catch (error) { 26 | // console.warn('Warning: Error gathering recent commits (git likely not initialized or no commits):', error.message); 27 | return []; 28 | } 29 | } 30 | 31 | /** 32 | * Retrieves a list of recent merged pull requests from the last 7 days using git merge commits. 33 | * 34 | * @returns {string[]} An array of strings representing recent merged pull requests, or an empty array if none are found or on error. 35 | */ 36 | function gatherRecentPRs() { 37 | try { 38 | // This is a simplified version - in a real implementation, you would use the GitHub API 39 | // For now, we'll use git log to get merge commits which likely represent merged PRs 40 | const recentPRs = execSync('git log --since="7 days ago" --merges --pretty=format:"%h - %s"').toString(); 41 | return recentPRs.split('\n').filter(line => line.trim() !== ''); 42 | } catch (error) { 43 | // console.warn('Warning: Error gathering recent PRs (git likely not initialized or no merge commits):', error.message); 44 | return []; 45 | } 46 | } 47 | 48 | /** 49 | * Gathers recent project activity and updates the memory bank using the MemoryBank class. 50 | * 51 | * Collects recent commits and pull requests from the local git repository, prepares structured update content for product context, active context, system patterns, decisions, and progress, and delegates the update process to the MemoryBank's command handler. 52 | * 53 | * @returns {Promise<{success: boolean, message: string}>} The result of the memory bank update operation. 54 | */ 55 | async function autoUpdateMemoryBank() { 56 | // Instantiate MemoryBank. By default, it will target './memory-bank' in the current working directory. 57 | const mb = new MemoryBank(); 58 | // The initialize method now ensures the directory and master files are created if they don't exist. 59 | // It uses the default content defined within the MemoryBank class. 60 | await mb.initialize(); 61 | console.log(`Memory bank will be managed at: ${mb.baseDir}`); 62 | 63 | try { 64 | // Gather information from recent commits and PRs 65 | const recentCommits = gatherRecentCommits(); 66 | const recentPRs = gatherRecentPRs(); 67 | 68 | // Extract information from commits and PRs 69 | const recentChangesContent = recentPRs.length > 0 70 | ? `Recent PRs:\n${recentPRs.map(pr => `- ${pr}`).join('\n')}` 71 | : (recentCommits.length > 0 ? `Recent Commits:\n${recentCommits.map(c => `- ${c}`).join('\n')}` : 'No recent PRs or commits found.'); 72 | 73 | // Current focus based on recent activity - placeholder 74 | const currentFocusContent = "Maintaining and improving the memory bank system for better context retention across development sessions."; 75 | 76 | // Core features based on project structure - placeholder 77 | const coreFeaturesContent = `- Daily context tracking 78 | - Session management 79 | - Statistics tracking 80 | - Roo-Code integration 81 | - Automated documentation updates`; 82 | 83 | // Architecture overview based on project structure - placeholder 84 | const architectureOverviewContent = `- Enhanced Memory Bank: Core functionality for context retention 85 | - Memory Bank: Simplified interface to the enhanced system 86 | - Roo Integration: Connects memory bank with Roo-Code 87 | - UMB Command: CLI tool for updating memory bank files`; 88 | 89 | // System patterns based on project structure - placeholder 90 | const architecturalPatternsContent = `- File-based storage for memory bank data 91 | - Command-line interface for updates 92 | - Markdown format for human-readable documentation 93 | - Automated updates based on git history`; 94 | 95 | // Recent decisions based on commits - placeholder 96 | const decisionContent = { 97 | title: "Refactor UMB script to use MemoryBank library", 98 | rationale: "Centralize memory bank logic and improve maintainability.", 99 | implications: "UMB script now relies on the compiled MemoryBank class from dist/.", 100 | status: "Implemented" 101 | }; 102 | 103 | // Progress updates based on recent activity - placeholder 104 | const progressContent = { 105 | currentTasks: [ 106 | "Verify UMB command behavior with refactored script", 107 | "Ensure documentation for MemoryBank class is up-to-date" 108 | ], 109 | completedTasks: [ 110 | "Refactored MemoryBank constructor for flexible pathing", 111 | "Added SystemPatterns, Decision, Progress update methods to MemoryBank class", 112 | "Refactored update-memory-bank.js to use MemoryBank class" 113 | ], 114 | upcomingTasks: [ 115 | "Further testing of UMB command scenarios", 116 | "Consider adding more automated info gathering to UMB script" 117 | ], 118 | milestones: [ 119 | { 120 | title: "Memory Bank Library Refactoring", 121 | description: "Successfully refactored UMB script to use the MemoryBank library, centralizing logic." 122 | } 123 | ] 124 | }; 125 | 126 | // Create the updates object for handleUMBCommand 127 | const updates = { 128 | productContext: { 129 | coreFeatures: coreFeaturesContent, 130 | architectureOverview: architectureOverviewContent 131 | }, 132 | activeContext: { 133 | currentFocus: currentFocusContent, 134 | recentChanges: recentChangesContent 135 | }, 136 | systemPatterns: { 137 | architecturalPatterns: architecturalPatternsContent 138 | }, 139 | decision: decisionContent, 140 | progress: progressContent 141 | }; 142 | 143 | // Call the centralized command handler in MemoryBank 144 | const result = await mb.handleUMBCommand(updates); 145 | return result; 146 | 147 | } catch (error) { 148 | console.error('Error automatically updating memory bank:', error); 149 | return { 150 | success: false, 151 | message: `Failed to update memory bank: ${error.message}` 152 | }; 153 | } 154 | } 155 | 156 | /** 157 | * Executes the memory bank auto-update process and logs the outcome. 158 | * 159 | * Calls {@link autoUpdateMemoryBank}, outputs the resulting message, and sets the process exit code to 1 if the update fails. 160 | */ 161 | async function main() { 162 | const result = await autoUpdateMemoryBank(); 163 | console.log(result.message); 164 | if (!result.success) { 165 | process.exitCode = 1; // Indicate failure 166 | } 167 | } 168 | 169 | main(); -------------------------------------------------------------------------------- /src/enhanced-memory-bank.ts: -------------------------------------------------------------------------------- 1 | import fs from 'fs-extra'; 2 | import path from 'path'; 3 | import { execSync } from 'child_process'; 4 | 5 | /** 6 | * Configuration options for the Enhanced Memory Bank 7 | */ 8 | export interface MemoryBankConfig { 9 | /** Base directory for the memory bank */ 10 | baseDir: string; 11 | /** Directory name for daily files */ 12 | dailyDirName?: string; 13 | /** Directory name for session files */ 14 | sessionsDirName?: string; 15 | /** Directory name for archived files */ 16 | archiveDirName?: string; 17 | /** Session timeout in hours */ 18 | sessionTimeoutHours?: number; 19 | /** Archive threshold in days */ 20 | archiveThresholdDays?: number; 21 | /** Developer hourly rate for cost estimation */ 22 | developerHourlyRate?: number; 23 | } 24 | 25 | /** 26 | * Statistics tracking for the memory bank 27 | */ 28 | export interface Statistics { 29 | timeSpent: string; 30 | estimatedCost: number; 31 | filesCreated: number; 32 | filesModified: number; 33 | filesDeleted: number; 34 | linesAdded: number; 35 | linesRemoved: number; 36 | totalLines: number; 37 | } 38 | 39 | /** 40 | * Enhanced Memory Bank class for project context retention 41 | */ 42 | export class EnhancedMemoryBank { 43 | private baseDir: string; 44 | private dailyDir: string; 45 | private sessionsDir: string; 46 | private archiveDir: string; 47 | private lastUpdatePath: string; 48 | private sessionTimeoutHours: number; 49 | private archiveThresholdDays: number; 50 | private developerHourlyRate: number; 51 | 52 | /** 53 | * Create a new Enhanced Memory Bank instance 54 | * @param config Configuration options 55 | */ 56 | constructor(config: MemoryBankConfig) { 57 | this.baseDir = config.baseDir; 58 | 59 | // Set up directory paths 60 | this.dailyDir = path.join(this.baseDir, config.dailyDirName || 'daily'); 61 | this.sessionsDir = path.join(this.baseDir, config.sessionsDirName || 'sessions'); 62 | this.archiveDir = path.join(this.baseDir, config.archiveDirName || 'archive'); 63 | this.lastUpdatePath = path.join(this.baseDir, '.last_update'); 64 | 65 | // Set up configuration values 66 | this.sessionTimeoutHours = config.sessionTimeoutHours || 2; 67 | this.archiveThresholdDays = config.archiveThresholdDays || 7; 68 | this.developerHourlyRate = config.developerHourlyRate || 60; 69 | } 70 | 71 | /** 72 | * Initialize the memory bank directories 73 | * @returns True if initialization was successful 74 | */ 75 | public async initialize(): Promise<boolean> { 76 | try { 77 | // Create the necessary directories 78 | await fs.ensureDir(this.baseDir); 79 | await fs.ensureDir(this.dailyDir); 80 | await fs.ensureDir(this.sessionsDir); 81 | await fs.ensureDir(this.archiveDir); 82 | 83 | // Initialize the last update timestamp if it doesn't exist 84 | if (!await fs.pathExists(this.lastUpdatePath)) { 85 | await fs.writeFile(this.lastUpdatePath, new Date().toISOString()); 86 | } 87 | 88 | return true; 89 | } catch (error) { 90 | console.error('Error initializing enhanced memory bank:', error); 91 | return false; 92 | } 93 | } 94 | 95 | /** 96 | * Get current date in YYYY-MM-DD format 97 | * @param date Optional date to format (defaults to current date) 98 | * @returns Formatted date string 99 | */ 100 | public getDateString(date: Date = new Date()): string { 101 | return date.toISOString().split('T')[0]; 102 | } 103 | 104 | /** 105 | * Get current timestamp in a consistent format 106 | * @returns Formatted timestamp string 107 | */ 108 | public getTimestamp(): string { 109 | return new Date().toISOString().replace('T', ' ').substring(0, 19); 110 | } 111 | 112 | /** 113 | * Read a file 114 | * @param filePath Path to the file 115 | * @returns File content as string 116 | */ 117 | public async readFile(filePath: string): Promise<string> { 118 | try { 119 | return await fs.readFile(filePath, 'utf8'); 120 | } catch (error) { 121 | console.error(`Error reading file ${filePath}:`, error); 122 | return ''; 123 | } 124 | } 125 | 126 | /** 127 | * Write to a file 128 | * @param filePath Path to the file 129 | * @param content Content to write 130 | * @returns True if write was successful 131 | */ 132 | public async writeFile(filePath: string, content: string): Promise<boolean> { 133 | try { 134 | // Ensure directory exists 135 | const dir = path.dirname(filePath); 136 | await fs.ensureDir(dir); 137 | 138 | await fs.writeFile(filePath, content, 'utf8'); 139 | return true; 140 | } catch (error) { 141 | console.error(`Error writing to file ${filePath}:`, error); 142 | return false; 143 | } 144 | } 145 | 146 | /** 147 | * Extract a section from markdown content 148 | * @param content Markdown content 149 | * @param sectionHeader Section header to extract 150 | * @returns Extracted section content 151 | */ 152 | public extractSection(content: string, sectionHeader: string): string { 153 | const sectionRegex = new RegExp(`${sectionHeader}\\n([\\s\\S]*?)(?=\\n## |$)`); 154 | const match = content.match(sectionRegex); 155 | return match ? match[1].trim() : ''; 156 | } 157 | 158 | /** 159 | * Update a section in markdown content 160 | * @param content Markdown content 161 | * @param sectionHeader Section header to update 162 | * @param newContent New content for the section 163 | * @returns Updated markdown content 164 | */ 165 | public updateSection(content: string, sectionHeader: string, newContent: string): string { 166 | const sectionRegex = new RegExp(`${sectionHeader}\\n([\\s\\S]*?)(?=\\n## |$)`); 167 | const currentSection = content.match(sectionRegex); 168 | if (currentSection) { 169 | return content.replace(sectionRegex, `${sectionHeader}\n${newContent}\n`); 170 | } 171 | // If section header doesn't exist, append it with the new content 172 | return `${content}\n${sectionHeader}\n${newContent}\n`; 173 | } 174 | /** 175 | * Create a daily file 176 | * @param date Optional date (defaults to current date) 177 | * @returns Path to the created file 178 | */ 179 | public async createDailyFile(date: Date = new Date()): Promise<string> { 180 | const dateStr = this.getDateString(date); 181 | const filePath = path.join(this.dailyDir, `activeContext-${dateStr}.md`); 182 | 183 | if (!await fs.pathExists(filePath)) { 184 | const content = `# Active Context - ${dateStr} 185 | 186 | ## Current Focus 187 | - 188 | 189 | ## Recent Changes 190 | - 191 | 192 | ## Open Questions/Issues 193 | - 194 | 195 | ## Statistics 196 | - Time Spent: 0h 0m 197 | - Estimated Cost: $0 198 | - Files Created: 0 199 | - Files Modified: 0 200 | - Files Deleted: 0 201 | - Lines of Code Added: 0 202 | - Lines of Code Removed: 0 203 | - Total Lines of Code: 0 204 | `; 205 | await this.writeFile(filePath, content); 206 | } 207 | 208 | return filePath; 209 | } 210 | 211 | /** 212 | * Get the latest daily file 213 | * @returns Path to the latest daily file 214 | */ 215 | public async getLatestDailyFile(): Promise<string | null> { 216 | try { 217 | if (!await fs.pathExists(this.dailyDir)) { 218 | return null; // Daily directory doesn't exist 219 | } 220 | const files = await fs.readdir(this.dailyDir); 221 | const dailyFiles = files.filter(file => file.startsWith('activeContext-') && file.endsWith('.md')); 222 | 223 | if (dailyFiles.length === 0) { 224 | return null; 225 | } 226 | 227 | // Sort by date (newest first) 228 | dailyFiles.sort().reverse(); 229 | 230 | return path.join(this.dailyDir, dailyFiles[0]); 231 | } catch (error) { 232 | console.error('Error getting latest daily file:', error); 233 | return null; 234 | } 235 | } 236 | 237 | /** 238 | * Check if a new session should be started 239 | * @returns True if a new session should be started 240 | */ 241 | public async shouldStartNewSession(): Promise<boolean> { 242 | try { 243 | if (!await fs.pathExists(this.lastUpdatePath)) { 244 | return true; 245 | } 246 | 247 | const lastUpdateStr = await fs.readFile(this.lastUpdatePath, 'utf8'); 248 | const lastUpdate = new Date(lastUpdateStr); 249 | const now = new Date(); 250 | 251 | // Check if the last update was more than sessionTimeoutHours ago 252 | const hoursDiff = (now.getTime() - lastUpdate.getTime()) / (1000 * 60 * 60); 253 | 254 | return hoursDiff > this.sessionTimeoutHours; 255 | } catch (error) { 256 | console.error('Error checking if new session should be started:', error); 257 | return true; 258 | } 259 | } 260 | 261 | /** 262 | * Create a new session file 263 | * @returns Path to the created session file 264 | */ 265 | public async createSessionFile(): Promise<string> { 266 | const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); 267 | const filePath = path.join(this.sessionsDir, `session-${timestamp}.md`); 268 | 269 | const content = `# Development Session - ${this.getTimestamp()} 270 | 271 | ## Start Time 272 | ${this.getTimestamp()} 273 | 274 | ## End Time 275 | (In progress) 276 | 277 | ## Focus 278 | - 279 | 280 | ## Notes 281 | - 282 | 283 | ## Statistics 284 | - Time Spent: 0h 0m 285 | - Estimated Cost: $0 286 | `; 287 | 288 | await this.writeFile(filePath, content); 289 | return filePath; 290 | } 291 | 292 | /** 293 | * Get the current session file 294 | * @returns Path to the current session file 295 | */ 296 | public async getCurrentSessionFile(): Promise<string | null> { 297 | try { 298 | if (!await fs.pathExists(this.sessionsDir)) { 299 | return null; // Sessions directory doesn't exist 300 | } 301 | const files = await fs.readdir(this.sessionsDir); 302 | const sessionFiles = files.filter(file => file.startsWith('session-') && file.endsWith('.md')); 303 | 304 | if (sessionFiles.length === 0) { 305 | return null; 306 | } 307 | 308 | // Sort by date (newest first) 309 | sessionFiles.sort().reverse(); 310 | 311 | // Check if the newest session is still active 312 | const filePath = path.join(this.sessionsDir, sessionFiles[0]); 313 | const content = await this.readFile(filePath); 314 | 315 | if (content.includes('End Time\n(In progress)')) { 316 | return filePath; 317 | } 318 | 319 | return null; 320 | } catch (error) { 321 | console.error('Error getting current session file:', error); 322 | return null; 323 | } 324 | } 325 | 326 | /** 327 | * Update the end time of a session file 328 | * @param filePath Path to the session file 329 | * @returns True if update was successful 330 | */ 331 | public async updateSessionEndTime(filePath: string): Promise<boolean> { 332 | try { 333 | const content = await this.readFile(filePath); 334 | const updatedContent = content.replace( 335 | /## End Time\n(.*)/, 336 | `## End Time\n${this.getTimestamp()}` 337 | ); 338 | 339 | return await this.writeFile(filePath, updatedContent); 340 | } catch (error) { 341 | console.error('Error updating session end time:', error); 342 | return false; 343 | } 344 | } 345 | 346 | /** 347 | * Archive old files 348 | * @returns True if archiving was successful 349 | */ 350 | public async archiveOldFiles(): Promise<boolean> { 351 | try { 352 | if (!await fs.pathExists(this.dailyDir) || !await fs.pathExists(this.archiveDir)) { 353 | // If daily or archive dir doesn't exist, nothing to do or nowhere to move. 354 | return true; 355 | } 356 | const now = new Date(); 357 | const thresholdDate = new Date(now.getTime() - this.archiveThresholdDays * 24 * 60 * 60 * 1000); 358 | const thresholdDateStr = this.getDateString(thresholdDate); 359 | 360 | // Archive daily files 361 | const dailyFiles = await fs.readdir(this.dailyDir); 362 | for (const file of dailyFiles) { 363 | if (!file.startsWith('activeContext-') || !file.endsWith('.md')) { 364 | continue; 365 | } 366 | 367 | const dateStr = file.replace('activeContext-', '').replace('.md', ''); 368 | if (dateStr < thresholdDateStr) { 369 | const sourcePath = path.join(this.dailyDir, file); 370 | const destPath = path.join(this.archiveDir, file); 371 | await fs.move(sourcePath, destPath, { overwrite: true }); 372 | console.log(`Archived ${file}`); 373 | } 374 | } 375 | 376 | return true; 377 | } catch (error) { 378 | console.error('Error archiving old files:', error); 379 | return false; 380 | } 381 | } 382 | 383 | /** 384 | * Load context from previous day 385 | * @returns True if context was loaded successfully 386 | */ 387 | public async loadContext(): Promise<boolean> { 388 | try { 389 | const latestDailyFile = await this.getLatestDailyFile(); 390 | if (!latestDailyFile) { 391 | return false; 392 | } 393 | 394 | // Create a new daily file for today 395 | const todayFile = await this.createDailyFile(); 396 | 397 | // Copy content from latest daily file to today's file 398 | const latestContent = await this.readFile(latestDailyFile); 399 | const todayContent = await this.readFile(todayFile); // Read potentially newly created empty file 400 | 401 | // Extract sections from latest file 402 | const currentFocus = this.extractSection(latestContent, '## Current Focus'); 403 | const openQuestions = this.extractSection(latestContent, '## Open Questions/Issues'); 404 | 405 | // Update today's file with content from latest file 406 | let updatedContent = todayContent; 407 | updatedContent = this.updateSection(updatedContent, '## Current Focus', currentFocus); 408 | updatedContent = this.updateSection(updatedContent, '## Open Questions/Issues', openQuestions); 409 | 410 | return await this.writeFile(todayFile, updatedContent); 411 | } catch (error) { 412 | console.error('Error loading context:', error); 413 | return false; 414 | } 415 | } 416 | 417 | /** 418 | * Track statistics for this update 419 | * @returns Statistics object 420 | */ 421 | public async trackStatistics(): Promise<Statistics> { 422 | try { 423 | // Get the last update time 424 | let lastUpdate = new Date(); 425 | if (await fs.pathExists(this.lastUpdatePath)) { 426 | const lastUpdateStr = await fs.readFile(this.lastUpdatePath, 'utf8'); 427 | lastUpdate = new Date(lastUpdateStr); 428 | } 429 | 430 | const now = new Date(); 431 | const minutesSpent = Math.round((now.getTime() - lastUpdate.getTime()) / (1000 * 60)); 432 | const hoursSpent = Math.floor(minutesSpent / 60); 433 | const remainingMinutes = minutesSpent % 60; 434 | const timeSpent = `${hoursSpent}h ${remainingMinutes}m`; 435 | 436 | // Calculate estimated cost 437 | const estimatedCost = Math.round((minutesSpent / 60) * this.developerHourlyRate * 100) / 100; 438 | 439 | // Get git statistics if available 440 | let filesCreated = 0; 441 | let filesModified = 0; 442 | let filesDeleted = 0; 443 | let linesAdded = 0; 444 | let linesRemoved = 0; 445 | let totalLines = 0; 446 | 447 | try { 448 | // Get git diff stats 449 | const gitDiffStats = execSync('git diff --stat HEAD', { encoding: 'utf8', stdio: 'pipe' }); 450 | const gitDiffMatch = gitDiffStats.match(/(\d+) files? changed, (\d+) insertions?\(\+\), (\d+) deletions?\(-\)/); 451 | 452 | if (gitDiffMatch) { 453 | filesModified = parseInt(gitDiffMatch[1], 10); 454 | linesAdded = parseInt(gitDiffMatch[2], 10); 455 | linesRemoved = parseInt(gitDiffMatch[3], 10); 456 | } 457 | 458 | // Get total lines of code 459 | // Using -z and -0 for safer filename handling, and -r for xargs to not run wc if no files. 460 | // Added || echo "0 total" to ensure the command succeeds even if wc has partial errors, 461 | // preventing execSync from throwing. 462 | const gitLsFilesCmd = '(git ls-files -z | grep -z -vE "(^|/)node_modules/" | xargs -0 -r wc -l) || echo "0 total"'; 463 | const gitLsFilesOutput = execSync(gitLsFilesCmd, { encoding: 'utf8', stdio: 'pipe' }); 464 | const gitLsMatch = gitLsFilesOutput.match(/(\d+)\s+total/); 465 | 466 | if (gitLsMatch && gitLsMatch[1]) { 467 | totalLines = parseInt(gitLsMatch[1], 10); 468 | } else if (gitLsFilesOutput.includes("0 total") && !gitLsMatch) { 469 | // This case handles when the fallback "0 total" was echoed 470 | totalLines = 0; 471 | } 472 | 473 | } catch (error) { 474 | console.warn('Git statistics not available or failed to parse:', error); 475 | } 476 | 477 | const stats: Statistics = { 478 | timeSpent, 479 | estimatedCost, 480 | filesCreated, // Note: filesCreated and filesDeleted are not easily available from simple git diff --stat 481 | filesModified, 482 | filesDeleted, 483 | linesAdded, 484 | linesRemoved, 485 | totalLines 486 | }; 487 | 488 | return stats; 489 | } catch (error) { 490 | console.error('Error tracking statistics:', error); 491 | return { 492 | timeSpent: '0h 0m', 493 | estimatedCost: 0, 494 | filesCreated: 0, 495 | filesModified: 0, 496 | filesDeleted: 0, 497 | linesAdded: 0, 498 | linesRemoved: 0, 499 | totalLines: 0 500 | }; 501 | } 502 | } 503 | 504 | /** 505 | * Update daily active context 506 | * @param update Update object with sections to update 507 | * @returns True if update was successful 508 | */ 509 | public async updateDailyActiveContext(update: { 510 | currentFocus?: string; 511 | recentChanges?: string; 512 | openQuestions?: string; 513 | }): Promise<boolean> { 514 | try { 515 | // Create or get today's daily file 516 | const todayFile = await this.createDailyFile(); 517 | const content = await this.readFile(todayFile); 518 | let updatedContent = content; 519 | 520 | if (update.currentFocus) { 521 | updatedContent = this.updateSection( 522 | updatedContent, 523 | '## Current Focus', 524 | update.currentFocus 525 | ); 526 | } 527 | 528 | // Add new recent change at the top of the list 529 | if (update.recentChanges) { 530 | const timestamp = this.getTimestamp(); 531 | const existingRecentChanges = this.extractSection(updatedContent, '## Recent Changes'); 532 | const newRecentChanges = `[${timestamp}] - ${update.recentChanges}${existingRecentChanges ? '\n' + existingRecentChanges : ''}`; 533 | updatedContent = this.updateSection( 534 | updatedContent, 535 | '## Recent Changes', 536 | newRecentChanges 537 | ); 538 | } 539 | 540 | if (update.openQuestions) { 541 | updatedContent = this.updateSection( 542 | updatedContent, 543 | '## Open Questions/Issues', 544 | update.openQuestions 545 | ); 546 | } 547 | 548 | return await this.writeFile(todayFile, updatedContent); 549 | } catch (error) { 550 | console.error('Error updating daily active context:', error); 551 | return false; 552 | } 553 | } 554 | 555 | /** 556 | * Aggregate daily files into master files 557 | * @returns True if aggregation was successful 558 | */ 559 | public async aggregateDailyFiles(): Promise<boolean> { 560 | try { 561 | // This is a placeholder for future implementation 562 | // In a real implementation, this would combine information from daily files 563 | // into master files for better organization 564 | return true; 565 | } catch (error) { 566 | console.error('Error aggregating daily files:', error); 567 | return false; 568 | } 569 | } 570 | 571 | /** 572 | * Reconstruct memory bank from existing files 573 | * @returns True if reconstruction was successful 574 | */ 575 | public async reconstructMemoryBank(): Promise<boolean> { 576 | try { 577 | // This is a placeholder for future implementation 578 | // In a real implementation, this would rebuild the memory bank structure 579 | // from existing files, useful for recovery or migration 580 | return true; 581 | } catch (error) { 582 | console.error('Error reconstructing memory bank:', error); 583 | return false; 584 | } 585 | } 586 | } -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * VibeCoding Memory Bank 3 | * 4 | * A system for project context retention and documentation. 5 | * This module exports the memory bank functionality for use in other projects. 6 | */ 7 | 8 | // Export the main classes and interfaces 9 | export { EnhancedMemoryBank, MemoryBankConfig, Statistics } from './enhanced-memory-bank'; 10 | export { MemoryBank, memoryBank } from './memory-bank'; 11 | export { RooIntegration, RooIntegrationConfig, rooIntegration } from './roo-integration'; 12 | 13 | // Export utility functions 14 | export { 15 | getDateString, 16 | getTimestamp, 17 | createDailyFile, 18 | getLatestDailyFile, 19 | shouldStartNewSession, 20 | createSessionFile, 21 | getCurrentSessionFile, 22 | updateSessionEndTime, 23 | archiveOldFiles, 24 | loadContext, 25 | trackStatistics, 26 | updateDailyActiveContext, 27 | aggregateDailyFiles, 28 | reconstructMemoryBank 29 | } from './memory-bank'; -------------------------------------------------------------------------------- /src/memory-bank.ts: -------------------------------------------------------------------------------- 1 | import fs from 'fs-extra'; 2 | import path from 'path'; 3 | import { EnhancedMemoryBank, Statistics } from './enhanced-memory-bank'; 4 | 5 | /** 6 | * Options for the MemoryBank constructor. 7 | */ 8 | export interface MemoryBankOptions { 9 | /** 10 | * Absolute or relative path to the base directory for the memory bank. 11 | * If provided, this takes precedence over projectName. 12 | */ 13 | baseDir?: string; 14 | /** 15 | * Name of the project. If provided (and baseDir is not), the memory bank 16 | * will be created in a directory with this name within the current working directory. 17 | * e.g., path.join(process.cwd(), projectName) 18 | */ 19 | projectName?: string; 20 | } 21 | 22 | /** 23 | * Memory Bank Manager 24 | * 25 | * This class provides a simplified interface to the Enhanced Memory Bank system. 26 | * It handles the initialization, configuration, and operations of the memory bank. 27 | */ 28 | export class MemoryBank { 29 | private _enhancedMemoryBank: EnhancedMemoryBank; 30 | private baseDir: string; 31 | private productContextPath: string; 32 | private activeContextPath: string; 33 | private systemPatternsPath: string; 34 | private decisionLogPath: string; 35 | private progressPath: string; 36 | private lastUpdatePath: string; 37 | 38 | /** 39 | * Create a new Memory Bank instance. 40 | * @param options Optional configuration for base directory or project name, or a string for baseDir for backward compatibility. 41 | * - If options is a string, it's treated as `baseDir`. 42 | * - If options is an object: 43 | * - `options.baseDir`: Specifies the exact base directory. 44 | * - `options.projectName`: Creates a directory named `projectName` in `process.cwd()`. 45 | * - If no options are provided, defaults to `path.join(process.cwd(), 'memory-bank')`. 46 | */ 47 | constructor(options?: MemoryBankOptions | string) { 48 | if (typeof options === 'string') { 49 | // Backward compatibility: if a string is passed, treat it as baseDir 50 | this.baseDir = options; 51 | } else if (options?.baseDir) { 52 | this.baseDir = options.baseDir; 53 | } else if (options?.projectName) { 54 | this.baseDir = path.join(process.cwd(), options.projectName); 55 | } else { 56 | this.baseDir = path.join(process.cwd(), 'memory-bank'); 57 | } 58 | 59 | // Initialize the enhanced memory bank 60 | this._enhancedMemoryBank = new EnhancedMemoryBank({ 61 | baseDir: this.baseDir 62 | }); 63 | 64 | // Define file paths 65 | this.productContextPath = path.join(this.baseDir, 'productContext.md'); 66 | this.activeContextPath = path.join(this.baseDir, 'activeContext.md'); 67 | this.systemPatternsPath = path.join(this.baseDir, 'systemPatterns.md'); 68 | this.decisionLogPath = path.join(this.baseDir, 'decisionLog.md'); 69 | this.progressPath = path.join(this.baseDir, 'progress.md'); 70 | this.lastUpdatePath = path.join(this.baseDir, '.last_update'); 71 | } 72 | 73 | // Public methods to expose EnhancedMemoryBank functionality 74 | public getTimestamp(): string { 75 | return this._enhancedMemoryBank.getTimestamp(); 76 | } 77 | 78 | public getDateString(date?: Date): string { 79 | return this._enhancedMemoryBank.getDateString(date); 80 | } 81 | 82 | public async createDailyFile(date?: Date): Promise<string> { 83 | return this._enhancedMemoryBank.createDailyFile(date); 84 | } 85 | 86 | public async getLatestDailyFile(): Promise<string | null> { 87 | return this._enhancedMemoryBank.getLatestDailyFile(); 88 | } 89 | 90 | public async shouldStartNewSession(): Promise<boolean> { 91 | return this._enhancedMemoryBank.shouldStartNewSession(); 92 | } 93 | 94 | public async createSessionFile(): Promise<string> { 95 | return this._enhancedMemoryBank.createSessionFile(); 96 | } 97 | 98 | public async getCurrentSessionFile(): Promise<string | null> { 99 | return this._enhancedMemoryBank.getCurrentSessionFile(); 100 | } 101 | 102 | public async updateSessionEndTime(filePath: string): Promise<boolean> { 103 | return this._enhancedMemoryBank.updateSessionEndTime(filePath); 104 | } 105 | 106 | public async archiveOldFiles(): Promise<boolean> { 107 | return this._enhancedMemoryBank.archiveOldFiles(); 108 | } 109 | 110 | public async loadContext(): Promise<boolean> { 111 | return this._enhancedMemoryBank.loadContext(); 112 | } 113 | 114 | public async trackStatistics(): Promise<Statistics> { 115 | return this._enhancedMemoryBank.trackStatistics(); 116 | } 117 | 118 | public async updateDailyActiveContext(update: any): Promise<boolean> { 119 | return this._enhancedMemoryBank.updateDailyActiveContext(update); 120 | } 121 | 122 | public async aggregateDailyFiles(): Promise<boolean> { 123 | return this._enhancedMemoryBank.aggregateDailyFiles(); 124 | } 125 | 126 | public async reconstructMemoryBank(): Promise<boolean> { 127 | return this._enhancedMemoryBank.reconstructMemoryBank(); 128 | } 129 | 130 | /** 131 | * Initialize the memory bank 132 | * @returns True if initialization was successful 133 | */ 134 | public async initialize(): Promise<boolean> { 135 | try { 136 | // Initialize the enhanced memory bank 137 | const success = await this._enhancedMemoryBank.initialize(); 138 | 139 | // Create master files if they don't exist 140 | if (success) { 141 | await this.createMasterFiles(); 142 | } 143 | 144 | return success; 145 | } catch (error) { 146 | console.error('Error initializing memory bank:', error); 147 | return false; 148 | } 149 | } 150 | 151 | /** 152 | * Create master files if they don't exist 153 | */ 154 | private async createMasterFiles(): Promise<void> { 155 | const date = new Date(); 156 | const timestamp = this._enhancedMemoryBank.getTimestamp(); 157 | 158 | // Create productContext.md 159 | if (!await fs.pathExists(this.productContextPath)) { 160 | const content = `# Product Context 161 | 162 | ## Project Overview 163 | - 164 | 165 | ## Goals and Objectives 166 | - 167 | 168 | ## Core Features 169 | - 170 | 171 | ## Architecture Overview 172 | - 173 | 174 | --- 175 | Footnotes: 176 | [${timestamp}] - Created product context 177 | `; 178 | await fs.writeFile(this.productContextPath, content, 'utf8'); 179 | } 180 | 181 | // Create activeContext.md 182 | if (!await fs.pathExists(this.activeContextPath)) { 183 | const content = `# Active Context 184 | 185 | ## Current Focus 186 | - 187 | 188 | ## Recent Changes 189 | - 190 | 191 | ## Open Questions/Issues 192 | - 193 | 194 | ## Statistics 195 | - Time Spent: 0h 0m 196 | - Estimated Cost: $0 197 | - Files Created: 0 198 | - Files Modified: 0 199 | - Files Deleted: 0 200 | - Lines of Code Added: 0 201 | - Lines of Code Removed: 0 202 | - Total Lines of Code: 0 203 | `; 204 | await fs.writeFile(this.activeContextPath, content, 'utf8'); 205 | } 206 | 207 | // Create systemPatterns.md 208 | if (!await fs.pathExists(this.systemPatternsPath)) { 209 | const content = `# System Patterns 210 | 211 | ## Architectural Patterns 212 | - 213 | 214 | ## Design Patterns 215 | - 216 | 217 | ## Technical Decisions 218 | - 219 | 220 | --- 221 | [${timestamp}] - Created system patterns 222 | `; 223 | await fs.writeFile(this.systemPatternsPath, content, 'utf8'); 224 | } 225 | 226 | // Create decisionLog.md 227 | if (!await fs.pathExists(this.decisionLogPath)) { 228 | const content = `# Decision Log 229 | 230 | ## Decisions 231 | - 232 | 233 | `; 234 | await fs.writeFile(this.decisionLogPath, content, 'utf8'); 235 | } 236 | 237 | // Create progress.md 238 | if (!await fs.pathExists(this.progressPath)) { 239 | const content = `# Progress 240 | 241 | ## Current Tasks 242 | - 243 | 244 | ## Completed Tasks 245 | - 246 | 247 | ## Upcoming Tasks 248 | - 249 | 250 | ## Milestones 251 | - 252 | 253 | `; 254 | await fs.writeFile(this.progressPath, content, 'utf8'); 255 | } 256 | } 257 | 258 | /** 259 | * Update product context 260 | * @param update Update object with sections to update 261 | * @returns True if update was successful 262 | */ 263 | public async updateProductContext(update: { 264 | projectOverview?: string; 265 | goalsAndObjectives?: string; 266 | coreFeatures?: string; 267 | architectureOverview?: string; 268 | }): Promise<boolean> { 269 | try { 270 | const content = await this._enhancedMemoryBank.readFile(this.productContextPath); 271 | let updatedContent = content; 272 | 273 | if (update.projectOverview) { 274 | updatedContent = this._enhancedMemoryBank.updateSection( 275 | updatedContent, 276 | '## Project Overview', 277 | update.projectOverview 278 | ); 279 | } 280 | 281 | if (update.goalsAndObjectives) { 282 | updatedContent = this._enhancedMemoryBank.updateSection( 283 | updatedContent, 284 | '## Goals and Objectives', 285 | update.goalsAndObjectives 286 | ); 287 | } 288 | 289 | if (update.coreFeatures) { 290 | updatedContent = this._enhancedMemoryBank.updateSection( 291 | updatedContent, 292 | '## Core Features', 293 | update.coreFeatures 294 | ); 295 | } 296 | 297 | if (update.architectureOverview) { 298 | updatedContent = this._enhancedMemoryBank.updateSection( 299 | updatedContent, 300 | '## Architecture Overview', 301 | update.architectureOverview 302 | ); 303 | } 304 | 305 | // Add timestamp to footnotes 306 | const timestamp = this._enhancedMemoryBank.getTimestamp(); 307 | updatedContent = updatedContent.replace( 308 | /---\nFootnotes:\n([\s\S]*?)$/, 309 | `---\nFootnotes:\n[${timestamp}] - Updated product context\n` 310 | ); 311 | 312 | return await this._enhancedMemoryBank.writeFile(this.productContextPath, updatedContent); 313 | } catch (error) { 314 | console.error('Error updating product context:', error); 315 | return false; 316 | } 317 | } 318 | 319 | /** 320 | * Update active context 321 | * @param update Update object with sections to update 322 | * @returns True if update was successful 323 | */ 324 | public async updateActiveContext(update: { 325 | currentFocus?: string; 326 | recentChanges?: string; 327 | openQuestions?: string; 328 | }): Promise<boolean> { 329 | try { 330 | // First update the daily active context file 331 | const dailyUpdateSuccess = await this._enhancedMemoryBank.updateDailyActiveContext(update); 332 | 333 | // Then update the master active context file for backward compatibility 334 | const content = await this._enhancedMemoryBank.readFile(this.activeContextPath); 335 | let updatedContent = content; 336 | 337 | if (update.currentFocus) { 338 | updatedContent = this._enhancedMemoryBank.updateSection( 339 | updatedContent, 340 | '## Current Focus', 341 | update.currentFocus 342 | ); 343 | } 344 | 345 | // Add new recent change at the top of the list 346 | if (update.recentChanges) { 347 | const timestamp = this._enhancedMemoryBank.getTimestamp(); 348 | updatedContent = updatedContent.replace( 349 | /## Recent Changes\n/, 350 | `## Recent Changes\n[${timestamp}] - ${update.recentChanges}\n` 351 | ); 352 | } 353 | 354 | if (update.openQuestions) { 355 | updatedContent = this._enhancedMemoryBank.updateSection( 356 | updatedContent, 357 | '## Open Questions/Issues', 358 | update.openQuestions 359 | ); 360 | } 361 | 362 | const masterUpdateSuccess = await this._enhancedMemoryBank.writeFile(this.activeContextPath, updatedContent); 363 | 364 | // Update the last update timestamp 365 | await fs.writeFile(this.lastUpdatePath, new Date().toISOString()); 366 | 367 | return dailyUpdateSuccess && masterUpdateSuccess; 368 | } catch (error) { 369 | console.error('Error updating active context:', error); 370 | return false; 371 | } 372 | } 373 | 374 | /** 375 | * Handle UMB command 376 | * @param updates Update object with sections to update 377 | * @returns Result object with success status and message 378 | */ 379 | public async handleUMBCommand(updates: { 380 | productContext?: { 381 | projectOverview?: string; 382 | goalsAndObjectives?: string; 383 | coreFeatures?: string; 384 | architectureOverview?: string; 385 | }; 386 | activeContext?: { 387 | currentFocus?: string; 388 | recentChanges?: string; 389 | openQuestions?: string; 390 | }; 391 | systemPatterns?: { 392 | architecturalPatterns?: string; 393 | designPatterns?: string; 394 | technicalDecisions?: string; 395 | }; 396 | decision?: { 397 | title: string; 398 | rationale: string; 399 | implications: string; 400 | status: 'Implemented' | 'Pending' | 'Revised'; 401 | }; 402 | progress?: { 403 | currentTasks?: string[]; 404 | completedTasks?: string[]; 405 | upcomingTasks?: string[]; 406 | milestones?: { title: string; description?: string }[]; 407 | }; 408 | }): Promise<{ success: boolean; message: string }> { 409 | try { 410 | let updatedFiles = []; 411 | 412 | // Check if we need to start a new session 413 | const startNewSession = await this._enhancedMemoryBank.shouldStartNewSession(); 414 | let sessionFile = await this._enhancedMemoryBank.getCurrentSessionFile(); 415 | 416 | if (startNewSession) { 417 | // Load context from previous day if needed 418 | await this._enhancedMemoryBank.loadContext(); 419 | 420 | // Create a new session file 421 | sessionFile = await this._enhancedMemoryBank.createSessionFile(); 422 | console.log(`Started new session: ${sessionFile}`); 423 | } else if (sessionFile) { 424 | // Update the end time of the current session 425 | await this._enhancedMemoryBank.updateSessionEndTime(sessionFile); 426 | console.log(`Updated session: ${sessionFile}`); 427 | } else { 428 | // No current session, create one 429 | sessionFile = await this._enhancedMemoryBank.createSessionFile(); 430 | console.log(`Created new session: ${sessionFile}`); 431 | } 432 | 433 | // Track statistics for this update 434 | const stats = await this._enhancedMemoryBank.trackStatistics(); 435 | console.log(`Statistics tracked: ${stats.timeSpent} spent, $${stats.estimatedCost} estimated cost`); 436 | 437 | if (updates.productContext) { 438 | const success = await this.updateProductContext(updates.productContext); 439 | if (success) updatedFiles.push('productContext.md'); 440 | } 441 | 442 | if (updates.activeContext) { 443 | const success = await this.updateActiveContext(updates.activeContext); 444 | if (success) { 445 | updatedFiles.push('activeContext.md'); 446 | // Also add the daily file 447 | const dateStr = this._enhancedMemoryBank.getDateString(); 448 | updatedFiles.push(`daily/activeContext-${dateStr}.md`); 449 | } 450 | } 451 | 452 | // Aggregate daily files into master files 453 | await this._enhancedMemoryBank.aggregateDailyFiles(); 454 | 455 | // Archive old files 456 | await this._enhancedMemoryBank.archiveOldFiles(); 457 | 458 | if (updatedFiles.length === 0) { 459 | return { 460 | success: false, 461 | message: 'No updates provided. Memory bank remains unchanged.' 462 | }; 463 | } 464 | 465 | // Update the last update timestamp 466 | await fs.writeFile(this.lastUpdatePath, new Date().toISOString()); 467 | 468 | return { 469 | success: true, 470 | message: `Memory bank updated successfully. Updated files: ${updatedFiles.join(', ')}` 471 | }; 472 | } catch (error) { 473 | console.error('Error handling UMB command:', error); 474 | return { 475 | success: false, 476 | message: `Failed to update memory bank: ${error instanceof Error ? error.message : String(error)}` 477 | }; 478 | } 479 | } 480 | } 481 | 482 | // Export a default instance for backward compatibility 483 | // This will use the default path: path.join(process.cwd(), 'memory-bank') 484 | export const memoryBank = new MemoryBank(); 485 | 486 | // Re-export functions from memory bank for backward compatibility 487 | export const getTimestamp = memoryBank.getTimestamp.bind(memoryBank); 488 | export const getDateString = memoryBank.getDateString.bind(memoryBank); 489 | export const createDailyFile = async () => memoryBank.createDailyFile(); 490 | export const getLatestDailyFile = async () => memoryBank.getLatestDailyFile(); 491 | export const shouldStartNewSession = async () => memoryBank.shouldStartNewSession(); 492 | export const createSessionFile = async () => memoryBank.createSessionFile(); 493 | export const getCurrentSessionFile = async () => memoryBank.getCurrentSessionFile(); 494 | export const updateSessionEndTime = async (filePath: string) => memoryBank.updateSessionEndTime(filePath); 495 | export const archiveOldFiles = async () => memoryBank.archiveOldFiles(); 496 | export const loadContext = async () => memoryBank.loadContext(); 497 | export const trackStatistics = async () => memoryBank.trackStatistics(); 498 | export const updateDailyActiveContext = async (update: any) => memoryBank.updateDailyActiveContext(update); 499 | export const aggregateDailyFiles = async () => memoryBank.aggregateDailyFiles(); 500 | export const reconstructMemoryBank = async () => memoryBank.reconstructMemoryBank(); -------------------------------------------------------------------------------- /src/roo-integration.ts: -------------------------------------------------------------------------------- 1 | import fs from 'fs-extra'; 2 | import path from 'path'; 3 | import { MemoryBank } from './memory-bank'; 4 | 5 | /** 6 | * Configuration options for the Roo-Code integration 7 | */ 8 | export interface RooIntegrationConfig { 9 | /** Base directory for the memory bank (defaults to ./memory-bank) */ 10 | memoryBankDir?: string; 11 | /** Directory where Roo rules will be stored (defaults to .roo/rules) */ 12 | rooRulesDir?: string; 13 | /** Automatically generate Roo rules from memory bank content */ 14 | autoGenerateRules?: boolean; 15 | /** Workspace root directory */ 16 | workspaceDir?: string; 17 | } 18 | 19 | /** 20 | * Roo-Code Memory Bank Integration 21 | * 22 | * This class provides integration between the Memory Bank system and Roo-Code. 23 | * It handles the initialization, configuration, and operations needed to make 24 | * the memory bank work seamlessly with Roo-Code. 25 | */ 26 | export class RooIntegration { 27 | private memoryBank: MemoryBank; 28 | private config: Required<RooIntegrationConfig>; 29 | private initialized: boolean = false; 30 | 31 | /** 32 | * Create a new Roo-Code integration instance 33 | * @param config Configuration options 34 | */ 35 | constructor(config: RooIntegrationConfig = {}) { 36 | // Set defaults for configuration 37 | this.config = { 38 | memoryBankDir: config.memoryBankDir || path.join(process.cwd(), 'memory-bank'), 39 | rooRulesDir: config.rooRulesDir || path.join(process.cwd(), '.roo', 'rules'), 40 | autoGenerateRules: config.autoGenerateRules !== undefined ? config.autoGenerateRules : true, 41 | workspaceDir: config.workspaceDir || process.cwd() 42 | }; 43 | 44 | // Initialize the memory bank 45 | this.memoryBank = new MemoryBank(this.config.memoryBankDir); 46 | } 47 | 48 | /** 49 | * Initialize the Roo-Code integration 50 | * @returns True if initialization was successful 51 | */ 52 | public async initialize(): Promise<boolean> { 53 | try { 54 | // Initialize the memory bank 55 | const memoryBankInitialized = await this.memoryBank.initialize(); 56 | 57 | if (memoryBankInitialized) { 58 | // Create Roo rules directory if it doesn't exist 59 | await fs.ensureDir(this.config.rooRulesDir); 60 | 61 | // Generate rules if auto-generation is enabled 62 | if (this.config.autoGenerateRules) { 63 | await this.generateRooRules(); 64 | } 65 | 66 | this.initialized = true; 67 | } 68 | 69 | return memoryBankInitialized; 70 | } catch (error) { 71 | console.error('Error initializing Roo-Code integration:', error); 72 | return false; 73 | } 74 | } 75 | 76 | /** 77 | * Generate Roo-Code custom instruction files from memory bank content 78 | */ 79 | public async generateRooRules(): Promise<boolean> { 80 | try { 81 | // Generate memory bank reference rule 82 | const memoryBankRule = `# Memory Bank Reference 83 | 84 | This file provides Roo with context from the memory bank located at: 85 | \`${this.config.memoryBankDir}\` 86 | 87 | ## Active Context 88 | The active context is the current focus of development and recent changes. 89 | Refer to this when working on the codebase to understand the current state. 90 | 91 | ## Product Context 92 | The product context provides an overview of the project, its goals, features, 93 | and architecture. Use this information to ensure your responses align with 94 | the project vision. 95 | 96 | ## System Patterns 97 | System patterns describe the architectural and design patterns used in the project. 98 | Follow these patterns when suggesting code changes. 99 | 100 | ## Decision Log 101 | The decision log contains important decisions and their rationale. 102 | Respect these decisions when making suggestions. 103 | `; 104 | 105 | // Write the rule file 106 | await fs.writeFile( 107 | path.join(this.config.rooRulesDir, '01-memory-bank-reference.md'), 108 | memoryBankRule 109 | ); 110 | 111 | // Generate active context rule from memory bank content 112 | await this.generateActiveContextRule(); 113 | 114 | return true; 115 | } catch (error) { 116 | console.error('Error generating Roo rules:', error); 117 | return false; 118 | } 119 | } 120 | 121 | /** 122 | * Generate active context rule from memory bank 123 | */ 124 | private async generateActiveContextRule(): Promise<boolean> { 125 | try { 126 | // Read the active context file 127 | const activeContextPath = path.join(this.config.memoryBankDir, 'activeContext.md'); 128 | 129 | if (await fs.pathExists(activeContextPath)) { 130 | const activeContext = await fs.readFile(activeContextPath, 'utf8'); 131 | 132 | // Extract sections 133 | const currentFocus = this.extractSection(activeContext, '## Current Focus'); 134 | const recentChanges = this.extractSection(activeContext, '## Recent Changes'); 135 | const openQuestions = this.extractSection(activeContext, '## Open Questions/Issues'); 136 | 137 | // Create active context rule 138 | const activeContextRule = `# Active Development Context 139 | 140 | ## Current Focus 141 | ${currentFocus || '- No current focus specified'} 142 | 143 | ## Recent Changes 144 | ${recentChanges || '- No recent changes recorded'} 145 | 146 | ## Open Questions/Issues 147 | ${openQuestions || '- No open questions'} 148 | 149 | --- 150 | This file is automatically generated from the memory bank. Do not edit directly. 151 | Last updated: ${new Date().toISOString()} 152 | `; 153 | 154 | // Write the rule file 155 | await fs.writeFile( 156 | path.join(this.config.rooRulesDir, '02-active-context.md'), 157 | activeContextRule 158 | ); 159 | 160 | return true; 161 | } 162 | 163 | return false; 164 | } catch (error) { 165 | console.error('Error generating active context rule:', error); 166 | return false; 167 | } 168 | } 169 | 170 | /** 171 | * Update Roo-Code rules with current memory bank content 172 | */ 173 | public async updateRooRules(): Promise<boolean> { 174 | try { 175 | if (!this.initialized) { 176 | await this.initialize(); 177 | } 178 | 179 | return await this.generateRooRules(); 180 | } catch (error) { 181 | console.error('Error updating Roo rules:', error); 182 | return false; 183 | } 184 | } 185 | 186 | /** 187 | * Sync memory bank changes to Roo-Code rules 188 | * This can be called after memory bank updates to ensure Roo has the latest context 189 | */ 190 | public async syncMemoryBankToRoo(): Promise<boolean> { 191 | try { 192 | return await this.updateRooRules(); 193 | } catch (error) { 194 | console.error('Error syncing memory bank to Roo:', error); 195 | return false; 196 | } 197 | } 198 | 199 | /** 200 | * Auto-detect and configure for a Roo-Code workspace 201 | * @param workspacePath Path to the workspace root (defaults to current directory) 202 | */ 203 | public static async autoConfigureForWorkspace( 204 | workspacePath: string = process.cwd() 205 | ): Promise<RooIntegration | null> { 206 | try { 207 | // Check if this is a Roo-Code workspace 208 | const isRooWorkspace = 209 | await fs.pathExists(path.join(workspacePath, '.roo')) || 210 | await fs.pathExists(path.join(workspacePath, '.roorules')); 211 | 212 | if (!isRooWorkspace) { 213 | console.log('This does not appear to be a Roo-Code workspace.'); 214 | return null; 215 | } 216 | 217 | // Create .roo/rules directory if it doesn't exist 218 | const rooRulesDir = path.join(workspacePath, '.roo', 'rules'); 219 | await fs.ensureDir(rooRulesDir); 220 | 221 | // Create memory bank directory 222 | const memoryBankDir = path.join(workspacePath, 'memory-bank'); 223 | 224 | // Configure the integration 225 | const config: RooIntegrationConfig = { 226 | workspaceDir: workspacePath, 227 | memoryBankDir, 228 | rooRulesDir, 229 | autoGenerateRules: true 230 | }; 231 | 232 | // Create and initialize the integration 233 | const integration = new RooIntegration(config); 234 | await integration.initialize(); 235 | 236 | return integration; 237 | } catch (error) { 238 | console.error('Error auto-configuring for workspace:', error); 239 | return null; 240 | } 241 | } 242 | 243 | /** 244 | * Extract a section from markdown content 245 | * @param content Markdown content 246 | * @param sectionHeader Section header to extract 247 | * @returns Extracted section content 248 | */ 249 | private extractSection(content: string, sectionHeader: string): string { 250 | const sectionRegex = new RegExp(`${sectionHeader}\\n([\\s\\S]*?)(?=\\n## |$)`); 251 | const match = content.match(sectionRegex); 252 | return match ? match[1].trim() : ''; 253 | } 254 | 255 | /** 256 | * Get the memory bank instance 257 | * @returns The memory bank instance 258 | */ 259 | public getMemoryBank(): MemoryBank { 260 | return this.memoryBank; 261 | } 262 | } 263 | 264 | // Export a default instance for easy use 265 | export const rooIntegration = new RooIntegration(); -------------------------------------------------------------------------------- /templates/roo-rules/01-memory-bank-reference.md: -------------------------------------------------------------------------------- 1 | # Memory Bank Reference 2 | 3 | This file provides Roo with context from the memory bank. The memory bank is a structured system for maintaining project context and history. 4 | 5 | ## Memory Bank Structure 6 | 7 | The memory bank contains the following key files: 8 | 9 | 1. **activeContext.md** - Current development focus and recent changes 10 | 2. **productContext.md** - Project overview, goals, and core features 11 | 3. **systemPatterns.md** - Architectural and design patterns 12 | 4. **decisionLog.md** - Important decisions and their rationale 13 | 5. **progress.md** - Current, completed, and upcoming tasks 14 | 15 | ## Usage Guidelines 16 | 17 | - When suggesting code changes, consider the active context and system patterns 18 | - Respect decisions documented in the decision log 19 | - Align responses with the project's goals and features 20 | - Maintain consistency with established architectural patterns 21 | 22 | ## Project Overview 23 | 24 | The project is focused on creating a memory bank system that helps maintain context and history for software development projects. It provides a structured way to document active context, product information, system patterns, and decisions. 25 | 26 | This information helps developers and AI assistants maintain awareness of the project's current state, goals, and architectural choices. 27 | 28 | --- 29 | This file is part of the memory bank integration with Roo-Code. -------------------------------------------------------------------------------- /templates/roo-rules/02-active-context.md: -------------------------------------------------------------------------------- 1 | # Active Development Context 2 | 3 | This file represents the current development context from the memory bank. It is automatically generated and updated when the memory bank is updated. 4 | 5 | ## Current Focus 6 | 7 | - Implementing memory bank integration with Roo-Code 8 | - Creating a seamless experience for Roo users 9 | 10 | ## Recent Changes 11 | 12 | - Added Roo-Code integration module 13 | - Created templates for Roo rules 14 | - Implemented auto-configuration for workspaces 15 | 16 | ## Open Questions/Issues 17 | 18 | - What is the best way to keep Roo rules updated when memory bank changes? 19 | - How can we provide a smooth setup experience for new users? 20 | - What additional context would be most useful for Roo? 21 | 22 | --- 23 | This file is automatically generated from the memory bank. Do not edit directly. 24 | Last updated: ${TIMESTAMP} -------------------------------------------------------------------------------- /templates/roo-rules/03-product-context.md: -------------------------------------------------------------------------------- 1 | # Product Context 2 | 3 | This file provides information about the product from the memory bank. It includes the project overview, goals, features, and architecture. 4 | 5 | ## Project Overview 6 | 7 | The Memory Bank system is designed to solve the problem of context loss during software development. It provides a structured way to document and track active context, product information, system patterns, and decisions. 8 | 9 | ## Goals and Objectives 10 | 11 | - Maintain persistent memory of development work 12 | - Provide structured documentation for projects 13 | - Track statistics like time spent and code changes 14 | - Integrate with development tools like Roo-Code 15 | - Reduce context switching costs for developers 16 | 17 | ## Core Features 18 | 19 | - Daily context files for tracking current work 20 | - Session tracking based on time gaps 21 | - Statistics tracking for development metrics 22 | - Git integration for tracking changes 23 | - Archiving system for organization 24 | - Command line interface for updates 25 | - Roo-Code integration for AI assistance 26 | 27 | ## Architecture Overview 28 | 29 | - TypeScript-based implementation 30 | - File-based storage using Markdown 31 | - Hierarchical organization (daily files, sessions, archives) 32 | - MemoryBank and EnhancedMemoryBank classes 33 | - Integration modules for external tools 34 | 35 | --- 36 | This file is automatically generated from the memory bank. Do not edit directly. 37 | Last updated: ${TIMESTAMP} -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2020", 4 | "module": "NodeNext", 5 | "moduleResolution": "NodeNext", 6 | "esModuleInterop": true, 7 | "strict": true, 8 | "declaration": true, 9 | "outDir": "./dist", 10 | "rootDir": "./src", 11 | "sourceMap": true, 12 | "resolveJsonModule": true, 13 | "forceConsistentCasingInFileNames": true, 14 | "skipLibCheck": true 15 | }, 16 | "include": ["src/**/*"], 17 | "exclude": ["node_modules", "dist", "**/*.test.ts"] 18 | } --------------------------------------------------------------------------------