wolverine-ai 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.
Files changed (79) hide show
  1. package/PLATFORM.md +442 -0
  2. package/README.md +475 -0
  3. package/SERVER_BEST_PRACTICES.md +62 -0
  4. package/TELEMETRY.md +108 -0
  5. package/bin/wolverine.js +95 -0
  6. package/examples/01-basic-typo.js +31 -0
  7. package/examples/02-multi-file/routes/users.js +15 -0
  8. package/examples/02-multi-file/server.js +25 -0
  9. package/examples/03-syntax-error.js +23 -0
  10. package/examples/04-secret-leak.js +14 -0
  11. package/examples/05-expired-key.js +27 -0
  12. package/examples/06-json-config/config.json +13 -0
  13. package/examples/06-json-config/server.js +28 -0
  14. package/examples/07-rate-limit-loop.js +11 -0
  15. package/examples/08-sandbox-escape.js +20 -0
  16. package/examples/buggy-server.js +39 -0
  17. package/examples/demos/01-basic-typo/index.js +20 -0
  18. package/examples/demos/01-basic-typo/routes/api.js +13 -0
  19. package/examples/demos/01-basic-typo/routes/health.js +4 -0
  20. package/examples/demos/02-multi-file/index.js +24 -0
  21. package/examples/demos/02-multi-file/routes/api.js +13 -0
  22. package/examples/demos/02-multi-file/routes/health.js +4 -0
  23. package/examples/demos/03-syntax-error/index.js +18 -0
  24. package/examples/demos/04-secret-leak/index.js +16 -0
  25. package/examples/demos/05-expired-key/index.js +21 -0
  26. package/examples/demos/06-json-config/config.json +9 -0
  27. package/examples/demos/06-json-config/index.js +20 -0
  28. package/examples/demos/07-null-crash/index.js +16 -0
  29. package/examples/run-demo.js +110 -0
  30. package/package.json +67 -0
  31. package/server/config/settings.json +62 -0
  32. package/server/index.js +33 -0
  33. package/server/routes/api.js +12 -0
  34. package/server/routes/health.js +16 -0
  35. package/server/routes/time.js +12 -0
  36. package/src/agent/agent-engine.js +727 -0
  37. package/src/agent/goal-loop.js +140 -0
  38. package/src/agent/research-agent.js +120 -0
  39. package/src/agent/sub-agents.js +176 -0
  40. package/src/backup/backup-manager.js +321 -0
  41. package/src/brain/brain.js +315 -0
  42. package/src/brain/embedder.js +131 -0
  43. package/src/brain/function-map.js +263 -0
  44. package/src/brain/vector-store.js +267 -0
  45. package/src/core/ai-client.js +387 -0
  46. package/src/core/cluster-manager.js +144 -0
  47. package/src/core/config.js +89 -0
  48. package/src/core/error-parser.js +87 -0
  49. package/src/core/health-monitor.js +129 -0
  50. package/src/core/models.js +132 -0
  51. package/src/core/patcher.js +55 -0
  52. package/src/core/runner.js +464 -0
  53. package/src/core/system-info.js +141 -0
  54. package/src/core/verifier.js +146 -0
  55. package/src/core/wolverine.js +290 -0
  56. package/src/dashboard/server.js +1332 -0
  57. package/src/index.js +94 -0
  58. package/src/logger/event-logger.js +237 -0
  59. package/src/logger/pricing.js +96 -0
  60. package/src/logger/repair-history.js +109 -0
  61. package/src/logger/token-tracker.js +277 -0
  62. package/src/mcp/mcp-client.js +224 -0
  63. package/src/mcp/mcp-registry.js +228 -0
  64. package/src/mcp/mcp-security.js +152 -0
  65. package/src/monitor/perf-monitor.js +300 -0
  66. package/src/monitor/process-monitor.js +231 -0
  67. package/src/monitor/route-prober.js +191 -0
  68. package/src/notifications/notifier.js +227 -0
  69. package/src/platform/heartbeat.js +93 -0
  70. package/src/platform/queue.js +53 -0
  71. package/src/platform/register.js +64 -0
  72. package/src/platform/telemetry.js +76 -0
  73. package/src/security/admin-auth.js +150 -0
  74. package/src/security/injection-detector.js +174 -0
  75. package/src/security/rate-limiter.js +152 -0
  76. package/src/security/sandbox.js +128 -0
  77. package/src/security/secret-redactor.js +217 -0
  78. package/src/skills/skill-registry.js +129 -0
  79. package/src/skills/sql.js +375 -0
package/README.md ADDED
@@ -0,0 +1,475 @@
1
+ # Wolverine Node.js
2
+
3
+ **Self-healing Node.js servers powered by an AI coding harness.**
4
+
5
+ Wolverine watches your server process, catches crashes, diagnoses errors with AI, generates fixes, verifies them, and restarts — automatically. It also has a dashboard with a command interface where you can tell the agent to build features, and it will modify your server code directly.
6
+
7
+ Built on patterns from [claw-code](https://github.com/instructkr/claw-code) — the open-source Claude Code harness.
8
+
9
+ ---
10
+
11
+ ## Quick Start
12
+
13
+ ```bash
14
+ git clone https://github.com/bobbyswhip/Wolverine.git
15
+ cd Wolverine
16
+ npm install
17
+ cp .env.example .env.local
18
+ # Edit .env.local — add your OPENAI_API_KEY and generate an ADMIN_KEY
19
+ npm start
20
+ ```
21
+
22
+ Dashboard opens at `http://localhost:PORT+1`. Server runs on `PORT`.
23
+
24
+ ### Try a Demo
25
+
26
+ Demos copy a buggy server into `server/`, let wolverine fix it, then restore your original:
27
+
28
+ ```bash
29
+ npm run demo:list # See all demos
30
+ npm run demo:01 # Basic typo (ReferenceError)
31
+ npm run demo:02 # Multi-file import mismatch
32
+ npm run demo:03 # Syntax error (extra paren)
33
+ npm run demo:04 # Secret leak in error output
34
+ npm run demo:05 # External service down (human notification)
35
+ npm run demo:06 # JSON config typo
36
+ npm run demo:07 # null.toString() crash
37
+ ```
38
+
39
+ Each demo:
40
+ 1. Backs up your current `server/` directory
41
+ 2. Copies the buggy demo into `server/`
42
+ 3. Runs wolverine — watch it detect, diagnose, fix, verify, and restart
43
+ 4. Restores your original `server/` when you press Ctrl+C
44
+
45
+ ---
46
+
47
+ ## Architecture
48
+
49
+ ```
50
+ wolverine/
51
+ ├── server/ ← YOUR server code (agent can edit)
52
+ │ ├── index.js ← Entry point
53
+ │ ├── routes/ ← Route modules
54
+ │ └── config/settings.json ← All settings (models, cluster, telemetry, limits)
55
+ ├── src/
56
+ │ ├── core/ ← Wolverine engine
57
+ │ │ ├── wolverine.js ← Heal pipeline + goal loop
58
+ │ │ ├── runner.js ← Process manager (PM2-like)
59
+ │ │ ├── ai-client.js ← OpenAI client (Chat + Responses API)
60
+ │ │ ├── models.js ← 10-model configuration system
61
+ │ │ ├── verifier.js ← Fix verification (syntax + boot probe)
62
+ │ │ ├── error-parser.js ← Stack trace parsing
63
+ │ │ ├── patcher.js ← File patching with sandbox
64
+ │ │ ├── health-monitor.js← PM2-style health checks
65
+ │ │ ├── config.js ← Config loader (settings.json + env)
66
+ │ │ ├── system-info.js ← Machine detection (cores, RAM, cloud, containers)
67
+ │ │ └── cluster-manager.js← Auto-scaling worker management
68
+ │ ├── agent/ ← AI agent system
69
+ │ │ ├── agent-engine.js ← Multi-turn agent with 10 tools
70
+ │ │ ├── goal-loop.js ← Goal-driven repair loop
71
+ │ │ ├── research-agent.js← Deep research + learning from failures
72
+ │ │ └── sub-agents.js ← 7 specialized sub-agents (explore/plan/fix/verify/...)
73
+ │ ├── security/ ← Security stack
74
+ │ │ ├── sandbox.js ← Directory-locked file access
75
+ │ │ ├── secret-redactor.js← Env value → key name replacement
76
+ │ │ ├── injection-detector.js ← AI-powered prompt injection scan
77
+ │ │ ├── rate-limiter.js ← Error explosion protection
78
+ │ │ └── admin-auth.js ← Dashboard admin authentication
79
+ │ ├── brain/ ← Semantic memory
80
+ │ │ ├── brain.js ← Vector store + function map + learning
81
+ │ │ ├── vector-store.js ← In-memory cosine similarity search
82
+ │ │ ├── embedder.js ← Embedding + text compaction pipeline
83
+ │ │ └── function-map.js ← Live project scanner
84
+ │ ├── backup/ ← Smart backup system
85
+ │ │ └── backup-manager.js← Full server/ snapshots with retention
86
+ │ ├── logger/ ← Observability
87
+ │ │ ├── event-logger.js ← Structured event bus + JSONL persistence
88
+ │ │ ├── token-tracker.js ← Token usage + USD cost tracking
89
+ │ │ ├── repair-history.js← Error/resolution audit trail
90
+ │ │ └── pricing.js ← Model cost calculations
91
+ │ ├── monitor/ ← Performance + process management
92
+ │ │ ├── perf-monitor.js ← Endpoint response times + spam detection
93
+ │ │ ├── process-monitor.js← Memory/CPU/heartbeat + leak detection
94
+ │ │ └── route-prober.js ← Auto-discovers and tests all routes
95
+ │ ├── dashboard/ ← Web UI
96
+ │ │ └── server.js ← Real-time dashboard + command interface
97
+ │ ├── notifications/ ← Alerts
98
+ │ │ └── notifier.js ← Human-required error detection
99
+ │ ├── mcp/ ← External tools
100
+ │ │ ├── mcp-client.js ← MCP protocol client (stdio + HTTP)
101
+ │ │ ├── mcp-registry.js ← Server discovery + tool registration
102
+ │ │ └── mcp-security.js ← Allowlists + injection scan on MCP results
103
+ │ ├── skills/ ← Reusable capabilities
104
+ │ │ ├── skill-registry.js← Auto-discovery + prompt injection
105
+ │ │ └── sql.js ← Cluster-safe SQL + injection prevention
106
+ │ └── platform/ ← Fleet telemetry
107
+ │ ├── telemetry.js ← Collects heartbeat data from all subsystems
108
+ │ ├── heartbeat.js ← Sends heartbeats to platform backend
109
+ │ ├── register.js ← Auto-registration on first run
110
+ │ └── queue.js ← Offline queue with replay
111
+ ├── bin/wolverine.js ← CLI entry point (cluster-aware)
112
+ ├── tests/ ← Test suite
113
+ └── .wolverine/ ← Runtime state (gitignored)
114
+ ├── brain/ ← Vector store persistence
115
+ ├── events/ ← Event log (JSONL)
116
+ ├── backups/ ← Server snapshots
117
+ ├── usage.json ← Token usage aggregates
118
+ ├── usage-history.jsonl ← Full token usage timeline
119
+ ├── repair-history.json ← Error/resolution audit trail
120
+ └── mcp.json ← MCP server configuration
121
+ ```
122
+
123
+ ---
124
+
125
+ ## How Self-Healing Works
126
+
127
+ ```
128
+ Server crashes
129
+ → Error parsed (file, line, message)
130
+ → Secrets redacted from error output
131
+ → Prompt injection scan (AUDIT_MODEL)
132
+ → Human-required check (expired keys, service down → notify, don't waste tokens)
133
+ → Rate limit check (error loop → exponential backoff)
134
+
135
+ Goal Loop (iterate until fixed or exhausted):
136
+ Iteration 1: Fast path (CODING_MODEL, single file, ~1-2k tokens)
137
+ → Apply patch → Verify (syntax check + boot probe) → Pass? Done.
138
+ Iteration 2: Single agent (REASONING_MODEL, multi-file, 10 tools)
139
+ → Explores codebase → Fix → Verify → Pass? Done.
140
+ Iteration 3: Sub-agents (explore → plan → fix)
141
+ → Explorer finds relevant files (read-only)
142
+ → Planner proposes fix strategy (read-only)
143
+ → Fixer executes the plan (write access)
144
+ → Deep research (RESEARCH_MODEL) feeds into context
145
+ → Each failure feeds into the next attempt
146
+
147
+ After fix:
148
+ → Record to repair history (error, resolution, tokens, cost)
149
+ → Store in brain for future reference
150
+ → Promote backup to stable after 30min uptime
151
+ ```
152
+
153
+ ---
154
+
155
+ ## Agent Tool Harness
156
+
157
+ The AI agent has 10 built-in tools (ported from [claw-code](https://github.com/instructkr/claw-code)):
158
+
159
+ | Tool | Source | Description |
160
+ |------|--------|-------------|
161
+ | `read_file` | FileReadTool | Read any file with optional offset/limit for large files |
162
+ | `write_file` | FileWriteTool | Write complete file content, creates parent dirs |
163
+ | `edit_file` | FileEditTool | Surgical find-and-replace without rewriting entire file |
164
+ | `glob_files` | GlobTool | Pattern-based file discovery (`**/*.js`, `src/**/*.json`) |
165
+ | `grep_code` | GrepTool | Regex search across codebase with context lines |
166
+ | `bash_exec` | BashTool | Sandboxed shell execution with blocked dangerous commands |
167
+ | `git_log` | gitOperationTracking | View recent commit history |
168
+ | `git_diff` | gitOperationTracking | View uncommitted changes |
169
+ | `web_fetch` | WebFetchTool | Fetch URL content for documentation/research |
170
+ | `done` | — | Signal task completion with summary |
171
+
172
+ **Blocked commands** (from claw-code's `destructiveCommandWarning`):
173
+ `rm -rf /`, `git push --force`, `git reset --hard`, `npm publish`, `curl | bash`, `eval()`
174
+
175
+ **Protected paths** — the agent can NEVER modify:
176
+ `src/`, `bin/`, `tests/`, `node_modules/`, `.env`, `package.json`
177
+
178
+ Only files in `server/` are editable.
179
+
180
+ ### Sub-Agents
181
+
182
+ For complex repairs, wolverine spawns specialized sub-agents that run in sequence or parallel:
183
+
184
+ | Agent | Access | Model | Role |
185
+ |-------|--------|-------|------|
186
+ | `explore` | Read-only | REASONING | Investigate codebase, find relevant files |
187
+ | `plan` | Read-only | REASONING | Analyze problem, propose fix strategy |
188
+ | `fix` | Read+write | CODING | Execute targeted fix from plan |
189
+ | `verify` | Read-only | REASONING | Check if fix actually works |
190
+ | `research` | Read-only | RESEARCH | Search brain + web for solutions |
191
+ | `security` | Read-only | AUDIT | Audit code for vulnerabilities |
192
+ | `database` | Read+write | CODING | Database-specific fixes (SQL skill) |
193
+
194
+ Each sub-agent gets **restricted tools** — the explorer can't write files, the fixer can't search the web. This prevents agents from overstepping their role.
195
+
196
+ **Workflows:**
197
+ - `exploreAndFix()` — explore → plan → fix (sequential, 3 agents)
198
+ - `spawnParallel()` — run multiple agents concurrently (e.g., security + explore)
199
+
200
+ ---
201
+
202
+ ## Dashboard
203
+
204
+ Real-time web UI at `http://localhost:PORT+1`:
205
+
206
+ | Panel | What it shows |
207
+ |-------|--------------|
208
+ | **Overview** | Heals, errors, rollbacks, memories, uptime + recent events |
209
+ | **Events** | Live SSE event stream with color-coded severity |
210
+ | **Performance** | Endpoint response times, request rates, error rates |
211
+ | **Command** | Admin chat interface — ask questions or build features |
212
+ | **Analytics** | Memory/CPU charts, route health, per-route response times + trends |
213
+ | **Command** | Admin chat interface — ask questions or build features |
214
+ | **Backups** | Full server/ snapshot history with status badges |
215
+ | **Brain** | Vector store stats (23 seed docs), namespace counts, function map |
216
+ | **Repairs** | Error/resolution audit trail: error, fix, tokens, cost, duration |
217
+ | **Tools** | Agent tool harness listing (10 built-in + MCP) |
218
+ | **Usage** | Token analytics: by model, by category, by tool + USD cost per call |
219
+
220
+ ### Command Interface
221
+
222
+ Three routes (AI-classified per command):
223
+
224
+ | Route | Model | Tools | When |
225
+ |-------|-------|-------|------|
226
+ | **SIMPLE** | CHAT_MODEL | None | Knowledge questions, explanations |
227
+ | **TOOLS** | TOOL_MODEL | call_endpoint, read_file, search_brain | Live data, file contents |
228
+ | **AGENT** | CODING_MODEL | Full 10-tool harness | Build features, fix code |
229
+
230
+ Secured with `WOLVERINE_ADMIN_KEY` + localhost-only IP check.
231
+
232
+ ---
233
+
234
+ ## 10-Model Configuration
235
+
236
+ Every AI task has its own model slot. Customize in `.env.local`:
237
+
238
+ | Env Variable | Role | Needs Tools? | Cost Impact |
239
+ |---|---|---|---|
240
+ | `REASONING_MODEL` | Multi-file agent | Yes | High (agent loop) |
241
+ | `CODING_MODEL` | Code repair/generation | Responses API | Medium-high |
242
+ | `CHAT_MODEL` | Simple text responses | No | Low |
243
+ | `TOOL_MODEL` | Chat with function calling | **Yes** | Medium |
244
+ | `CLASSIFIER_MODEL` | SIMPLE/TOOLS/AGENT routing | No | ~10 tokens |
245
+ | `AUDIT_MODEL` | Injection detection (every error) | No | Low |
246
+ | `COMPACTING_MODEL` | Text compression for brain | No | Low |
247
+ | `RESEARCH_MODEL` | Deep research on failures | No | High (rare) |
248
+ | `TEXT_EMBEDDING_MODEL` | Brain vector embeddings | No | Very low |
249
+
250
+ Reasoning models (`o-series`, `gpt-5-nano`) automatically get 4x token limits to accommodate chain-of-thought.
251
+
252
+ ---
253
+
254
+ ## Security
255
+
256
+ | Layer | What it does |
257
+ |-------|-------------|
258
+ | **Secret Redactor** | Reads `.env.local`, replaces secret values with `process.env.KEY_NAME` in all AI calls, logs, brain, dashboard |
259
+ | **Injection Detector** | Regex layer + AI audit (AUDIT_MODEL) on every error before repair |
260
+ | **Sandbox** | All file operations locked to project directory, symlink escape detection |
261
+ | **Protected Paths** | Agent blocked from modifying wolverine internals (`src/`, `bin/`, etc.) |
262
+ | **Admin Auth** | Dashboard command interface requires key + localhost IP, timing-safe comparison, lockout after 10 failures |
263
+ | **Rate Limiter** | Sliding window, min gap, hourly budget, exponential backoff on error loops |
264
+ | **MCP Security** | Per-server tool allowlists, arg sanitization, result injection scanning |
265
+ | **SQL Skill** | `sqlGuard()` middleware blocks 15 injection pattern families on all endpoints |
266
+
267
+ ---
268
+
269
+ ## Brain (Semantic Memory)
270
+
271
+ Vector database that gives wolverine long-term memory:
272
+
273
+ - **Function Map** — scans `server/` on startup, indexes all routes, functions, classes, exports
274
+ - **Error History** — past errors with context for loop prevention
275
+ - **Fix History** — successful and failed repairs for learning
276
+ - **Learnings** — research findings, admin commands, patterns discovered
277
+ - **Skill Knowledge** — embedded docs for SQL skill, best practices, wolverine itself
278
+
279
+ **Two-tier search** for speed:
280
+ 1. Keyword match (instant, 0ms) — catches most lookups
281
+ 2. Semantic embedding search (API call) — only when keywords miss
282
+
283
+ ---
284
+
285
+ ## Process Manager
286
+
287
+ Wolverine acts as a PM2-like process manager with AI-powered diagnostics:
288
+
289
+ | Feature | What it does |
290
+ |---------|-------------|
291
+ | **Heartbeat** | Checks if the process is alive every 10 seconds |
292
+ | **Memory monitoring** | Tracks RSS/heap, detects leaks (N consecutive growth samples → restart) |
293
+ | **Memory limit** | Auto-restart when RSS exceeds threshold (default 512MB, configurable) |
294
+ | **CPU tracking** | Samples CPU% with color-coded charting (green/yellow/red) |
295
+ | **Route probing** | Auto-discovers ALL routes from function map, probes every 30s |
296
+ | **Response time trends** | Per-route avg/min/max + trend detection (stable/degrading/improving) |
297
+ | **Frozen detection** | Health check failures trigger force-kill and heal cycle |
298
+ | **Auto-adaptation** | When you add new routes, the prober discovers and monitors them |
299
+
300
+ The `📊 Analytics` dashboard panel shows memory/CPU charts, route health status, and response time breakdowns — all updating in real-time.
301
+
302
+ ---
303
+
304
+ ## Auto-Clustering
305
+
306
+ Wolverine detects your machine and forks the optimal number of workers:
307
+
308
+ ```bash
309
+ wolverine server/index.js # auto-detect: 20 cores → 10 workers
310
+ wolverine server/index.js --single # force single worker (dev mode)
311
+ wolverine server/index.js --workers 4 # force 4 workers
312
+ wolverine --info # show system capabilities
313
+ ```
314
+
315
+ **System detection:**
316
+ - CPU cores, model, speed
317
+ - Total/free RAM, disk space
318
+ - Platform (Linux, macOS, Windows)
319
+ - Container environment (Docker, Kubernetes)
320
+ - Cloud provider (AWS, GCP, Azure, Railway, Fly, Render, Heroku)
321
+
322
+ **Scaling rules:**
323
+
324
+ | Cores | Workers |
325
+ |-------|---------|
326
+ | 1 | 1 (no clustering) |
327
+ | 2 | 2 |
328
+ | 3-4 | cores - 1 |
329
+ | 5-8 | cores - 1, cap 6 |
330
+ | 9+ | cores / 2, cap 16 |
331
+
332
+ Workers auto-respawn on crash with exponential backoff (1s → 30s). Max 5 restarts per worker.
333
+
334
+ ---
335
+
336
+ ## Configuration
337
+
338
+ ```
339
+ .env.local ← Secrets only (API keys, admin key)
340
+ server/config/settings.json ← Everything else (models, port, clustering, telemetry, limits)
341
+ ```
342
+
343
+ `settings.json` is inside `server/` so the agent can read and edit it. Config loader priority: **env vars > settings.json > defaults**.
344
+
345
+ ---
346
+
347
+ ## Platform Telemetry
348
+
349
+ Every wolverine instance automatically broadcasts health data to the analytics platform. **Zero config** — telemetry is on by default.
350
+
351
+ ```
352
+ Startup:
353
+ 📡 Registering with https://api.wolverinenode.xyz...
354
+ 📡 Registered: wlv_a8f3e9b1c4d7
355
+ 📡 https://api.wolverinenode.xyz (60s)
356
+ ```
357
+
358
+ **How it works:**
359
+ - Auto-registers on first run, retries every 60s until platform responds
360
+ - Saves key to `.wolverine/platform-key` (survives restarts)
361
+ - Sends one ~2KB JSON POST every 60 seconds (5s timeout, non-blocking)
362
+ - Payload matches [PLATFORM.md](PLATFORM.md) spec: `instanceId`, `server`, `process`, `routes`, `repairs`, `usage`, `brain`, `backups`
363
+ - Secrets redacted before sending
364
+ - Offline-resilient: queues up to 1440 heartbeats locally, drains on reconnect
365
+
366
+ **Lightweight:** 4 files, ~250 lines. No external dependencies. Key/version cached in memory. Response bodies drained immediately. No blocking, no delays.
367
+
368
+ **Override:** `WOLVERINE_PLATFORM_URL=https://your-own-platform.com`
369
+ **Opt out:** `WOLVERINE_TELEMETRY=false`
370
+
371
+ See [PLATFORM.md](PLATFORM.md) for the backend spec and [TELEMETRY.md](TELEMETRY.md) for the protocol.
372
+
373
+ ---
374
+
375
+ ## Demos
376
+
377
+ All demos use the `server/` directory pattern. Each demo:
378
+ 1. Backs up your current `server/`
379
+ 2. Copies a buggy Express server into `server/`
380
+ 3. Runs wolverine — you watch it fix the bug in real-time
381
+ 4. Restores your original `server/` on Ctrl+C
382
+
383
+ | Demo | Bug | What it tests |
384
+ |------|-----|--------------|
385
+ | `01-basic-typo` | `userz` → `users` | Fast path, error parser, backup |
386
+ | `02-multi-file` | Import name mismatch across files | Agent multi-file understanding |
387
+ | `03-syntax-error` | Extra closing paren | Syntax check in verifier |
388
+ | `04-secret-leak` | Env var in error output | Secret redaction before AI |
389
+ | `05-expired-key` | External service 503 | Human notification system |
390
+ | `06-json-config` | Typo in JSON key | Agent edits non-JS files |
391
+ | `07-null-crash` | `null.toString()` | Fast path basic repair |
392
+
393
+ ---
394
+
395
+ ## Backup System
396
+
397
+ Full `server/` directory snapshots:
398
+
399
+ - Created before every repair attempt and every smart edit
400
+ - Includes all files: `.js`, `.json`, `.sql`, `.db`, `.yaml`, configs
401
+ - **Status lifecycle**: UNSTABLE → VERIFIED (fix passed) → STABLE (30min+ uptime)
402
+ - **Retention**: unstable pruned after 7 days, stable keeps 1/day after 7 days
403
+ - Atomic writes prevent corruption on kill
404
+
405
+ ---
406
+
407
+ ## Skills
408
+
409
+ Auto-discovered from `src/skills/`. Each skill exports metadata for the registry:
410
+
411
+ ### SQL Skill (`src/skills/sql.js`)
412
+ - **sqlGuard()** — Express middleware blocking SQL injection (UNION, stacked queries, tautologies, timing attacks, etc.)
413
+ - **SafeDB** — Parameterized-only database wrapper (blocks string concatenation in queries)
414
+ - Auto-injected into agent prompts when building database features
415
+
416
+ Add new skills by creating a file in `src/skills/` with `SKILL_NAME`, `SKILL_DESCRIPTION`, `SKILL_KEYWORDS`, `SKILL_USAGE` exports.
417
+
418
+ ---
419
+
420
+ ## MCP Integration
421
+
422
+ Connect external tools via [Model Context Protocol](https://modelcontextprotocol.io):
423
+
424
+ ```json
425
+ // .wolverine/mcp.json
426
+ {
427
+ "servers": {
428
+ "datadog": {
429
+ "type": "stdio",
430
+ "command": "npx",
431
+ "args": ["-y", "@datadog/mcp-server"],
432
+ "allowedTools": ["get_metrics", "list_monitors"],
433
+ "enabled": true
434
+ }
435
+ }
436
+ }
437
+ ```
438
+
439
+ Tools appear as `mcp__datadog__get_metrics` in the agent. All MCP data passes through the security stack (redaction, injection scan, rate limiting).
440
+
441
+ ---
442
+
443
+ ## Usage Tracking
444
+
445
+ Every API call tracked with input/output tokens + USD cost:
446
+
447
+ - **By Category**: heal, develop, chat, security, classify, research, brain
448
+ - **By Model**: which model costs the most
449
+ - **By Tool**: call_endpoint, search_brain, etc.
450
+ - **Timeline chart**: color-coded SVG bar chart
451
+ - **Persisted**: `.wolverine/usage-history.jsonl` survives restarts
452
+ - **Custom pricing**: override in `.wolverine/pricing.json`
453
+
454
+ ---
455
+
456
+ ## Notifications
457
+
458
+ Errors the AI can't fix trigger human alerts:
459
+
460
+ | Category | Examples |
461
+ |----------|---------|
462
+ | **auth** | 401 Unauthorized, expired API key, invalid credentials |
463
+ | **billing** | 429 rate limit, quota exceeded, credits depleted |
464
+ | **service** | ECONNREFUSED, ENOTFOUND, ETIMEDOUT, 503 |
465
+ | **cert** | SSL/TLS errors, self-signed certificate |
466
+ | **permission** | EACCES, EPERM |
467
+ | **disk** | ENOSPC, ENOMEM |
468
+
469
+ AI summary generated with CHAT_MODEL, secrets redacted, optional webhook delivery.
470
+
471
+ ---
472
+
473
+ ## License
474
+
475
+ MIT
@@ -0,0 +1,62 @@
1
+ # Wolverine Server Best Practices
2
+
3
+ Rules for building secure, scalable, well-structured servers. Wolverine's agent follows these when building or editing server code.
4
+
5
+ ## Structure
6
+
7
+ ```
8
+ server/
9
+ ├── index.js Entry point — app setup, middleware, route mounting, listen
10
+ ├── routes/ Route modules — one file per resource
11
+ │ ├── health.js Health check endpoint (always required)
12
+ │ └── api.js API routes
13
+ ├── middleware/ Custom middleware (auth, validation, logging)
14
+ ├── models/ Data models / database schemas
15
+ ├── services/ Business logic (keep routes thin)
16
+ ├── config/ Configuration files
17
+ └── utils/ Shared utilities
18
+ ```
19
+
20
+ ## Rules
21
+
22
+ ### Security
23
+ - Never expose secrets in responses — use env vars, never hardcode
24
+ - Validate ALL input — use express.json() with size limits
25
+ - Use helmet() for HTTP security headers in production
26
+ - Rate limit public endpoints
27
+ - Sanitize user input before database queries
28
+ - Never return stack traces in production error responses
29
+
30
+ ### Scalability
31
+ - Keep routes thin — business logic goes in services/
32
+ - Use async/await, never block the event loop
33
+ - Add a /health endpoint that returns status + uptime + memory
34
+ - Use environment variables for all configuration
35
+ - Structure for horizontal scaling — no in-memory session state
36
+
37
+ ### Error Handling
38
+ - Always have a global error handler middleware
39
+ - Log errors with context (timestamp, request path, user)
40
+ - Return consistent error response format: { error: "message" }
41
+ - Never swallow errors silently
42
+ - Use try/catch in async route handlers
43
+
44
+ ### Code Quality
45
+ - One route file per resource (users.js, orders.js, etc.)
46
+ - Export express.Router() from each route file
47
+ - Mount routes in index.js with clear prefixes
48
+ - Use middleware for cross-cutting concerns (auth, logging)
49
+ - Keep index.js under 50 lines — it's just wiring
50
+
51
+ ### Database
52
+ - Use connection pooling
53
+ - Handle connection errors gracefully
54
+ - Use migrations for schema changes
55
+ - Never use string concatenation for queries — use parameterized queries
56
+ - Close connections on process exit
57
+
58
+ ### Monitoring
59
+ - /health endpoint is mandatory
60
+ - Log request duration for slow endpoint detection
61
+ - Use structured logging (JSON format)
62
+ - Track error rates per endpoint
package/TELEMETRY.md ADDED
@@ -0,0 +1,108 @@
1
+ # Wolverine Telemetry
2
+
3
+ Connect your Wolverine instance to a platform backend for fleet-wide monitoring, uptime tracking, and cost analytics.
4
+
5
+ ## Setup
6
+
7
+ ### 1. Deploy your platform backend
8
+
9
+ See [PLATFORM.md](PLATFORM.md) for the full backend spec — database schema, API endpoints, scaling strategy.
10
+
11
+ Your backend needs to implement:
12
+ - `POST /api/v1/heartbeat` — receive heartbeat payloads
13
+ - `GET /api/v1/servers` — list connected instances
14
+ - Standard Bearer token auth
15
+
16
+ ### 2. Configure your Wolverine instance
17
+
18
+ Add to `.env.local`:
19
+
20
+ ```env
21
+ WOLVERINE_PLATFORM_URL=https://your-platform.com
22
+ WOLVERINE_PLATFORM_KEY=your_api_key_here
23
+ ```
24
+
25
+ That's it. Wolverine starts sending heartbeats every 60 seconds.
26
+
27
+ ### Optional settings
28
+
29
+ ```env
30
+ # Human-readable name (defaults to folder name)
31
+ WOLVERINE_INSTANCE_NAME=my-api-prod
32
+
33
+ # Heartbeat interval in ms (default: 60000 = 1 minute)
34
+ WOLVERINE_HEARTBEAT_INTERVAL_MS=60000
35
+ ```
36
+
37
+ ### 3. Verify
38
+
39
+ On startup you'll see:
40
+
41
+ ```
42
+ 📡 Platform: https://your-platform.com (every 60s)
43
+ 📡 Instance: wlv_a8f3e9b1c4d7
44
+ ```
45
+
46
+ If the platform is unreachable, heartbeats queue locally in `.wolverine/heartbeat-queue.jsonl` and drain automatically when connectivity returns.
47
+
48
+ ---
49
+
50
+ ## Heartbeat Payload
51
+
52
+ Each heartbeat is ~2KB JSON, sent every 60 seconds:
53
+
54
+ ```json
55
+ {
56
+ "instanceId": "wlv_a8f3e9b1c4d7",
57
+ "version": "0.1.0",
58
+ "timestamp": 1775073247574,
59
+ "server": {
60
+ "name": "my-api",
61
+ "port": 3000,
62
+ "uptime": 86400,
63
+ "status": "healthy",
64
+ "pid": 12345
65
+ },
66
+ "process": {
67
+ "memoryMB": 128,
68
+ "cpuPercent": 12,
69
+ "peakMemoryMB": 256
70
+ },
71
+ "routes": {
72
+ "total": 8,
73
+ "healthy": 8,
74
+ "unhealthy": 0
75
+ },
76
+ "repairs": {
77
+ "total": 3,
78
+ "successes": 2,
79
+ "failures": 1,
80
+ "lastRepair": { "error": "...", "resolution": "...", "tokens": 1820, "cost": 0.0045 }
81
+ },
82
+ "usage": {
83
+ "totalTokens": 45000,
84
+ "totalCost": 0.12,
85
+ "totalCalls": 85,
86
+ "byCategory": { "heal": {...}, "chat": {...}, "develop": {...} }
87
+ },
88
+ "brain": { "totalMemories": 45 },
89
+ "backups": { "total": 8, "stable": 3 }
90
+ }
91
+ ```
92
+
93
+ ## Design
94
+
95
+ - **Opt-in**: disabled unless `WOLVERINE_PLATFORM_URL` and `WOLVERINE_PLATFORM_KEY` are set
96
+ - **Lightweight**: 1 request per 60s, ~2KB payload
97
+ - **Offline-resilient**: queues locally when platform is down, replays on reconnect (max 24h / 1440 entries)
98
+ - **Secure**: secrets redacted before sending, HTTPS supported, Bearer token auth
99
+ - **No source code**: only metrics, redacted error messages, and stats
100
+
101
+ ## Files
102
+
103
+ ```
104
+ src/platform/
105
+ ├── telemetry.js — Collects metrics from all subsystems into heartbeat payload
106
+ ├── heartbeat.js — Sends heartbeats on interval, handles failures
107
+ └── queue.js — Offline queue with replay on reconnect
108
+ ```