Skip to content

Commit 1491123

Browse files
committed
feat(ProcessManager): add Bun availability check and improve PID file validation
- Implemented a method to check if Bun is available in the system PATH. - Updated the startWithBun method to return an error if Bun is not found. - Enhanced PID file parsing to validate required fields and their types. - Cleaned up stale PID files if the process is no longer alive. fix(SettingsRoutes): clear port cache after updating settings - Added a call to clearPortCache after writing updated settings to ensure the application uses the latest configuration.
1 parent 9f1745b commit 1491123

27 files changed

+246
-315
lines changed

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ npx mintlify dev
109109
- **[Architecture Evolution](https://docs.claude-mem.ai/architecture-evolution)** - The journey from v3 to v5
110110
- **[Hooks Architecture](https://docs.claude-mem.ai/hooks-architecture)** - How Claude-Mem uses lifecycle hooks
111111
- **[Hooks Reference](https://docs.claude-mem.ai/architecture/hooks)** - 7 hook scripts explained
112-
- **[Worker Service](https://docs.claude-mem.ai/architecture/worker-service)** - HTTP API & PM2 management
112+
- **[Worker Service](https://docs.claude-mem.ai/architecture/worker-service)** - HTTP API & Bun management
113113
- **[Database](https://docs.claude-mem.ai/architecture/database)** - SQLite schema & FTS5 search
114114
- **[Search Architecture](https://docs.claude-mem.ai/architecture/search-architecture)** - Hybrid search with Chroma vector database
115115

@@ -149,7 +149,7 @@ npx mintlify dev
149149

150150
1. **5 Lifecycle Hooks** - SessionStart, UserPromptSubmit, PostToolUse, Stop, SessionEnd (6 hook scripts)
151151
2. **Smart Install** - Cached dependency checker (pre-hook script, not a lifecycle hook)
152-
3. **Worker Service** - HTTP API on port 37777 with web viewer UI and 10 search endpoints, managed by PM2
152+
3. **Worker Service** - HTTP API on port 37777 with web viewer UI and 10 search endpoints, managed by Bun
153153
4. **SQLite Database** - Stores sessions, observations, summaries with FTS5 full-text search
154154
5. **mem-search Skill** - Natural language queries with progressive disclosure (~2,250 token savings vs MCP)
155155
6. **Chroma Vector Database** - Hybrid semantic + keyword search for intelligent context retrieval
@@ -263,7 +263,7 @@ See [CHANGELOG.md](CHANGELOG.md) for complete version history.
263263

264264
- **Node.js**: 18.0.0 or higher
265265
- **Claude Code**: Latest version with plugin support
266-
- **PM2**: Process manager (bundled - no global install required)
266+
- **Bun**: JavaScript runtime and process manager (auto-installed if missing)
267267
- **SQLite 3**: For persistent storage (bundled)
268268

269269
---

docs/context/SMART_INSTALL_ANALYSIS.md

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ isWorkerHealthy() → fetch /health endpoint
3434
└─ [UNHEALTHY] → startWorker()
3535
3636
├─ [Windows] → PowerShell Start-Process (hidden window)
37-
└─ [Unix] → PM2 start ecosystem.config.cjs
37+
└─ [Unix] → Bun start ecosystem.config.cjs
3838
3939
Wait for health check (15 retries × 1000ms)
4040
@@ -116,7 +116,7 @@ spawnSync('powershell.exe', [
116116
**Issues:**
117117
1. **PowerShell Dependency:** Assumes PowerShell is available and in PATH
118118
2. **Command Injection Risk:** Worker script path inserted directly into command string without escaping
119-
3. **Process Monitoring:** Windows approach launches detached process with no PM2 monitoring - harder to debug/restart
119+
3. **Process Monitoring:** Windows approach launches detached process with no Bun monitoring - harder to debug/restart
120120
4. **Health Check Timeout:** Comment says "Windows needs longer timeouts" but timeout is same for all platforms (500ms)
121121

122122
**Edge Cases:**
@@ -127,16 +127,16 @@ spawnSync('powershell.exe', [
127127

128128
**Unix Implementation:**
129129
```typescript
130-
const localPm2Base = path.join(MARKETPLACE_ROOT, 'node_modules', '.bin', 'pm2');
131-
const pm2Command = existsSync(localPm2Base) ? localPm2Base : 'pm2';
130+
const localBunBase = path.join(MARKETPLACE_ROOT, 'node_modules', '.bin', 'bun');
131+
const bunCommand = existsSync(localBunBase) ? localBunBase : 'bun';
132132
```
133133

134134
**Issues:**
135-
1. **PM2 Dependency:** Falls back to global pm2 if local not found, but doesn't verify it exists
136-
2. **Silent Failure:** If PM2 not installed globally, spawnSync will fail with cryptic ENOENT error
135+
1. **Bun Dependency:** Falls back to global bun if local not found, but doesn't verify it exists
136+
2. **Silent Failure:** If Bun not installed globally, spawnSync will fail with cryptic ENOENT error
137137

138138
**Recommendation:**
139-
- Add pm2 existence check before spawn
139+
- Add bun existence check before spawn
140140
- Implement consistent process monitoring across platforms
141141
- Add path escaping for Windows command construction
142142
- Actually implement longer timeout for Windows if needed
@@ -414,7 +414,7 @@ if (!existsSync(join(commandsDir, 'save.md'))) {
414414
### Missing Edge Case Handling ⚠️
415415

416416
1. **curl Failure:** context-hook.ts has no error handling for curl failures
417-
2. **PM2 Not Installed:** worker-utils.ts assumes pm2 exists globally
417+
2. **Bun Not Installed:** worker-utils.ts assumes bun exists globally
418418
3. **PowerShell Restrictions:** worker-utils.ts doesn't check execution policy
419419
4. **Concurrent Worker Starts:** No locking to prevent multiple hooks from starting worker simultaneously
420420
5. **Port Already In Use:** No detection or recovery if worker port is taken
@@ -442,7 +442,7 @@ if (!existsSync(join(commandsDir, 'save.md'))) {
442442

443443
### Medium Priority 🟡
444444

445-
4. **Verify PM2 availability** before attempting to use it
445+
4. **Verify Bun availability** before attempting to use it
446446
- Check existence before spawn
447447
- Provide clear error message if missing
448448

@@ -494,7 +494,7 @@ if (!existsSync(join(commandsDir, 'save.md'))) {
494494

495495
1. **Cold Start:** First run with no existing data
496496
2. **Corrupt Settings:** Invalid JSON in settings.json
497-
3. **Missing Dependencies:** No PM2, no git, no curl
497+
3. **Missing Dependencies:** No Bun, no git, no curl
498498
4. **Port Conflicts:** Worker port already in use
499499
5. **Rapid Hook Invocations:** Multiple hooks trying to start worker simultaneously
500500
6. **Permission Issues:** Read-only filesystem, restricted execution
@@ -525,7 +525,7 @@ if (!existsSync(join(commandsDir, 'save.md'))) {
525525

526526
- Duplicate health endpoints
527527
- curl dependency when fetch available
528-
- PM2 dependency on Unix but not Windows (inconsistent monitoring)
528+
- Bun dependency on Unix but not Windows (inconsistent monitoring)
529529
- First-run detection using node_modules existence
530530
- Hardcoded timeout values
531531

docs/context/platform-integration-guide.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -68,9 +68,9 @@ CLAUDE_MEM_PYTHON_VERSION=3.13 # Python version for chroma-mcp
6868
```bash
6969
npm run build # Compile TypeScript (hooks + worker)
7070
npm run sync-marketplace # Copy to ~/.claude/plugins
71-
npm run worker:restart # Restart PM2 worker
71+
npm run worker:restart # Restart Bun worker
7272
npm run worker:logs # View worker logs
73-
pm2 list # Check worker status
73+
bun list # Check worker status
7474
```
7575

7676
---
@@ -918,8 +918,8 @@ esbuild.build({
918918
npm run watch
919919

920920
# Terminal 2: Check worker status
921-
pm2 list
922-
pm2 logs claude-mem-worker
921+
bun list
922+
bun logs claude-mem-worker
923923

924924
# Terminal 3: Test API manually
925925
curl http://localhost:37777/api/health
@@ -1020,7 +1020,7 @@ describe('Worker Integration', () => {
10201020
### Manual Testing Checklist
10211021

10221022
**Phase 1: Connection & Health**
1023-
- [ ] Worker starts successfully (`pm2 list`)
1023+
- [ ] Worker starts successfully (`bun list`)
10241024
- [ ] Health endpoint responds (`curl http://localhost:37777/api/health`)
10251025
- [ ] SSE stream connects (`curl http://localhost:37777/stream`)
10261026

docs/public/architecture-evolution.mdx

Lines changed: 8 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -46,22 +46,15 @@ const ThemeProvider = ({ children }) => {
4646

4747
**Why It Matters**: Users working in different lighting conditions can now customize the viewer for comfort.
4848

49-
### v5.1.1: PM2 Windows Fix (November 2025)
49+
### v5.1.1: Worker Startup Fix (November 2025) - Now Deprecated
5050

51-
**The Problem**: PM2 startup failed on Windows with ENOENT error
51+
**Note**: This section describes a historical PM2-based approach that has been replaced with Bun in later versions.
5252

53-
**Root Cause**:
54-
```typescript
55-
// ❌ Failed on Windows - PM2 not in PATH
56-
execSync('pm2 start ecosystem.config.cjs');
57-
```
53+
**The Problem**: Worker startup failed on Windows with ENOENT error when using PM2
5854

59-
**The Fix**:
60-
```typescript
61-
// ✅ Use full path to PM2 binary
62-
const PM2_PATH = join(PLUGIN_ROOT, 'node_modules', '.bin', 'pm2');
63-
execSync(`"${PM2_PATH}" start "${ECOSYSTEM_CONFIG}"`);
64-
```
55+
**Historical Solution**: Used full path to PM2 binary instead of relying on PATH
56+
57+
**Current Approach**: The project now uses Bun for process management, which provides better cross-platform compatibility and eliminates these PATH-related issues.
6558

6659
**Impact**: Cross-platform compatibility restored, Windows users can now use claude-mem without issues.
6760

@@ -203,7 +196,7 @@ async function ensureWorkerHealthy() {
203196
**Key Fixes**:
204197
- Fixed race conditions in observation queue processing
205198
- Improved error handling in SDK worker
206-
- Better cleanup of stale PM2 processes
199+
- Better cleanup of stale worker processes
207200
- Enhanced logging for debugging
208201
209202
### v5.0.0: Hybrid Search Architecture (October 2025)
@@ -520,7 +513,7 @@ const response = query({
520513
521514
**Key change from v3:**
522515
- ✅ Stores raw prompts for search
523-
- ✅ Auto-starts PM2 worker
516+
- ✅ Auto-starts worker service
524517
</Tab>
525518
526519
<Tab title="PostToolUse">

docs/public/architecture/hooks.mdx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -446,7 +446,7 @@ sequenceDiagram
446446
else Tool allowed
447447
SaveHook->>SaveHook: Strip privacy tags from input/response
448448
449-
SaveHook->>SaveHook: Ensure worker running<br/>(PM2 health check)
449+
SaveHook->>SaveHook: Ensure worker running<br/>(health check)
450450
451451
SaveHook->>Worker: POST /api/sessions/observations<br/>{ claudeSessionId, tool_name, tool_input, tool_response, cwd }<br/>(fire-and-forget, 2s timeout)
452452
@@ -906,7 +906,7 @@ For developers implementing this pattern on other platforms:
906906
907907
### Worker Service
908908
- [ ] HTTP server on configurable port (default 37777)
909-
- [ ] PM2 or equivalent process management
909+
- [ ] Bun runtime for process management
910910
- [ ] 3 core services: SessionManager, SDKAgent, DatabaseManager
911911
912912
### Hook Implementation

docs/public/architecture/overview.mdx

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ Claude-Mem operates as a Claude Code plugin with five core components:
2929
| **UI Framework** | React + TypeScript |
3030
| **AI SDK** | @anthropic-ai/claude-agent-sdk |
3131
| **Build Tool** | esbuild (bundles TypeScript) |
32-
| **Process Manager** | PM2 |
32+
| **Process Manager** | Bun |
3333
| **Testing** | Node.js built-in test runner |
3434

3535
## Data Flow
@@ -70,7 +70,7 @@ User Query → mem-search Skill Invoked → HTTP API → SessionSearch Service
7070
7171
┌─────────────────────────────────────────────────────────────────┐
7272
│ 1. Session Starts → Context Hook Fires │
73-
│ Starts PM2 worker if needed, injects context from previous │
73+
│ Starts Bun worker if needed, injects context from previous │
7474
│ sessions (configurable observation count) │
7575
└─────────────────────────────────────────────────────────────────┘
7676
@@ -177,13 +177,13 @@ claude-mem/
177177
178178
├── tests/ # Test suite
179179
├── docs/ # Documentation
180-
└── ecosystem.config.cjs # PM2 configuration
180+
└── ecosystem.config.cjs # Process configuration (deprecated)
181181
```
182182

183183
## Component Details
184184

185185
### 1. Plugin Hooks (6 Hooks)
186-
- **context-hook.js** - SessionStart: Starts PM2 worker, injects context
186+
- **context-hook.js** - SessionStart: Starts Bun worker, injects context
187187
- **user-message-hook.js** - UserMessage: Debugging hook
188188
- **new-hook.js** - UserPromptSubmit: Creates session, saves prompt
189189
- **save-hook.js** - PostToolUse: Captures tool executions
@@ -200,7 +200,7 @@ Express.js HTTP server on port 37777 (configurable) with:
200200
- 8 viewer UI HTTP/SSE endpoints
201201
- Async observation processing via Claude Agent SDK
202202
- Real-time updates via Server-Sent Events
203-
- Auto-managed by PM2 process manager
203+
- Auto-managed by Bun
204204

205205
See [Worker Service](/architecture/worker-service) for HTTP API and endpoints.
206206

docs/public/architecture/search-architecture.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -415,7 +415,7 @@ Claude translates to appropriate API call.
415415
If searches fail, check worker service:
416416

417417
```bash
418-
pm2 list # Check status
418+
npm run worker:status # Check status
419419
npm run worker:restart # Restart worker
420420
npm run worker:logs # View logs
421421
```

docs/public/configuration.mdx

Lines changed: 3 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -181,33 +181,9 @@ Claude-Mem supports switching between stable and beta versions via the web viewe
181181

182182
See [Beta Features](beta-features) for details on what's available in beta.
183183

184-
## PM2 Configuration
185-
186-
Worker service is managed by PM2 via `ecosystem.config.cjs`:
187-
188-
```javascript
189-
module.exports = {
190-
apps: [{
191-
name: 'claude-mem-worker',
192-
script: './plugin/scripts/worker-service.cjs',
193-
instances: 1,
194-
autorestart: true,
195-
watch: false,
196-
max_memory_restart: '1G',
197-
env: {
198-
NODE_ENV: 'production',
199-
FORCE_COLOR: '1'
200-
}
201-
}]
202-
};
203-
```
204-
205-
### PM2 Settings
184+
## Worker Service Management
206185

207-
- **instances**: 1 (single instance)
208-
- **autorestart**: true (auto-restart on crash)
209-
- **watch**: false (no file watching)
210-
- **max_memory_restart**: 1G (restart if memory exceeds 1GB)
186+
Worker service is managed by Bun as a background process. The worker auto-starts on first session and runs continuously in the background.
211187

212188
## Context Injection Configuration
213189

@@ -402,13 +378,7 @@ Recommended values:
402378

403379
### Worker Memory Limit
404380

405-
Modify PM2 memory limit in `ecosystem.config.cjs`:
406-
407-
```javascript
408-
{
409-
max_memory_restart: '2G' // Increase if needed
410-
}
411-
```
381+
The worker service is managed by Bun and will automatically restart if it encounters issues. Memory usage is typically low (~100-200MB).
412382

413383
### Logging Verbosity
414384

docs/public/development.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -650,7 +650,7 @@ rm -rf plugin/scripts/*.js plugin/scripts/*.cjs
650650

651651
1. Kill existing process:
652652
```bash
653-
pm2 delete claude-mem-worker
653+
npm run worker:stop
654654
```
655655

656656
2. Check port:

0 commit comments

Comments
 (0)