systemlens 1.0.0
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/.env.example +5 -0
- package/LICENSE +21 -0
- package/README.md +160 -0
- package/bin/systemlens.js +127 -0
- package/package.json +73 -0
- package/server.js +106 -0
- package/src/analyzers/cpu.analyzer.js +124 -0
- package/src/analyzers/memory.analyzer.js +107 -0
- package/src/analyzers/process.analyzer.js +136 -0
- package/src/analyzers/spike.detector.js +135 -0
- package/src/classifiers/process.classifier.js +127 -0
- package/src/collectors/cpu.collector.js +48 -0
- package/src/collectors/disk.collector.js +41 -0
- package/src/collectors/memory.collector.js +41 -0
- package/src/collectors/process.collector.js +65 -0
- package/src/engines/ai.engine.js +105 -0
- package/src/engines/explanation.engine.js +348 -0
- package/src/engines/suggestion.engine.js +242 -0
- package/src/history/history.tracker.js +114 -0
- package/src/index.js +130 -0
- package/src/monitor/realtime.monitor.js +145 -0
- package/src/renderer/cli.renderer.js +318 -0
- package/src/utils/constants.js +80 -0
- package/src/utils/helpers.js +110 -0
- package/web/app.js +352 -0
- package/web/index.html +209 -0
- package/web/style.css +886 -0
package/.env.example
ADDED
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Neeraj — CreatedBYNJ5.0
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
# 🔬 SystemLens
|
|
2
|
+
|
|
3
|
+
**An intelligent system explainer that converts raw metrics into human-readable insights.**
|
|
4
|
+
|
|
5
|
+
> _CreatedBYNJ5.0_
|
|
6
|
+
|
|
7
|
+
SystemLens doesn't just show numbers — it tells you *why* your system is slow, *what* is responsible, and *what you should do about it*. It acts like a senior engineer explaining system behavior to a beginner.
|
|
8
|
+
|
|
9
|
+
**Works on Linux, macOS, and Windows.**
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## 🚀 Quick Start
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
# Run instantly with npx (no install needed)
|
|
17
|
+
npx systemlens
|
|
18
|
+
|
|
19
|
+
# Or install globally
|
|
20
|
+
npm install -g systemlens
|
|
21
|
+
systemlens
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
That's it. One command.
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
## 📋 Commands
|
|
29
|
+
|
|
30
|
+
| Command | Description |
|
|
31
|
+
|---------|-------------|
|
|
32
|
+
| `systemlens` | Start real-time CLI monitoring |
|
|
33
|
+
| `systemlens --once` | Single analysis snapshot |
|
|
34
|
+
| `systemlens --web` | Launch beautiful web dashboard |
|
|
35
|
+
| `systemlens --web --port 4000` | Web dashboard on custom port |
|
|
36
|
+
| `systemlens --help` | Show all options |
|
|
37
|
+
| `systemlens --version` | Print version |
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## ✨ Features
|
|
42
|
+
|
|
43
|
+
🧠 **Intelligent Explanations** — Not just "CPU is 85%", but "Chrome is consuming high CPU due to multiple open tabs"
|
|
44
|
+
🔗 **Cause & Effect Chains** — Links symptoms to causes with clear reasoning
|
|
45
|
+
🛠️ **Developer Mode** — Detects dev servers, hot-reload, and possible infinite loops
|
|
46
|
+
📈 **Pattern Detection** — Identifies sustained high usage, spikes, and trends over time
|
|
47
|
+
✅ **Actionable Suggestions** — Prioritized actions with impact ratings
|
|
48
|
+
🤖 **Optional AI Enhancement** — GPT-powered deeper insights (set `OPENAI_API_KEY`)
|
|
49
|
+
🌐 **Web Dashboard** — Real-time glassmorphic dark-mode UI
|
|
50
|
+
⚡ **CLI Mode** — Terminal-based monitoring with colored output and progress bars
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
## 🖥️ CLI Output
|
|
55
|
+
|
|
56
|
+
```
|
|
57
|
+
╔═══════════════════════════════════════════════════════════╗
|
|
58
|
+
║ 🔬 S Y S T E M L E N S ║
|
|
59
|
+
║ CreatedBYNJ5.0 ║
|
|
60
|
+
╚═══════════════════════════════════════════════════════════╝
|
|
61
|
+
|
|
62
|
+
🟡 SYSTEM STATUS: LIGHTLY LOADED
|
|
63
|
+
|
|
64
|
+
📊 System Summary
|
|
65
|
+
CPU ████░░░░░░░░░░░░░░░░ 15%
|
|
66
|
+
Memory ███████████████░░░░░ 62%
|
|
67
|
+
|
|
68
|
+
💬 What's Happening
|
|
69
|
+
Your system is moderately loaded...
|
|
70
|
+
|
|
71
|
+
🔗 Cause & Effect
|
|
72
|
+
🌐 Cause: Browser with ~4 open tabs using significant resources
|
|
73
|
+
Effect: Using 22% memory and 1% CPU
|
|
74
|
+
|
|
75
|
+
✅ Suggested Actions
|
|
76
|
+
🌐 1. Close unused browser tabs and disable heavy extensions
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
---
|
|
80
|
+
|
|
81
|
+
## 🌐 Web Dashboard
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
systemlens --web
|
|
85
|
+
# Open http://localhost:3777
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
A premium dark-mode real-time dashboard with:
|
|
89
|
+
- Live metric cards with sparkline charts
|
|
90
|
+
- Natural language explanation panel
|
|
91
|
+
- Cause & Effect visualization
|
|
92
|
+
- Process table with categories
|
|
93
|
+
- Developer insights panel
|
|
94
|
+
- Prioritized suggestions
|
|
95
|
+
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
## 🤖 AI Enhancement (Optional)
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
# Set your OpenAI API key
|
|
102
|
+
export OPENAI_API_KEY=sk-your-key-here
|
|
103
|
+
|
|
104
|
+
# Run with AI insights
|
|
105
|
+
systemlens
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
AI adds:
|
|
109
|
+
- Deeper contextual insights
|
|
110
|
+
- Performance predictions
|
|
111
|
+
- Power-user tips
|
|
112
|
+
|
|
113
|
+
---
|
|
114
|
+
|
|
115
|
+
## 🏗️ Architecture
|
|
116
|
+
|
|
117
|
+
```
|
|
118
|
+
Collection → Classification → Analysis → Explanation → Suggestion → Rendering
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
| Layer | Purpose |
|
|
122
|
+
|-------|---------|
|
|
123
|
+
| **4 Collectors** | CPU, Memory, Disk, Process data |
|
|
124
|
+
| **Classifier** | Categorizes processes (Browser/Dev/System/Media) |
|
|
125
|
+
| **4 Analyzers** | Detects issues, spikes, core imbalance, swap pressure |
|
|
126
|
+
| **Explanation Engine** | Converts analysis → human-language narratives |
|
|
127
|
+
| **Suggestion Engine** | Prioritized, actionable recommendations |
|
|
128
|
+
| **Spike Detector** | Time-series pattern detection |
|
|
129
|
+
| **AI Engine** | Optional GPT-powered enhancement |
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
133
|
+
## 🔧 Configuration
|
|
134
|
+
|
|
135
|
+
All thresholds are configurable in `src/utils/constants.js`:
|
|
136
|
+
|
|
137
|
+
| Threshold | Default | Description |
|
|
138
|
+
|-----------|---------|-------------|
|
|
139
|
+
| `CPU_HIGH` | 80% | Triggers critical alert |
|
|
140
|
+
| `MEMORY_HIGH` | 80% | Triggers critical alert |
|
|
141
|
+
| `SPIKE_THRESHOLD` | 20% | Jump size for spike detection |
|
|
142
|
+
| `MONITORING_INTERVAL` | 3000ms | Data refresh rate |
|
|
143
|
+
|
|
144
|
+
---
|
|
145
|
+
|
|
146
|
+
## 🖥️ Platform Support
|
|
147
|
+
|
|
148
|
+
| Platform | Status |
|
|
149
|
+
|----------|--------|
|
|
150
|
+
| Linux | ✅ Fully supported |
|
|
151
|
+
| macOS | ✅ Fully supported |
|
|
152
|
+
| Windows | ✅ Fully supported |
|
|
153
|
+
|
|
154
|
+
Requires **Node.js 18+** — uses ES modules and top-level await.
|
|
155
|
+
|
|
156
|
+
---
|
|
157
|
+
|
|
158
|
+
## 📄 License
|
|
159
|
+
|
|
160
|
+
MIT — CreatedBYNJ5.0
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// ─── SystemLens CLI ──────────────────────────────────────────────
|
|
4
|
+
// Single entry point for all SystemLens modes.
|
|
5
|
+
// Works on Windows, macOS, and Linux.
|
|
6
|
+
//
|
|
7
|
+
// Usage:
|
|
8
|
+
// systemlens → Start real-time CLI monitoring
|
|
9
|
+
// systemlens --once → Run a single analysis
|
|
10
|
+
// systemlens --web → Start web dashboard on localhost:3777
|
|
11
|
+
// systemlens --help → Show help
|
|
12
|
+
|
|
13
|
+
import chalk from 'chalk';
|
|
14
|
+
import { fileURLToPath } from 'url';
|
|
15
|
+
import { dirname, join } from 'path';
|
|
16
|
+
import { readFileSync } from 'fs';
|
|
17
|
+
|
|
18
|
+
// ─── Resolve package root (cross-platform) ──────────────────────
|
|
19
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
20
|
+
const __dirname = dirname(__filename);
|
|
21
|
+
const PKG_ROOT = join(__dirname, '..');
|
|
22
|
+
|
|
23
|
+
// ─── Read version from package.json ─────────────────────────────
|
|
24
|
+
let version = '1.0.0';
|
|
25
|
+
try {
|
|
26
|
+
const pkg = JSON.parse(readFileSync(join(PKG_ROOT, 'package.json'), 'utf-8'));
|
|
27
|
+
version = pkg.version;
|
|
28
|
+
} catch { }
|
|
29
|
+
|
|
30
|
+
// ─── Parse args ─────────────────────────────────────────────────
|
|
31
|
+
const args = process.argv.slice(2);
|
|
32
|
+
const hasFlag = (flag) => args.includes(flag);
|
|
33
|
+
|
|
34
|
+
// ─── Version ────────────────────────────────────────────────────
|
|
35
|
+
if (hasFlag('--version') || hasFlag('-v')) {
|
|
36
|
+
console.log(`systemlens v${version}`);
|
|
37
|
+
process.exit(0);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// ─── Help ───────────────────────────────────────────────────────
|
|
41
|
+
if (hasFlag('--help') || hasFlag('-h')) {
|
|
42
|
+
console.log(chalk.cyan.bold(`
|
|
43
|
+
🔬 SystemLens v${version} — Intelligent System Explainer
|
|
44
|
+
CreatedBYNJ5.0
|
|
45
|
+
|
|
46
|
+
Usage:
|
|
47
|
+
systemlens Start real-time CLI monitoring
|
|
48
|
+
systemlens --once Run a single analysis snapshot
|
|
49
|
+
systemlens --web Start web dashboard (localhost:3777)
|
|
50
|
+
systemlens --version Show version
|
|
51
|
+
systemlens --help Show this help message
|
|
52
|
+
|
|
53
|
+
Options:
|
|
54
|
+
--once, -o Single analysis (no continuous monitoring)
|
|
55
|
+
--web, -w Launch web dashboard with real-time updates
|
|
56
|
+
--port <number> Port for web dashboard (default: 3777)
|
|
57
|
+
--version, -v Print version
|
|
58
|
+
--help, -h Show help
|
|
59
|
+
|
|
60
|
+
Environment:
|
|
61
|
+
OPENAI_API_KEY Optional: Enable AI-enhanced explanations
|
|
62
|
+
|
|
63
|
+
Examples:
|
|
64
|
+
npx systemlens # Monitor your system
|
|
65
|
+
npx systemlens --once # Quick snapshot
|
|
66
|
+
npx systemlens --web # Beautiful web dashboard
|
|
67
|
+
npx systemlens --web --port 4000 # Custom port
|
|
68
|
+
OPENAI_API_KEY=sk-... npx systemlens # With AI insights
|
|
69
|
+
|
|
70
|
+
Platforms:
|
|
71
|
+
✅ Linux ✅ macOS ✅ Windows
|
|
72
|
+
`));
|
|
73
|
+
process.exit(0);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// ─── Splash ─────────────────────────────────────────────────────
|
|
77
|
+
function showSplash() {
|
|
78
|
+
console.log(chalk.cyan(`
|
|
79
|
+
███████╗██╗ ██╗███████╗████████╗███████╗███╗ ███╗
|
|
80
|
+
██╔════╝╚██╗ ██╔╝██╔════╝╚══██╔══╝██╔════╝████╗ ████║
|
|
81
|
+
███████╗ ╚████╔╝ ███████╗ ██║ █████╗ ██╔████╔██║
|
|
82
|
+
╚════██║ ╚██╔╝ ╚════██║ ██║ ██╔══╝ ██║╚██╔╝██║
|
|
83
|
+
███████║ ██║ ███████║ ██║ ███████╗██║ ╚═╝ ██║
|
|
84
|
+
╚══════╝ ╚═╝ ╚══════╝ ╚═╝ ╚══════╝╚═╝ ╚═╝
|
|
85
|
+
|
|
86
|
+
██╗ ███████╗███╗ ██╗███████╗
|
|
87
|
+
██║ ██╔════╝████╗ ██║██╔════╝
|
|
88
|
+
██║ █████╗ ██╔██╗ ██║███████╗
|
|
89
|
+
██║ ██╔══╝ ██║╚██╗██║╚════██║
|
|
90
|
+
███████╗███████╗██║ ╚████║███████║
|
|
91
|
+
╚══════╝╚══════╝╚═╝ ╚═══╝╚══════╝
|
|
92
|
+
`));
|
|
93
|
+
console.log(chalk.bold.hex('#8B5CF6')(` CreatedBYNJ5.0 • v${version}\n`));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// ─── Web Mode ───────────────────────────────────────────────────
|
|
97
|
+
if (hasFlag('--web') || hasFlag('-w')) {
|
|
98
|
+
showSplash();
|
|
99
|
+
|
|
100
|
+
// Parse custom port
|
|
101
|
+
const portIdx = args.indexOf('--port');
|
|
102
|
+
const customPort = portIdx !== -1 && args[portIdx + 1]
|
|
103
|
+
? parseInt(args[portIdx + 1], 10)
|
|
104
|
+
: null;
|
|
105
|
+
|
|
106
|
+
if (customPort) {
|
|
107
|
+
process.env.PORT = String(customPort);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Import and run the web server
|
|
111
|
+
await import(join(PKG_ROOT, 'server.js'));
|
|
112
|
+
|
|
113
|
+
} else {
|
|
114
|
+
// ─── CLI Mode ───────────────────────────────────────────────
|
|
115
|
+
showSplash();
|
|
116
|
+
console.log(chalk.dim(' Initializing system analysis...\n'));
|
|
117
|
+
|
|
118
|
+
// Dynamic import to avoid loading everything upfront
|
|
119
|
+
const { SystemLens } = await import(join(PKG_ROOT, 'src', 'index.js'));
|
|
120
|
+
const lens = new SystemLens();
|
|
121
|
+
|
|
122
|
+
if (hasFlag('--once') || hasFlag('-o')) {
|
|
123
|
+
await lens.runOnce();
|
|
124
|
+
} else {
|
|
125
|
+
await lens.startMonitoring();
|
|
126
|
+
}
|
|
127
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "systemlens",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "An intelligent system explainer that converts raw metrics into human-readable insights. Not a monitor — a system mentor.",
|
|
5
|
+
"main": "src/index.js",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"systemlens": "bin/systemlens.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"bin/",
|
|
12
|
+
"src/",
|
|
13
|
+
"web/",
|
|
14
|
+
"server.js",
|
|
15
|
+
".env.example",
|
|
16
|
+
"README.md",
|
|
17
|
+
"LICENSE"
|
|
18
|
+
],
|
|
19
|
+
"scripts": {
|
|
20
|
+
"start": "node bin/systemlens.js",
|
|
21
|
+
"cli": "node bin/systemlens.js",
|
|
22
|
+
"once": "node bin/systemlens.js --once",
|
|
23
|
+
"web": "node bin/systemlens.js --web"
|
|
24
|
+
},
|
|
25
|
+
"keywords": [
|
|
26
|
+
"system",
|
|
27
|
+
"monitor",
|
|
28
|
+
"explainer",
|
|
29
|
+
"diagnostics",
|
|
30
|
+
"insights",
|
|
31
|
+
"cpu",
|
|
32
|
+
"memory",
|
|
33
|
+
"process",
|
|
34
|
+
"system-info",
|
|
35
|
+
"system-monitor",
|
|
36
|
+
"cli",
|
|
37
|
+
"dashboard",
|
|
38
|
+
"devtools",
|
|
39
|
+
"performance",
|
|
40
|
+
"linux",
|
|
41
|
+
"macos",
|
|
42
|
+
"windows",
|
|
43
|
+
"cross-platform"
|
|
44
|
+
],
|
|
45
|
+
"author": "Neeraj — CreatedBYNJ5.0",
|
|
46
|
+
"license": "MIT",
|
|
47
|
+
"repository": {
|
|
48
|
+
"type": "git",
|
|
49
|
+
"url": "https://github.com/neeraj/systemlens"
|
|
50
|
+
},
|
|
51
|
+
"homepage": "https://github.com/neeraj/systemlens#readme",
|
|
52
|
+
"bugs": {
|
|
53
|
+
"url": "https://github.com/neeraj/systemlens/issues"
|
|
54
|
+
},
|
|
55
|
+
"engines": {
|
|
56
|
+
"node": ">=18.0.0"
|
|
57
|
+
},
|
|
58
|
+
"os": [
|
|
59
|
+
"linux",
|
|
60
|
+
"darwin",
|
|
61
|
+
"win32"
|
|
62
|
+
],
|
|
63
|
+
"dependencies": {
|
|
64
|
+
"chalk": "^5.6.2",
|
|
65
|
+
"cli-table3": "^0.6.5",
|
|
66
|
+
"dotenv": "^17.3.1",
|
|
67
|
+
"express": "^5.2.1",
|
|
68
|
+
"openai": "^6.33.0",
|
|
69
|
+
"pidusage": "^4.0.1",
|
|
70
|
+
"systeminformation": "^5.31.5",
|
|
71
|
+
"ws": "^8.20.0"
|
|
72
|
+
}
|
|
73
|
+
}
|
package/server.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// ─── SystemLens Web Server ───────────────────────────────────────
|
|
2
|
+
// Express + WebSocket server that streams system analysis to the browser
|
|
3
|
+
import express from 'express';
|
|
4
|
+
import { WebSocketServer } from 'ws';
|
|
5
|
+
import { createServer } from 'http';
|
|
6
|
+
import { fileURLToPath } from 'url';
|
|
7
|
+
import { dirname, join, resolve } from 'path';
|
|
8
|
+
import { SystemLens } from './src/index.js';
|
|
9
|
+
|
|
10
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
11
|
+
const __dirname = dirname(__filename);
|
|
12
|
+
|
|
13
|
+
const app = express();
|
|
14
|
+
const server = createServer(app);
|
|
15
|
+
const wss = new WebSocketServer({ server });
|
|
16
|
+
|
|
17
|
+
// Serve static files from /web
|
|
18
|
+
app.use(express.static(join(__dirname, 'web')));
|
|
19
|
+
|
|
20
|
+
// Initialize SystemLens
|
|
21
|
+
const lens = new SystemLens();
|
|
22
|
+
|
|
23
|
+
// ─── REST API ────────────────────────────────────────────────────
|
|
24
|
+
app.get('/api/analyze', async (req, res) => {
|
|
25
|
+
try {
|
|
26
|
+
const result = await lens.analyze();
|
|
27
|
+
res.json(result);
|
|
28
|
+
} catch (error) {
|
|
29
|
+
res.status(500).json({ error: error.message });
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
app.get('/api/history', (req, res) => {
|
|
34
|
+
res.json(lens.historyTracker.getSummary());
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
// ─── WebSocket Real-Time Stream ──────────────────────────────────
|
|
38
|
+
const BROADCAST_INTERVAL = 3000;
|
|
39
|
+
let broadcastTimer = null;
|
|
40
|
+
|
|
41
|
+
wss.on('connection', (ws) => {
|
|
42
|
+
console.log('🔌 Client connected');
|
|
43
|
+
|
|
44
|
+
// Send initial data immediately
|
|
45
|
+
sendAnalysis(ws);
|
|
46
|
+
|
|
47
|
+
ws.on('close', () => {
|
|
48
|
+
console.log('🔌 Client disconnected');
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
ws.on('error', (err) => {
|
|
52
|
+
console.error('WebSocket error:', err.message);
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
async function sendAnalysis(ws) {
|
|
57
|
+
try {
|
|
58
|
+
const result = await lens.analyze();
|
|
59
|
+
if (ws.readyState === 1) { // OPEN
|
|
60
|
+
ws.send(JSON.stringify(result));
|
|
61
|
+
}
|
|
62
|
+
} catch (error) {
|
|
63
|
+
console.error('Analysis error:', error.message);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function broadcastToAll() {
|
|
68
|
+
if (wss.clients.size === 0) return;
|
|
69
|
+
|
|
70
|
+
lens.analyze().then(result => {
|
|
71
|
+
const data = JSON.stringify(result);
|
|
72
|
+
wss.clients.forEach(client => {
|
|
73
|
+
if (client.readyState === 1) {
|
|
74
|
+
client.send(data);
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
}).catch(err => {
|
|
78
|
+
console.error('Broadcast error:', err.message);
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Start broadcasting when we have clients
|
|
83
|
+
broadcastTimer = setInterval(broadcastToAll, BROADCAST_INTERVAL);
|
|
84
|
+
|
|
85
|
+
// ─── Start Server ────────────────────────────────────────────────
|
|
86
|
+
const PORT = process.env.PORT || 3777;
|
|
87
|
+
|
|
88
|
+
server.listen(PORT, () => {
|
|
89
|
+
console.log(`
|
|
90
|
+
🔬 SystemLens Web Dashboard
|
|
91
|
+
───────────────────────────
|
|
92
|
+
🌐 Dashboard: http://localhost:${PORT}
|
|
93
|
+
📡 API: http://localhost:${PORT}/api/analyze
|
|
94
|
+
🔌 WebSocket: ws://localhost:${PORT}
|
|
95
|
+
|
|
96
|
+
Press Ctrl+C to stop
|
|
97
|
+
`);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
// Graceful shutdown
|
|
101
|
+
process.on('SIGINT', () => {
|
|
102
|
+
clearInterval(broadcastTimer);
|
|
103
|
+
wss.close();
|
|
104
|
+
server.close();
|
|
105
|
+
process.exit(0);
|
|
106
|
+
});
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// ─── CPU Analyzer ────────────────────────────────────────────────
|
|
2
|
+
// Analyzes CPU data and produces structured insights
|
|
3
|
+
import { THRESHOLDS, SEVERITY } from '../utils/constants.js';
|
|
4
|
+
|
|
5
|
+
export class CpuAnalyzer {
|
|
6
|
+
/**
|
|
7
|
+
* Analyze CPU data and return insights
|
|
8
|
+
* @param {Object} cpuData - From CpuCollector
|
|
9
|
+
* @param {Object|null} previousData - Previous snapshot for comparison
|
|
10
|
+
* @returns {Object} Analysis results
|
|
11
|
+
*/
|
|
12
|
+
analyze(cpuData, previousData = null) {
|
|
13
|
+
const load = cpuData.load.overall;
|
|
14
|
+
const issues = [];
|
|
15
|
+
const insights = [];
|
|
16
|
+
|
|
17
|
+
// ── Severity classification ──
|
|
18
|
+
let severity;
|
|
19
|
+
if (load >= THRESHOLDS.CPU_HIGH) {
|
|
20
|
+
severity = SEVERITY.CRITICAL;
|
|
21
|
+
issues.push({
|
|
22
|
+
type: 'cpu_high',
|
|
23
|
+
severity: 'critical',
|
|
24
|
+
message: `CPU usage is critically high at ${load}%`,
|
|
25
|
+
value: load,
|
|
26
|
+
});
|
|
27
|
+
} else if (load >= THRESHOLDS.CPU_WARNING) {
|
|
28
|
+
severity = SEVERITY.WARNING;
|
|
29
|
+
issues.push({
|
|
30
|
+
type: 'cpu_warning',
|
|
31
|
+
severity: 'warning',
|
|
32
|
+
message: `CPU usage is elevated at ${load}%`,
|
|
33
|
+
value: load,
|
|
34
|
+
});
|
|
35
|
+
} else if (load >= THRESHOLDS.CPU_MODERATE) {
|
|
36
|
+
severity = SEVERITY.INFO;
|
|
37
|
+
insights.push({
|
|
38
|
+
type: 'cpu_moderate',
|
|
39
|
+
message: `CPU load is moderate at ${load}%`,
|
|
40
|
+
value: load,
|
|
41
|
+
});
|
|
42
|
+
} else {
|
|
43
|
+
severity = SEVERITY.OK;
|
|
44
|
+
insights.push({
|
|
45
|
+
type: 'cpu_ok',
|
|
46
|
+
message: `CPU usage is healthy at ${load}%`,
|
|
47
|
+
value: load,
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// ── Core imbalance detection ──
|
|
52
|
+
const coreLoads = cpuData.load.perCore.map(c => c.load);
|
|
53
|
+
const maxCore = Math.max(...coreLoads);
|
|
54
|
+
const minCore = Math.min(...coreLoads);
|
|
55
|
+
const coreSpread = maxCore - minCore;
|
|
56
|
+
|
|
57
|
+
if (coreSpread > 50) {
|
|
58
|
+
issues.push({
|
|
59
|
+
type: 'core_imbalance',
|
|
60
|
+
severity: 'warning',
|
|
61
|
+
message: `Core load imbalance detected (spread: ${coreSpread.toFixed(0)}%). One core is heavily loaded while others are idle — possible single-threaded bottleneck.`,
|
|
62
|
+
value: coreSpread,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// ── System vs User load ──
|
|
67
|
+
const systemLoadRatio = cpuData.load.system / (load || 1);
|
|
68
|
+
if (systemLoadRatio > 0.5 && load > THRESHOLDS.CPU_MODERATE) {
|
|
69
|
+
insights.push({
|
|
70
|
+
type: 'system_heavy',
|
|
71
|
+
message: `System (kernel) tasks are consuming ${cpuData.load.system}% of CPU — this may indicate heavy I/O, driver activity, or system maintenance.`,
|
|
72
|
+
value: cpuData.load.system,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// ── Spike detection (compare with previous) ──
|
|
77
|
+
if (previousData) {
|
|
78
|
+
const prevLoad = previousData.load.overall;
|
|
79
|
+
const delta = load - prevLoad;
|
|
80
|
+
|
|
81
|
+
if (delta >= THRESHOLDS.SPIKE_THRESHOLD) {
|
|
82
|
+
issues.push({
|
|
83
|
+
type: 'cpu_spike',
|
|
84
|
+
severity: 'warning',
|
|
85
|
+
message: `CPU usage spiked by ${delta.toFixed(1)}% (from ${prevLoad}% to ${load}%)`,
|
|
86
|
+
value: delta,
|
|
87
|
+
previousValue: prevLoad,
|
|
88
|
+
});
|
|
89
|
+
} else if (delta <= -THRESHOLDS.SPIKE_THRESHOLD) {
|
|
90
|
+
insights.push({
|
|
91
|
+
type: 'cpu_drop',
|
|
92
|
+
message: `CPU usage dropped by ${Math.abs(delta).toFixed(1)}% — load is settling down`,
|
|
93
|
+
value: delta,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// ── Temperature insight ──
|
|
99
|
+
if (cpuData.temperature?.main && cpuData.temperature.main > 80) {
|
|
100
|
+
issues.push({
|
|
101
|
+
type: 'cpu_temp_high',
|
|
102
|
+
severity: 'warning',
|
|
103
|
+
message: `CPU temperature is high at ${cpuData.temperature.main}°C — may cause thermal throttling`,
|
|
104
|
+
value: cpuData.temperature.main,
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
return {
|
|
109
|
+
overall: load,
|
|
110
|
+
severity,
|
|
111
|
+
issues,
|
|
112
|
+
insights,
|
|
113
|
+
details: {
|
|
114
|
+
user: cpuData.load.user,
|
|
115
|
+
system: cpuData.load.system,
|
|
116
|
+
idle: cpuData.load.idle,
|
|
117
|
+
coreSpread,
|
|
118
|
+
maxCoreLoad: maxCore,
|
|
119
|
+
minCoreLoad: minCore,
|
|
120
|
+
temperature: cpuData.temperature?.main || null,
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
}
|