claude-brain 0.30.0 → 0.30.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/VERSION +1 -1
- package/package.json +2 -1
- package/skills/persistent-memory/SKILL.md +148 -0
- package/skills/persistent-memory/references/tool-reference.md +90 -0
- package/src/cli/commands/serve.ts +45 -8
- package/src/server/auto-updater.ts +3 -28
- package/src/server/pid-manager.ts +29 -4
- package/src/utils/index.ts +4 -0
- package/src/utils/kill-port.ts +53 -0
package/VERSION
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
0.30.
|
|
1
|
+
0.30.1
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "claude-brain",
|
|
3
|
-
"version": "0.30.
|
|
3
|
+
"version": "0.30.1",
|
|
4
4
|
"description": "Local development assistant bridging Obsidian vaults with Claude Code via MCP",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "src/index.ts",
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
"src/hooks/claude-code-mastery.md",
|
|
14
14
|
"scripts/postinstall.mjs",
|
|
15
15
|
"packs/",
|
|
16
|
+
"skills/",
|
|
16
17
|
"assets/",
|
|
17
18
|
"package.json",
|
|
18
19
|
"tsconfig.json",
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: persistent-memory
|
|
3
|
+
description: Persistent memory management for Claude sessions using the brain MCP tool. Use when starting a work session, making architectural decisions, learning from mistakes, ending a session, or when user says "remember this", "what do I know about", "recall", "brain", or "session summary". Also use when searching code symbols, files, or dependencies with search_code.
|
|
4
|
+
license: MIT
|
|
5
|
+
metadata:
|
|
6
|
+
author: claude-brain
|
|
7
|
+
version: 1.0.0
|
|
8
|
+
mcp-server: claude-brain
|
|
9
|
+
category: productivity
|
|
10
|
+
tags: [memory, persistence, decisions, context, code-intelligence]
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
# Persistent Memory
|
|
14
|
+
|
|
15
|
+
Manage persistent memory across Claude sessions using the `brain` and `search_code` MCP tools. Memory persists between conversations — decisions, lessons, and context survive session boundaries.
|
|
16
|
+
|
|
17
|
+
## Critical Rules
|
|
18
|
+
|
|
19
|
+
- The `brain` tool auto-classifies intent. Most of the time, just pass a natural language message — don't force an action unless you have a reason.
|
|
20
|
+
- Do NOT store file paths, "read file X" events, or progress like "ran tests" — these are too granular and captured automatically by hooks.
|
|
21
|
+
- DO store the WHY — reasoning behind decisions, user preferences, lessons learned from debugging.
|
|
22
|
+
- Use the `project` parameter to scope memories to the right project. If omitted, it's auto-detected from the message.
|
|
23
|
+
|
|
24
|
+
## Session Workflow
|
|
25
|
+
|
|
26
|
+
### Step 1: Session Start — Recall Context
|
|
27
|
+
|
|
28
|
+
At the beginning of significant work, recall what you know:
|
|
29
|
+
|
|
30
|
+
```
|
|
31
|
+
brain("What do I know about this project?")
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
This returns past decisions, preferences, patterns, and lessons. Use it to avoid re-asking questions the user already answered in previous sessions.
|
|
35
|
+
|
|
36
|
+
Expected output: A summary of stored memories with relevance scores.
|
|
37
|
+
|
|
38
|
+
### Step 2: During Work — Store Decisions and Lessons
|
|
39
|
+
|
|
40
|
+
Store when you encounter something worth remembering:
|
|
41
|
+
|
|
42
|
+
**Decisions:**
|
|
43
|
+
```
|
|
44
|
+
brain("Decided to use JWT over sessions because the app is stateless")
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
**Mistakes and fixes:**
|
|
48
|
+
```
|
|
49
|
+
brain("The bug was caused by missing CORS credentials — fixed with credentials: include")
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
**User preferences:**
|
|
53
|
+
```
|
|
54
|
+
brain("User prefers explicit error messages over generic 500s")
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
**Architecture changes:**
|
|
58
|
+
```
|
|
59
|
+
brain("Changed database from MySQL to Postgres for better JSON support")
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### Step 3: Session End — Summarize
|
|
63
|
+
|
|
64
|
+
Before finishing significant work, store a 2-3 sentence summary:
|
|
65
|
+
|
|
66
|
+
```
|
|
67
|
+
brain("Session summary: Built auth flow for expense tracker. Chose JWT for stateless architecture. Hit CORS issue on /api/login, fixed with credentials: include.")
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Using search_code
|
|
71
|
+
|
|
72
|
+
The `search_code` tool searches indexed code — faster than grep for large projects.
|
|
73
|
+
|
|
74
|
+
**Search symbols (functions, classes, types):**
|
|
75
|
+
```
|
|
76
|
+
search_code({ query: "handleAuth", project: "my-app" })
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
**Search files by name:**
|
|
80
|
+
```
|
|
81
|
+
search_code({ query: "config", project: "my-app", type: "files" })
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
**Show dependencies of a file:**
|
|
85
|
+
```
|
|
86
|
+
search_code({ query: "deps", project: "my-app", type: "dependencies", file_path: "src/auth.ts" })
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
If search returns no results, the project may need indexing. Run `claude-brain reindex` first.
|
|
90
|
+
|
|
91
|
+
## Advanced Patterns
|
|
92
|
+
|
|
93
|
+
### Updating Past Memories
|
|
94
|
+
When a previous decision changes:
|
|
95
|
+
```
|
|
96
|
+
brain({ message: "Changed my mind — use Postgres instead of MySQL", action: "update" })
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### Getting Full Details
|
|
100
|
+
Search returns compact summaries. For the full stored content:
|
|
101
|
+
```
|
|
102
|
+
brain("details 42")
|
|
103
|
+
```
|
|
104
|
+
where 42 is the memory ID from a previous search result.
|
|
105
|
+
|
|
106
|
+
### Deleting Outdated Memories
|
|
107
|
+
```
|
|
108
|
+
brain({ message: "delete memory about MySQL choice", action: "delete" })
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
### Scoping to Projects
|
|
112
|
+
Always pass the project name for multi-project work:
|
|
113
|
+
```
|
|
114
|
+
brain({ message: "Chose Tailwind for styling", project: "expense-tracker" })
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## What to Store vs. Skip
|
|
118
|
+
|
|
119
|
+
### Store These
|
|
120
|
+
- Architectural decisions and their reasoning
|
|
121
|
+
- User preferences for tools, style, workflow
|
|
122
|
+
- Solutions to hard debugging problems
|
|
123
|
+
- Patterns confirmed across multiple sessions
|
|
124
|
+
- Key file paths and project structure insights
|
|
125
|
+
|
|
126
|
+
### Skip These
|
|
127
|
+
- File read/write events (captured by hooks)
|
|
128
|
+
- "Ran tests" / "built successfully" (too granular)
|
|
129
|
+
- Anything already in CLAUDE.md or the codebase
|
|
130
|
+
- Speculative conclusions from reading a single file
|
|
131
|
+
|
|
132
|
+
## Troubleshooting
|
|
133
|
+
|
|
134
|
+
### brain tool returns "no relevant memories"
|
|
135
|
+
**Cause:** No memories stored yet, or query doesn't match stored content.
|
|
136
|
+
**Solution:** Try broader phrasing. Use `brain("list all memories for project X")` to see what's stored.
|
|
137
|
+
|
|
138
|
+
### search_code returns empty results
|
|
139
|
+
**Cause:** Project not indexed.
|
|
140
|
+
**Solution:** Run `claude-brain reindex` in terminal, then retry.
|
|
141
|
+
|
|
142
|
+
### Memories scoped to wrong project
|
|
143
|
+
**Cause:** Project name not specified or auto-detected incorrectly.
|
|
144
|
+
**Solution:** Always pass `project` parameter explicitly for multi-project work.
|
|
145
|
+
|
|
146
|
+
### brain tool seems slow
|
|
147
|
+
**Cause:** Large memory database or complex semantic search.
|
|
148
|
+
**Solution:** Use more specific queries. Scope to a project to narrow search space.
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# Tool Reference
|
|
2
|
+
|
|
3
|
+
Complete parameter reference for the brain and search_code MCP tools.
|
|
4
|
+
|
|
5
|
+
## brain
|
|
6
|
+
|
|
7
|
+
Your persistent memory. Tell it decisions, ask it questions, or update/delete past notes.
|
|
8
|
+
|
|
9
|
+
### Parameters
|
|
10
|
+
|
|
11
|
+
| Parameter | Type | Required | Description |
|
|
12
|
+
|-----------|------|----------|-------------|
|
|
13
|
+
| `message` | string | Yes | What you are doing, decided, learned, or need. Natural language. |
|
|
14
|
+
| `project` | string | No | Project name to scope memories (e.g., "my-app"). Auto-detected if omitted. |
|
|
15
|
+
| `action` | enum | No | Force action: `auto`, `store`, `recall`, `update`, `delete`. Default: `auto`. |
|
|
16
|
+
|
|
17
|
+
### Intent Classification
|
|
18
|
+
|
|
19
|
+
When `action` is `auto` (default), the tool classifies your message into one of these intents:
|
|
20
|
+
|
|
21
|
+
- **session_start** — "What do I know about X?" / beginning of session
|
|
22
|
+
- **decision_made** — "Decided to use X because Y"
|
|
23
|
+
- **store_this** — "Remember that..." / storing information
|
|
24
|
+
- **pattern_found** — "I noticed a pattern where..."
|
|
25
|
+
- **mistake_learned** — "The bug was X, fixed by Y"
|
|
26
|
+
- **question** — "What was the reason for X?"
|
|
27
|
+
- **context_needed** — Requesting stored context
|
|
28
|
+
- **update_memory** — Changing a previous memory
|
|
29
|
+
- **delete_memory** — Removing a memory
|
|
30
|
+
- **detail_request** — "details {ID}" for full content
|
|
31
|
+
- **list_all** — "list all memories" / "show everything"
|
|
32
|
+
- **timeline** — "show history" / "what happened when"
|
|
33
|
+
- **comparison** — "compare X vs Y decisions"
|
|
34
|
+
- **exploration** — Open-ended exploration of stored knowledge
|
|
35
|
+
- **progress_update** — "Completed X, next steps Y"
|
|
36
|
+
|
|
37
|
+
### Response Format
|
|
38
|
+
|
|
39
|
+
```json
|
|
40
|
+
{
|
|
41
|
+
"action": "stored | retrieved | updated | deleted | none",
|
|
42
|
+
"summary": "Brief description of what happened",
|
|
43
|
+
"content": "Full response with details",
|
|
44
|
+
"relevantItems": 5
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## search_code
|
|
49
|
+
|
|
50
|
+
Search indexed code for symbols, files, or dependencies. Faster than grep for indexed projects.
|
|
51
|
+
|
|
52
|
+
### Parameters
|
|
53
|
+
|
|
54
|
+
| Parameter | Type | Required | Default | Description |
|
|
55
|
+
|-----------|------|----------|---------|-------------|
|
|
56
|
+
| `query` | string | Yes | — | Symbol name, file name, or search term |
|
|
57
|
+
| `project` | string | Yes | — | Project name (usually directory name) |
|
|
58
|
+
| `type` | enum | No | `symbols` | `symbols`, `files`, or `dependencies` |
|
|
59
|
+
| `file_path` | string | No* | — | Required when type is `dependencies` |
|
|
60
|
+
| `limit` | number | No | 20 | Max results (1-100) |
|
|
61
|
+
|
|
62
|
+
### Search Types
|
|
63
|
+
|
|
64
|
+
**symbols** (default): Search functions, classes, types, interfaces by name.
|
|
65
|
+
```
|
|
66
|
+
search_code({ query: "UserService", project: "my-app" })
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
**files**: Search for files by name pattern.
|
|
70
|
+
```
|
|
71
|
+
search_code({ query: "middleware", project: "my-app", type: "files" })
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
**dependencies**: Show imports and imported-by for a specific file.
|
|
75
|
+
```
|
|
76
|
+
search_code({ query: "deps", project: "my-app", type: "dependencies", file_path: "src/auth/service.ts" })
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### Supported File Types
|
|
80
|
+
|
|
81
|
+
`.ts .tsx .js .jsx .mjs .cjs .py .go .rs .vue .html .css .json .yaml .yml`
|
|
82
|
+
|
|
83
|
+
### Indexing
|
|
84
|
+
|
|
85
|
+
If search returns no results, the project needs indexing:
|
|
86
|
+
```bash
|
|
87
|
+
claude-brain reindex
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
This parses the codebase using tree-sitter and stores symbols in SQLite for fast lookup.
|
|
@@ -47,14 +47,21 @@ export async function runServe() {
|
|
|
47
47
|
return runAsDaemon(httpOnly, pidManager)
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
-
/** Check if the daemon at the given port is responsive and
|
|
50
|
+
/** Check if the daemon at the given port is responsive, initialized, and can serve MCP tools */
|
|
51
51
|
async function isDaemonHealthy(port: number): Promise<boolean> {
|
|
52
52
|
try {
|
|
53
|
-
const
|
|
53
|
+
const healthRes = await fetch(`http://localhost:${port}/api/health`, {
|
|
54
54
|
signal: AbortSignal.timeout(2000),
|
|
55
55
|
})
|
|
56
|
-
const
|
|
57
|
-
|
|
56
|
+
const healthJson = await healthRes.json() as any
|
|
57
|
+
if (healthJson.success !== true || healthJson.initialized !== true) return false
|
|
58
|
+
|
|
59
|
+
// Verify MCP proxy endpoints actually work (old versions return 404)
|
|
60
|
+
const toolsRes = await fetch(`http://localhost:${port}/api/mcp/list-tools`, {
|
|
61
|
+
signal: AbortSignal.timeout(2000),
|
|
62
|
+
})
|
|
63
|
+
const toolsJson = await toolsRes.json() as any
|
|
64
|
+
return toolsJson.success === true && Array.isArray(toolsJson.data?.tools)
|
|
58
65
|
} catch {
|
|
59
66
|
return false
|
|
60
67
|
}
|
|
@@ -93,7 +100,9 @@ async function runAsProxy(daemonPort: number) {
|
|
|
93
100
|
|
|
94
101
|
process.on('SIGTERM', () => stopProxy('SIGTERM'))
|
|
95
102
|
process.on('SIGINT', () => stopProxy('SIGINT'))
|
|
96
|
-
process.
|
|
103
|
+
if (process.platform !== 'win32') {
|
|
104
|
+
process.on('SIGHUP', () => stopProxy('SIGHUP'))
|
|
105
|
+
}
|
|
97
106
|
|
|
98
107
|
await proxy.start()
|
|
99
108
|
mainLogger.info('MCP proxy ready — forwarding to daemon')
|
|
@@ -382,15 +391,43 @@ async function runAsDaemon(httpOnly: boolean, pidManager: ServerPidManager) {
|
|
|
382
391
|
} catch (error) {
|
|
383
392
|
mainLogger.debug({ error }, 'No hook queue to drain')
|
|
384
393
|
}
|
|
385
|
-
} catch (error) {
|
|
386
|
-
|
|
394
|
+
} catch (error: any) {
|
|
395
|
+
// EADDRINUSE: kill the stale process and retry once
|
|
396
|
+
if (error?.code === 'EADDRINUSE' || String(error).includes('EADDRINUSE')) {
|
|
397
|
+
mainLogger.warn({ port: config.port }, 'Port in use — killing stale process and retrying')
|
|
398
|
+
try {
|
|
399
|
+
const { killProcessOnPort } = await import('@/utils/kill-port')
|
|
400
|
+
const killed = killProcessOnPort(config.port)
|
|
401
|
+
if (killed.length > 0) {
|
|
402
|
+
mainLogger.info({ killed }, 'Killed stale process(es) on port')
|
|
403
|
+
}
|
|
404
|
+
await new Promise(r => setTimeout(r, 1000))
|
|
405
|
+
await httpServer.start()
|
|
406
|
+
mainLogger.info({ port: config.port }, 'HTTP API server started (after recovery)')
|
|
407
|
+
|
|
408
|
+
// Drain hook queue on retry success too
|
|
409
|
+
try {
|
|
410
|
+
const { drainQueue } = await import('@/hooks/queue')
|
|
411
|
+
const drained = await drainQueue(config.port)
|
|
412
|
+
if (drained > 0) {
|
|
413
|
+
mainLogger.info({ drained }, 'Drained hook queue')
|
|
414
|
+
}
|
|
415
|
+
} catch {}
|
|
416
|
+
} catch (retryError) {
|
|
417
|
+
mainLogger.error({ error: retryError }, 'Failed to start HTTP API server after recovery — MCP stdio still works')
|
|
418
|
+
}
|
|
419
|
+
} else {
|
|
420
|
+
mainLogger.error({ error }, 'Failed to start HTTP API server')
|
|
421
|
+
}
|
|
387
422
|
}
|
|
388
423
|
}, 2000)
|
|
389
424
|
|
|
390
425
|
// ── Signal handlers ──────────────────────────────────────
|
|
391
426
|
process.on('SIGTERM', () => shutdown('SIGTERM'))
|
|
392
427
|
process.on('SIGINT', () => shutdown('SIGINT'))
|
|
393
|
-
process.
|
|
428
|
+
if (process.platform !== 'win32') {
|
|
429
|
+
process.on('SIGHUP', () => shutdown('SIGHUP'))
|
|
430
|
+
}
|
|
394
431
|
|
|
395
432
|
if (httpOnly) {
|
|
396
433
|
// HTTP-only daemon mode: no MCP stdio. Use idle watchdog instead of infinite keepAlive.
|
|
@@ -8,6 +8,7 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync, unlinkSync } from '
|
|
|
8
8
|
import { join, dirname, resolve } from 'node:path'
|
|
9
9
|
import { homedir, platform } from 'node:os'
|
|
10
10
|
import { fileURLToPath } from 'node:url'
|
|
11
|
+
import { killProcessOnPort } from '@/utils/kill-port'
|
|
11
12
|
|
|
12
13
|
const __filename = fileURLToPath(import.meta.url)
|
|
13
14
|
const __dirname = dirname(__filename)
|
|
@@ -223,34 +224,8 @@ export class AutoUpdater {
|
|
|
223
224
|
// No matching processes — that's fine
|
|
224
225
|
}
|
|
225
226
|
|
|
226
|
-
// Kill by port 3000
|
|
227
|
-
|
|
228
|
-
if (isWindows) {
|
|
229
|
-
const result = execSync(`netstat -ano | findstr :3000 | findstr LISTENING`, {
|
|
230
|
-
encoding: 'utf-8', stdio: 'pipe', timeout: 5000,
|
|
231
|
-
})
|
|
232
|
-
const pids = new Set(
|
|
233
|
-
result.split('\n')
|
|
234
|
-
.map(line => line.trim().split(/\s+/).pop())
|
|
235
|
-
.filter(p => p && Number(p) !== myPid)
|
|
236
|
-
)
|
|
237
|
-
for (const pid of pids) {
|
|
238
|
-
try { execSync(`taskkill /F /PID ${pid}`, { stdio: 'pipe', timeout: 5000 }) } catch {}
|
|
239
|
-
}
|
|
240
|
-
} else {
|
|
241
|
-
const raw = execSync(`lsof -ti :3000`, {
|
|
242
|
-
encoding: 'utf-8', stdio: 'pipe', timeout: 5000,
|
|
243
|
-
}).trim()
|
|
244
|
-
if (raw) {
|
|
245
|
-
const pids = raw.split('\n').filter(p => p && Number(p) !== myPid)
|
|
246
|
-
for (const pid of pids) {
|
|
247
|
-
try { process.kill(Number(pid), 'SIGKILL') } catch {}
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
} catch {
|
|
252
|
-
// No process on port — that's fine
|
|
253
|
-
}
|
|
227
|
+
// Kill by port 3000 using shared utility
|
|
228
|
+
killProcessOnPort(3000, myPid)
|
|
254
229
|
|
|
255
230
|
// Clean up stale PID files
|
|
256
231
|
const pidPath = join(this.dataDir, 'server.pid')
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
import { existsSync, readFileSync, writeFileSync, unlinkSync } from 'node:fs'
|
|
8
|
+
import { execSync } from 'node:child_process'
|
|
8
9
|
import { join } from 'node:path'
|
|
9
10
|
import { getHomePaths } from '@/config/home'
|
|
10
11
|
|
|
@@ -65,10 +66,32 @@ export class ServerPidManager {
|
|
|
65
66
|
}
|
|
66
67
|
|
|
67
68
|
// Signal 0 tests if process exists without killing it
|
|
68
|
-
|
|
69
|
+
try {
|
|
70
|
+
process.kill(pid, 0)
|
|
71
|
+
} catch (signalError: any) {
|
|
72
|
+
// On Windows, process.kill(pid, 0) can throw unexpected errors
|
|
73
|
+
// Fall back to tasklist to verify the PID exists
|
|
74
|
+
if (process.platform === 'win32' && signalError?.code !== 'ESRCH') {
|
|
75
|
+
try {
|
|
76
|
+
const result = execSync(`tasklist /FI "PID eq ${pid}" /NH`, {
|
|
77
|
+
encoding: 'utf-8', stdio: 'pipe', timeout: 3000,
|
|
78
|
+
})
|
|
79
|
+
if (!result.includes(String(pid))) {
|
|
80
|
+
this.cleanup()
|
|
81
|
+
return null
|
|
82
|
+
}
|
|
83
|
+
} catch {
|
|
84
|
+
this.cleanup()
|
|
85
|
+
return null
|
|
86
|
+
}
|
|
87
|
+
} else {
|
|
88
|
+
this.cleanup()
|
|
89
|
+
return null
|
|
90
|
+
}
|
|
91
|
+
}
|
|
69
92
|
return { pid, port }
|
|
70
93
|
} catch {
|
|
71
|
-
//
|
|
94
|
+
// Invalid file format, clean up stale PID file
|
|
72
95
|
this.cleanup()
|
|
73
96
|
return null
|
|
74
97
|
}
|
|
@@ -97,7 +120,7 @@ export class ServerPidManager {
|
|
|
97
120
|
}
|
|
98
121
|
}
|
|
99
122
|
|
|
100
|
-
/** Register cleanup handlers on SIGINT, SIGTERM, SIGHUP, and process exit. */
|
|
123
|
+
/** Register cleanup handlers on SIGINT, SIGTERM, SIGHUP (non-Windows), and process exit. */
|
|
101
124
|
registerCleanupHandlers(): void {
|
|
102
125
|
const doCleanup = () => {
|
|
103
126
|
this.cleanup()
|
|
@@ -106,6 +129,8 @@ export class ServerPidManager {
|
|
|
106
129
|
process.on('exit', doCleanup)
|
|
107
130
|
process.on('SIGINT', doCleanup)
|
|
108
131
|
process.on('SIGTERM', doCleanup)
|
|
109
|
-
process.
|
|
132
|
+
if (process.platform !== 'win32') {
|
|
133
|
+
process.on('SIGHUP', doCleanup)
|
|
134
|
+
}
|
|
110
135
|
}
|
|
111
136
|
}
|
package/src/utils/index.ts
CHANGED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cross-platform utility to kill the process holding a specific port.
|
|
3
|
+
* Used by serve.ts (EADDRINUSE recovery) and auto-updater.ts (ghost cleanup).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { execSync } from 'node:child_process'
|
|
7
|
+
|
|
8
|
+
const isWindows = process.platform === 'win32'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Kill the process listening on the given port.
|
|
12
|
+
* Skips the current process (myPid) to avoid self-termination.
|
|
13
|
+
* Returns the PIDs that were killed, or an empty array if none found.
|
|
14
|
+
*/
|
|
15
|
+
export function killProcessOnPort(port: number, myPid: number = process.pid): number[] {
|
|
16
|
+
const killed: number[] = []
|
|
17
|
+
|
|
18
|
+
try {
|
|
19
|
+
if (isWindows) {
|
|
20
|
+
const result = execSync(`netstat -ano | findstr :${port} | findstr LISTENING`, {
|
|
21
|
+
encoding: 'utf-8', stdio: 'pipe', timeout: 5000,
|
|
22
|
+
})
|
|
23
|
+
const pids = new Set(
|
|
24
|
+
result.split('\n')
|
|
25
|
+
.map(line => line.trim().split(/\s+/).pop())
|
|
26
|
+
.filter((p): p is string => !!p && Number(p) !== myPid && !isNaN(Number(p)))
|
|
27
|
+
)
|
|
28
|
+
for (const pid of pids) {
|
|
29
|
+
try {
|
|
30
|
+
execSync(`taskkill /F /PID ${pid}`, { stdio: 'pipe', timeout: 5000 })
|
|
31
|
+
killed.push(Number(pid))
|
|
32
|
+
} catch {}
|
|
33
|
+
}
|
|
34
|
+
} else {
|
|
35
|
+
const raw = execSync(`lsof -ti :${port}`, {
|
|
36
|
+
encoding: 'utf-8', stdio: 'pipe', timeout: 5000,
|
|
37
|
+
}).trim()
|
|
38
|
+
if (raw) {
|
|
39
|
+
const pids = raw.split('\n').filter(p => p && Number(p) !== myPid)
|
|
40
|
+
for (const pid of pids) {
|
|
41
|
+
try {
|
|
42
|
+
process.kill(Number(pid), 'SIGKILL')
|
|
43
|
+
killed.push(Number(pid))
|
|
44
|
+
} catch {}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
} catch {
|
|
49
|
+
// No process on port — that's fine
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return killed
|
|
53
|
+
}
|