@whenlabs/when 0.9.2 → 0.9.3

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.
@@ -1,484 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- ALL_EDITORS,
4
- installForEditor,
5
- registerMcpServer
6
- } from "./chunk-3PDLNC63.js";
7
- import {
8
- injectBlock
9
- } from "./chunk-NYUYV3UL.js";
10
-
11
- // src/commands/install.ts
12
- import { join } from "path";
13
- import { homedir } from "os";
14
- import { existsSync, readFileSync, writeFileSync, mkdirSync, chmodSync } from "fs";
15
- import { execFileSync } from "child_process";
16
- var CLAUDE_MD_PATH = join(homedir(), ".claude", "CLAUDE.md");
17
- var SCRIPTS_DIR = join(homedir(), ".claude", "scripts");
18
- var STATUSLINE_PATH = join(SCRIPTS_DIR, "statusline.py");
19
- var SETTINGS_PATH = join(homedir(), ".claude", "settings.json");
20
- var OLD_START_MARKER = "<!-- velocity-mcp:start -->";
21
- var OLD_END_MARKER = "<!-- velocity-mcp:end -->";
22
- var CLAUDE_MD_CONTENT = `# WhenLabs Toolkit
23
-
24
- ## Task Timing (velocity-mcp)
25
-
26
- Velocity tools are part of the unified \`whenlabs\` MCP server. Follow these rules for EVERY session:
27
-
28
- 1. **Before starting any discrete coding task**, call \`velocity_start_task\` with:
29
- - Appropriate \`category\` (scaffold, implement, refactor, debug, test, config, docs, deploy)
30
- - Relevant \`tags\` (e.g. typescript, react, sqlite, api)
31
- - Clear \`description\` of what you're about to do
32
- - \`estimated_files\` if you know how many files you'll touch
33
- - \`project\` set to the current project name (auto-detected from git remote or directory name)
34
-
35
- 2. **After completing each task**, call \`velocity_end_task\` with:
36
- - The \`task_id\` from the start call
37
- - \`status\`: completed, failed, or abandoned
38
- - \`actual_files\`: how many files were actually modified
39
- - \`notes\`: any useful context about what happened
40
-
41
- 3. **When creating a multi-step plan**, call \`velocity_estimate\` to provide the user with a time estimate before starting work.
42
-
43
- 4. **If the user asks about speed or performance**, call \`velocity_stats\` to show aggregate data.
44
-
45
- ### Guidelines
46
- - Every discrete unit of work should be tracked \u2014 don't batch multiple unrelated changes into one task
47
- - If a task is abandoned or fails, still call \`velocity_end_task\` with the appropriate status
48
- - Use consistent tags across sessions so the similarity matching can find comparable historical tasks
49
- - Keep descriptions concise but specific enough to be useful for future matching
50
-
51
- ## WhenLabs MCP Tools (ALWAYS prefer these over shell commands)
52
-
53
- All six tools (including velocity) are available through the unified \`whenlabs\` MCP server. **ALWAYS use these MCP tools instead of running shell commands like lsof, grep, or manual checks.** These tools are purpose-built and give better results:
54
-
55
- | When to use | Call this tool | NOT this |
56
- |-------------|---------------|----------|
57
- | Check ports or port conflicts | \`berth_status\` or \`berth_check\` | \`lsof\`, \`netstat\`, \`ss\` |
58
- | Scan dependency licenses | \`vow_scan\` or \`vow_check\` | manual \`npm ls\`, \`license-checker\` |
59
- | Check if docs are stale | \`stale_scan\` | manual file comparison |
60
- | Validate .env files | \`envalid_validate\` or \`envalid_detect\` | manual .env inspection |
61
- | Generate AI context files | \`aware_init\` or \`aware_doctor\` | manual CLAUDE.md creation |
62
-
63
- ### Tool Reference
64
- - \`berth_status\` \u2014 Show all active ports, Docker ports, and configured ports
65
- - \`berth_check\` \u2014 Scan a project directory for port conflicts
66
- - \`stale_scan\` \u2014 Detect documentation drift in the codebase
67
- - \`envalid_validate\` \u2014 Validate .env files against their schema
68
- - \`envalid_detect\` \u2014 Find undocumented env vars in codebase
69
- - \`aware_init\` \u2014 Auto-detect stack and generate AI context files
70
- - \`aware_doctor\` \u2014 Diagnose project health and config issues
71
- - \`vow_scan\` \u2014 Scan and summarize all dependency licenses
72
- - \`vow_check\` \u2014 Validate licenses against a policy file
73
-
74
- ### Proactive Background Scans
75
- WhenLabs tools run automatically in the background on a schedule. The status line shows findings:
76
- - \`stale:N\` \u2014 N docs have drifted from code. Run \`stale_scan\` and fix the drift.
77
- - \`env:N\` \u2014 N .env issues found. Run \`envalid_validate\` and help the user fix them.
78
- - \`ports:N\` \u2014 N port conflicts. Run \`berth_status\` and suggest resolution.
79
- - \`lic:N?\` \u2014 N packages with unknown licenses. Run \`vow_scan\` for details.
80
- - \`aware:stale\` \u2014 AI context files are outdated. Run \`aware_init\` to regenerate.
81
-
82
- **When you see any of these in the status line, proactively tell the user and offer to fix the issue.** Do not wait for the user to ask.`;
83
- var STATUSLINE_SCRIPT = `#!/usr/bin/env python3
84
- """WhenLabs status line for Claude Code \u2014 with proactive background tool scans."""
85
-
86
- import json
87
- import os
88
- import subprocess
89
- import sys
90
- import time
91
- from pathlib import Path
92
-
93
- CACHE_DIR = Path.home() / ".whenlabs" / "cache"
94
- CACHE_DIR.mkdir(parents=True, exist_ok=True)
95
-
96
- # Scan intervals in seconds
97
- INTERVALS = {
98
- "berth": 900, # 15 min
99
- "stale": 1800, # 30 min
100
- "envalid": 1800, # 30 min
101
- "vow": 3600, # 60 min
102
- "aware": 3600, # 60 min
103
- }
104
-
105
-
106
- class C:
107
- AMBER = "\\033[38;2;196;106;26m"
108
- BLUE = "\\033[38;2;59;130;246m"
109
- CYAN = "\\033[38;2;34;211;238m"
110
- GREEN = "\\033[38;2;34;197;94m"
111
- RED = "\\033[38;2;239;68;68m"
112
- YELLOW = "\\033[38;2;234;179;8m"
113
- GRAY = "\\033[38;2;156;163;175m"
114
- DIM = "\\033[2m"
115
- RESET = "\\033[0m"
116
- SEP = f"\\033[38;2;107;114;128m \\u30fb \\033[0m"
117
-
118
-
119
- def git_info(cwd):
120
- try:
121
- subprocess.run(["git", "rev-parse", "--git-dir"], cwd=cwd, capture_output=True, check=True, timeout=1)
122
- branch = subprocess.run(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=cwd, capture_output=True, text=True, timeout=1).stdout.strip()
123
- status = subprocess.run(["git", "status", "--porcelain"], cwd=cwd, capture_output=True, text=True, timeout=1).stdout
124
- clean = len([l for l in status.strip().split("\\n") if l]) == 0
125
- color = C.GREEN if clean else C.YELLOW
126
- icon = "\\u2713" if clean else "\\u00b1"
127
- return f"{color}{branch} {icon}{C.RESET}"
128
- except Exception:
129
- return None
130
-
131
-
132
- def mcp_servers(data):
133
- servers = []
134
- try:
135
- cfg = Path.home() / ".claude.json"
136
- if cfg.exists():
137
- with open(cfg) as f:
138
- servers.extend(json.load(f).get("mcpServers", {}).keys())
139
- except Exception:
140
- pass
141
- cwd = data.get("workspace", {}).get("current_dir", "")
142
- if cwd:
143
- for p in [Path(cwd) / ".mcp.json", Path(cwd) / ".claude" / ".mcp.json"]:
144
- try:
145
- if p.exists():
146
- with open(p) as f:
147
- servers.extend(json.load(f).get("mcpServers", {}).keys())
148
- except Exception:
149
- pass
150
- seen = set()
151
- return [s for s in servers if not (s in seen or seen.add(s))]
152
-
153
-
154
- def context_pct(data):
155
- try:
156
- cw = data["context_window"]
157
- size = cw["context_window_size"]
158
- usage = cw.get("current_usage", {})
159
- tokens = usage.get("input_tokens", 0) + usage.get("cache_creation_input_tokens", 0) + usage.get("cache_read_input_tokens", 0)
160
- pct = (tokens * 100) // size
161
- color = C.GREEN if pct < 40 else C.YELLOW if pct < 70 else C.RED
162
- return f"{C.DIM}{color}{pct}%{C.RESET}"
163
- except Exception:
164
- return None
165
-
166
-
167
- def cost_info(data):
168
- try:
169
- cfg = Path.home() / ".claude.json"
170
- if cfg.exists():
171
- with open(cfg) as f:
172
- if json.load(f).get("oauthAccount", {}).get("accountUuid"):
173
- return None
174
- except Exception:
175
- pass
176
- try:
177
- cost = data.get("cost", {}).get("total_cost_usd")
178
- if cost:
179
- color = C.GREEN if cost < 1 else C.YELLOW if cost < 5 else C.RED
180
- return f"{color}\${cost:.2f}{C.RESET}"
181
- except Exception:
182
- pass
183
- return None
184
-
185
-
186
- # --- Background tool scanning ---
187
-
188
- def cache_path(tool, cwd):
189
- project = Path(cwd).name if cwd else "global"
190
- return CACHE_DIR / f"{tool}_{project}.json"
191
-
192
-
193
- def should_run(tool, cwd):
194
- cp = cache_path(tool, cwd)
195
- if not cp.exists():
196
- return True
197
- try:
198
- cached = json.loads(cp.read_text())
199
- return (time.time() - cached.get("timestamp", 0)) > INTERVALS[tool]
200
- except Exception:
201
- return True
202
-
203
-
204
- def run_bg(tool, args, cwd):
205
- cp = cache_path(tool, cwd)
206
- snippet = (
207
- "import subprocess, json, time, os; "
208
- f"args = {args!r}; "
209
- f"cwd = {cwd!r}; "
210
- f"out_path = {str(cp)!r}; "
211
- "env = {**os.environ, 'FORCE_COLOR': '0', 'NO_COLOR': '1'}; "
212
- "r = subprocess.run(args, cwd=cwd, capture_output=True, text=True, env=env, timeout=60); "
213
- "cache = {'timestamp': time.time(), 'output': r.stdout + r.stderr, 'code': r.returncode}; "
214
- "open(out_path, 'w').write(json.dumps(cache))"
215
- )
216
- try:
217
- subprocess.Popen(
218
- [sys.executable, "-c", snippet],
219
- stdout=subprocess.DEVNULL,
220
- stderr=subprocess.DEVNULL,
221
- start_new_session=True,
222
- )
223
- except Exception:
224
- pass
225
-
226
-
227
- def read_cache(tool, cwd):
228
- cp = cache_path(tool, cwd)
229
- if not cp.exists():
230
- return None
231
- try:
232
- return json.loads(cp.read_text())
233
- except Exception:
234
- return None
235
-
236
-
237
- def parse_stale(cached):
238
- if not cached or cached["code"] != 0:
239
- return None
240
- out = cached["output"]
241
- drifted = out.count("\\u2717")
242
- if drifted > 0:
243
- return f"{C.RED}stale:{drifted}{C.RESET}"
244
- if "\\u2713" in out or "No drift" in out.lower() or "clean" in out.lower():
245
- return f"{C.GREEN}stale:ok{C.RESET}"
246
- return None
247
-
248
-
249
- def parse_envalid(cached):
250
- if not cached:
251
- return None
252
- out = cached["output"]
253
- if cached["code"] != 0:
254
- errors = sum(1 for line in out.split("\\n") if "\\u2717" in line or "error" in line.lower() or "missing" in line.lower())
255
- if errors > 0:
256
- return f"{C.RED}env:{errors}{C.RESET}"
257
- return f"{C.YELLOW}env:?{C.RESET}"
258
- return f"{C.GREEN}env:ok{C.RESET}"
259
-
260
-
261
- def parse_berth(cached):
262
- if not cached:
263
- return None
264
- out = cached["output"]
265
- conflicts = out.lower().count("conflict")
266
- if conflicts > 0:
267
- return f"{C.RED}ports:{conflicts}{C.RESET}"
268
- return None
269
-
270
-
271
- def parse_vow(cached):
272
- if not cached:
273
- return None
274
- out = cached["output"]
275
- unknown = 0
276
- for line in out.split("\\n"):
277
- low = line.lower()
278
- if "unknown" in low or "unlicensed" in low:
279
- for word in line.split():
280
- if word.isdigit():
281
- unknown += int(word)
282
- break
283
- else:
284
- unknown += 1
285
- if unknown > 0:
286
- return f"{C.YELLOW}lic:{unknown}?{C.RESET}"
287
- return None
288
-
289
-
290
- def parse_aware(cached):
291
- if not cached:
292
- return None
293
- out = cached["output"]
294
- if cached["code"] != 0 or "stale" in out.lower() or "outdated" in out.lower() or "drift" in out.lower():
295
- return f"{C.YELLOW}aware:stale{C.RESET}"
296
- return None
297
-
298
-
299
- def run_scans(cwd):
300
- if not cwd:
301
- return []
302
-
303
- scans = {
304
- "stale": (["npx", "--yes", "@whenlabs/stale", "scan"], parse_stale),
305
- "envalid": (["npx", "--yes", "@whenlabs/envalid", "validate"], parse_envalid),
306
- "berth": (["npx", "--yes", "@whenlabs/berth", "check", "."], parse_berth),
307
- "vow": (["npx", "--yes", "@whenlabs/vow", "scan"], parse_vow),
308
- "aware": (["npx", "--yes", "@whenlabs/aware", "doctor"], parse_aware),
309
- }
310
-
311
- for tool, (args, _) in scans.items():
312
- if should_run(tool, cwd):
313
- run_bg(tool, args, cwd)
314
- break
315
-
316
- # Auto-sync aware when staleness detected
317
- aware_cached = read_cache("aware", cwd)
318
- if aware_cached:
319
- out = aware_cached.get("output", "")
320
- code = aware_cached.get("code", 0)
321
- if code != 0 or "stale" in out.lower() or "outdated" in out.lower() or "drift" in out.lower() or "never synced" in out.lower():
322
- sync_cache = cache_path("aware_sync", cwd)
323
- sync_age = 0
324
- if sync_cache.exists():
325
- try:
326
- sync_age = time.time() - json.loads(sync_cache.read_text()).get("timestamp", 0)
327
- except Exception:
328
- sync_age = 99999
329
- else:
330
- sync_age = 99999
331
- if sync_age > 3600: # Only auto-sync once per hour
332
- run_bg("aware_sync", ["npx", "--yes", "@whenlabs/aware", "sync"], cwd)
333
-
334
- results = []
335
- for tool, (_, parser) in scans.items():
336
- cached = read_cache(tool, cwd)
337
- if cached:
338
- parsed = parser(cached)
339
- if parsed:
340
- results.append(parsed)
341
-
342
- return results
343
-
344
-
345
- def main():
346
- try:
347
- data = json.loads(sys.stdin.read())
348
- except Exception:
349
- return
350
-
351
- parts = []
352
-
353
- cwd = data.get("workspace", {}).get("current_dir", "")
354
- if cwd:
355
- parts.append(f"{C.BLUE}{Path(cwd).name}{C.RESET}")
356
-
357
- if cwd:
358
- g = git_info(cwd)
359
- if g:
360
- parts.append(g)
361
-
362
- servers = mcp_servers(data)
363
- if servers:
364
- names = " ".join(servers)
365
- parts.append(f"{C.AMBER}{C.DIM}{names}{C.RESET}")
366
-
367
- c = cost_info(data)
368
- if c:
369
- parts.append(c)
370
-
371
- model = data.get("model", {}).get("display_name", "")
372
- if model:
373
- short = "".join(ch for ch in model if ch.isalpha()).lower()
374
- parts.append(f"{C.GRAY}{short}{C.RESET}")
375
-
376
- ctx = context_pct(data)
377
- if ctx:
378
- parts.append(ctx)
379
-
380
- ver = data.get("version")
381
- if ver:
382
- parts.append(f"{C.DIM}{C.GRAY}v{ver}{C.RESET}")
383
-
384
- scan_results = run_scans(cwd)
385
-
386
- print(C.SEP.join(parts))
387
-
388
- if scan_results:
389
- print(f"{C.DIM}{C.GRAY} tools:{C.RESET} {f' {C.DIM}|{C.RESET} '.join(scan_results)}")
390
-
391
-
392
- if __name__ == "__main__":
393
- main()
394
- `;
395
- function installStatusLine() {
396
- try {
397
- mkdirSync(SCRIPTS_DIR, { recursive: true });
398
- writeFileSync(STATUSLINE_PATH, STATUSLINE_SCRIPT, "utf-8");
399
- chmodSync(STATUSLINE_PATH, 493);
400
- let settings = {};
401
- if (existsSync(SETTINGS_PATH)) {
402
- try {
403
- settings = JSON.parse(readFileSync(SETTINGS_PATH, "utf-8"));
404
- } catch {
405
- settings = {};
406
- }
407
- }
408
- const statuslineCmd = `python3 ${STATUSLINE_PATH}`;
409
- const currentCmd = settings.statusLine?.command;
410
- if (currentCmd !== statuslineCmd) {
411
- settings.statusLine = { type: "command", command: statuslineCmd };
412
- writeFileSync(SETTINGS_PATH, JSON.stringify(settings, null, 2) + "\n", "utf-8");
413
- }
414
- return { installed: true, message: "Status line installed (proactive background scans)" };
415
- } catch (err) {
416
- return { installed: false, message: `Status line install failed: ${err.message}` };
417
- }
418
- }
419
- function escapeRegex(str) {
420
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
421
- }
422
- function hasOldBlock(filePath) {
423
- if (!existsSync(filePath)) return false;
424
- const content = readFileSync(filePath, "utf-8");
425
- return content.includes(OLD_START_MARKER) && content.includes(OLD_END_MARKER);
426
- }
427
- function removeOldBlock(filePath) {
428
- if (!existsSync(filePath)) return;
429
- let content = readFileSync(filePath, "utf-8");
430
- const pattern = new RegExp(
431
- `\\n?${escapeRegex(OLD_START_MARKER)}[\\s\\S]*?${escapeRegex(OLD_END_MARKER)}\\n?`,
432
- "g"
433
- );
434
- content = content.replace(pattern, "\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
435
- writeFileSync(filePath, content, "utf-8");
436
- }
437
- async function install(options = {}) {
438
- console.log("\n\u{1F527} WhenLabs toolkit installer\n");
439
- const editorFlags = options.all ? ALL_EDITORS : [
440
- options.cursor && "cursor",
441
- options.vscode && "vscode",
442
- options.windsurf && "windsurf"
443
- ].filter(Boolean);
444
- const claudeOnly = editorFlags.length === 0;
445
- if (claudeOnly) {
446
- const mcpResult = registerMcpServer();
447
- console.log(mcpResult.success ? ` \u2713 ${mcpResult.message}` : ` \u2717 ${mcpResult.message}`);
448
- injectBlock(CLAUDE_MD_PATH, CLAUDE_MD_CONTENT);
449
- console.log(` \u2713 CLAUDE.md instructions written to ${CLAUDE_MD_PATH}`);
450
- const slResult = installStatusLine();
451
- console.log(slResult.installed ? ` \u2713 ${slResult.message}` : ` \u2717 ${slResult.message}`);
452
- try {
453
- const cwd = process.cwd();
454
- execFileSync("npx", ["--yes", "@whenlabs/aware", "init", "--force"], {
455
- cwd,
456
- stdio: "pipe",
457
- env: { ...process.env, FORCE_COLOR: "0", NO_COLOR: "1" },
458
- timeout: 3e4
459
- });
460
- execFileSync("npx", ["--yes", "@whenlabs/aware", "sync"], {
461
- cwd,
462
- stdio: "pipe",
463
- env: { ...process.env, FORCE_COLOR: "0", NO_COLOR: "1" },
464
- timeout: 3e4
465
- });
466
- console.log(" \u2713 AI context files generated and synced (aware init + sync)");
467
- } catch {
468
- console.log(" - Skipped aware init (run `when aware init` in a project directory)");
469
- }
470
- if (hasOldBlock(CLAUDE_MD_PATH)) {
471
- removeOldBlock(CLAUDE_MD_PATH);
472
- console.log(" \u2713 Removed legacy velocity-mcp markers (migrated to whenlabs block)");
473
- }
474
- } else {
475
- for (const editor of editorFlags) {
476
- const result = installForEditor(editor);
477
- console.log(result.success ? ` \u2713 ${result.message}` : ` \u2717 ${result.message}`);
478
- }
479
- }
480
- console.log("\nInstallation complete. Run `when status` to verify.\n");
481
- }
482
- export {
483
- install
484
- };