Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 | 1x 1x 1x 28x 28x 80x 80x 2x 2x 2x 2x 2x 2x 80x 26x 26x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 32x 32x 1x 1x 1x 32x 28x 28x 28x 28x 28x 28x 28x 28x 9x 9x 2x 2x 2x 7x 9x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 24x 24x 4x 4x 4x 4x 4x 4x 4x 24x 2x 2x 2x 2x 2x 2x 24x 4x 4x 4x 4x 4x 4x 24x 3x 3x 3x 3x 3x 3x 24x 3x 3x 3x 3x 3x 3x 24x 4x 4x 4x 4x 4x 4x 4x 4x 1x | #!/usr/bin/env node
/**
* OpenSIP Tools CLI — codebase analysis toolkit
*
* Usage:
* opensip-tools fit [options] Run fitness checks
* opensip-tools fit --list List available checks
* opensip-tools fit --recipes List available recipes
* opensip-tools asm [options] Run assessments (coming soon)
* opensip-tools sim [options] Run simulations (coming soon)
*/
import { defaultRegistry, type Check, type CheckResult } from '@opensip-tools/core';
import { builtInRecipesByName } from '@opensip-tools/core/recipes/built-in-recipes.js';
import { resolveChecks } from '@opensip-tools/core/recipes/check-resolution.js';
/** Lazy-load fitness checks — only imported when actually running checks */
let checksLoaded = false;
async function ensureChecksLoaded(): Promise<void> {
if (checksLoaded) return;
await import('@opensip-tools/fitness');
checksLoaded = true;
}
import { execFileSync } from 'node:child_process';
import { readFileSync, existsSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { parse as parseYaml } from 'yaml';
import { saveSession, loadSessions, getReportsDir, generateSessionId, type StoredSession } from './persistence/store.js';
import { generateDashboardHtml } from './persistence/dashboard.js';
// =============================================================================
// CONFIG FILE (.opensip-tools.yml)
// =============================================================================
interface ToolsConfig {
recipe?: string;
exclude?: string[];
verbose?: boolean;
json?: boolean;
reportTo?: string;
apiKey?: string;
fileTypes?: string[];
ignore?: string[];
}
const CONFIG_FILENAMES = ['.opensip-tools.yml', '.opensip-tools.yaml', 'opensip-tools.yml'];
function loadConfig(cwd: string): ToolsConfig {
for (const filename of CONFIG_FILENAMES) {
const path = join(cwd, filename);
if (existsSync(path)) {
try {
const raw = readFileSync(path, 'utf-8');
const parsed = parseYaml(raw) as ToolsConfig | null;
return parsed ?? {};
} catch {
// Invalid YAML — ignore, use defaults
}
}
}
return {};
}
// =============================================================================
// TYPES
// =============================================================================
// =============================================================================
// BRANDING
// =============================================================================
// Each entry: [cup, openPart, sipPart]
const BANNER: readonly [string, string, string][] = [
[' \u2591 \u2591 ', ' \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588', ' \u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 '],
[' \u2591 \u2591 ', ' \u2588\u2588\u2588\u2591\u2591\u2591\u2588\u2588\u2588\u2591\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2588\u2588\u2591\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588', '\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2588\u2588'],
[' \u2591 \u2591 ', '\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2588 \u2588\u2588\u2588', '\u2591\u2588\u2588\u2588 \u2591\u2591\u2591 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588'],
['\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 ', '\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2588\u2588\u2591\u2588\u2588\u2588\u2588\u2588', '\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2591'],
['\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 ', '\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2591\u2588\u2588\u2588\u2591\u2591\u2591\u2591 \u2591\u2588\u2588\u2588\u2591\u2591\u2591 \u2591\u2588\u2588 \u2591\u2588\u2588\u2588\u2588', ' \u2591\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2591\u2591\u2591\u2591 '],
['\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2591\u2591\u2588\u2588\u2588 ', '\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588 \u2591\u2588\u2588\u2588', ' \u2588\u2588\u2588 \u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 '],
['\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 ', ' \u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2591 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588', '\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588 '],
['\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2591 \u2591\u2591\u2591 ', ' \u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591', ' \u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591 '],
];
const BANNER_SAUCER = ' \u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2591';
function printBanner(): void {
console.log('');
for (const [cup, openPart, sipPart] of BANNER) {
console.log(`${cup}${c.cyan(openPart)} ${c.bold(sipPart)}`);
}
console.log(BANNER_SAUCER);
console.log('');
}
// =============================================================================
// TYPES
// =============================================================================
/** Structured JSON output format */
interface CliOutput {
readonly version: '1.0';
readonly tool: 'fit' | 'asm' | 'sim';
readonly timestamp: string;
readonly recipe?: string;
readonly score: number;
readonly passed: boolean;
readonly summary: { total: number; passed: number; failed: number; errors: number; warnings: number };
readonly checks: readonly CheckOutput[];
readonly durationMs: number;
}
interface CheckOutput {
readonly checkSlug: string;
readonly passed: boolean;
readonly findings: readonly FindingOutput[];
readonly durationMs: number;
}
interface FindingOutput {
readonly ruleId: string;
readonly message: string;
readonly severity: 'error' | 'warning';
readonly filePath?: string;
readonly line?: number;
readonly column?: number;
readonly suggestion?: string;
readonly category?: string;
}
// =============================================================================
// COLORS (ANSI escape codes — no dependencies)
// =============================================================================
const supportsColor = process.stdout.isTTY && !process.env.NO_COLOR;
const c = {
green: (s: string) => supportsColor ? `\x1b[32m${s}\x1b[0m` : s,
red: (s: string) => supportsColor ? `\x1b[31m${s}\x1b[0m` : s,
yellow: (s: string) => supportsColor ? `\x1b[33m${s}\x1b[0m` : s,
dim: (s: string) => supportsColor ? `\x1b[2m${s}\x1b[0m` : s,
bold: (s: string) => supportsColor ? `\x1b[1m${s}\x1b[0m` : s,
cyan: (s: string) => supportsColor ? `\x1b[36m${s}\x1b[0m` : s,
};
// =============================================================================
// ARGUMENT PARSING
// =============================================================================
export interface CliArgs {
command: 'fit' | 'asm' | 'sim' | 'help' | 'version';
json: boolean;
check?: string;
recipe?: string;
cwd: string;
help: boolean;
list: boolean;
listRecipes: boolean;
verbose: boolean;
reportTo?: string;
apiKey?: string;
exclude: string[];
history: boolean;
dashboard: boolean;
}
export function parseArgs(argv: string[]): CliArgs {
const args = argv.slice(2);
const command = (args[0] ?? 'help') as CliArgs['command'];
let cwd = process.cwd();
let json = false;
let check: string | undefined;
let recipe: string | undefined;
let help = false;
let list = false;
let listRecipes = false;
let verbose = false;
let reportTo: string | undefined;
let apiKey: string | undefined;
const exclude: string[] = [];
let history = false;
let dashboard = false;
// First pass: extract --cwd or positional path so config loads from the right place
for (let i = 1; i < args.length; i++) {
if (args[i] === '--cwd' && args[i + 1]) { cwd = args[++i]; break; }
// Positional path: first arg after command that doesn't start with --
if (!args[i].startsWith('--') && !args[i].startsWith('-') && i === 1) {
cwd = args[i];
break;
}
}
// Load config file defaults from target directory
const config = loadConfig(cwd);
json = config.json ?? false;
recipe = config.recipe;
verbose = config.verbose ?? false;
reportTo = config.reportTo;
apiKey = config.apiKey;
if (config.exclude) exclude.push(...config.exclude);
// CLI flags override config. Helper to safely consume flag values.
const consumeValue = (flag: string, idx: number): string | undefined => {
const val = args[idx + 1];
if (!val || val.startsWith('--')) {
console.error(`${c.red('\u2716')} Missing value for ${flag}`);
return undefined;
}
return val;
};
for (let i = 1; i < args.length; i++) {
switch (args[i]) {
case '--json': json = true; break;
case '--check': { const v = consumeValue('--check', i); if (v) { check = v; i++; } break; }
case '--recipe': { const v = consumeValue('--recipe', i); if (v) { recipe = v; i++; } break; }
case '--cwd': i++; break; // already handled in first pass
case '--help': case '-h': help = true; break;
case '--list': list = true; break;
case '--recipes': listRecipes = true; break;
case '--verbose': case '-v': verbose = true; break;
case '--report-to': { const v = consumeValue('--report-to', i); if (v) { reportTo = v; i++; } break; }
case '--api-key': { const v = consumeValue('--api-key', i); if (v) { apiKey = v; i++; } break; }
case '--exclude': { const v = consumeValue('--exclude', i); if (v) { exclude.push(v); i++; } break; }
case '--history': history = true; break;
case '--dashboard': dashboard = true; break;
}
}
return { command, json, check, recipe, cwd, help, list, listRecipes, verbose, reportTo, apiKey, exclude, history, dashboard };
}
// =============================================================================
// LIST COMMANDS
// =============================================================================
async function listChecks(): Promise<void> {
await ensureChecksLoaded();
const checks = defaultRegistry.listEnabled();
const categories = new Map<string, Check[]>();
for (const check of checks) {
const cat = check.config.category ?? 'uncategorized';
const list = categories.get(cat) ?? [];
list.push(check);
categories.set(cat, list);
}
console.log(`\n${c.bold('Available Fitness Checks')} ${c.dim(`(${checks.length} total)`)}\n`);
for (const [category, catChecks] of [...categories.entries()].sort()) {
console.log(` ${c.cyan(category)} ${c.dim(`(${catChecks.length})`)}`);
for (const check of catChecks.sort((a, b) => a.config.slug.localeCompare(b.config.slug))) {
console.log(` ${check.config.slug} ${c.dim('—')} ${c.dim(check.config.description)}`);
}
console.log('');
}
}
function listRecipesFn(): void {
console.log(`\n${c.bold('Available Recipes')}\n`);
for (const [name, recipe] of builtInRecipesByName.entries()) {
const checkCount = recipe.checks.type === 'all'
? 'all checks'
: recipe.checks.type === 'explicit'
? `${(recipe.checks as unknown as { checkIds: string[] }).checkIds.length} checks`
: 'pattern-based';
console.log(` ${c.cyan(name)} ${c.dim('—')} ${recipe.description} ${c.dim(`(${checkCount})`)}`);
}
console.log('');
}
// =============================================================================
// HISTORY & DASHBOARD
// =============================================================================
function showHistory(): void {
const sessions = loadSessions();
if (sessions.length === 0) {
console.log(`\n ${c.dim('No sessions recorded yet. Run opensip-tools fit to generate data.')}\n`);
return;
}
console.log(`\n${c.bold('Run History')} ${c.dim(`(${sessions.length} sessions)`)}\n`);
for (const s of sessions.slice(0, 20)) {
const scoreColor = s.score >= 90 ? c.green : s.score >= 70 ? c.yellow : c.red;
const badge = s.passed ? c.green('PASS') : c.red('FAIL');
const date = new Date(s.timestamp).toLocaleString();
const recipe = s.recipe ? c.dim(` (${s.recipe})`) : '';
console.log(` ${c.dim(date)} ${scoreColor(`${s.score}%`)} ${badge} ${s.summary.passed}/${s.summary.total} checks${recipe} ${c.dim(`${(s.durationMs / 1000).toFixed(1)}s`)}`);
}
console.log('');
}
function openDashboard(): void {
const sessions = loadSessions(20);
const html = generateDashboardHtml(sessions);
const reportPath = join(getReportsDir(), 'latest.html');
writeFileSync(reportPath, html, 'utf-8');
console.log(`\n ${c.green('\u2713')} Report written to ${c.bold(reportPath)}`);
// Try to open in browser using execFile (no shell injection risk)
try {
const platform = process.platform;
if (platform === 'darwin') execFileSync('open', [reportPath]);
else if (platform === 'linux') execFileSync('xdg-open', [reportPath]);
else if (platform === 'win32') execFileSync('cmd', ['/c', 'start', '', reportPath]);
console.log(` ${c.dim('Opened in browser.')}\n`);
} catch {
console.log(` ${c.dim('Open the file in your browser to view.')}\n`);
}
}
// =============================================================================
// CONCURRENCY POOL
// =============================================================================
async function runWithConcurrency<T>(
items: T[],
fn: (item: T) => Promise<void>,
concurrency: number,
): Promise<void> {
const queue = [...items];
const workers = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
while (queue.length > 0) {
const item = queue.shift()!;
await fn(item);
}
});
await Promise.all(workers);
}
// =============================================================================
// FIT COMMAND
// =============================================================================
async function runFit(args: CliArgs): Promise<void> {
await ensureChecksLoaded();
const start = Date.now();
// Resolve which checks to run
let checks: Check[];
let recipeName: string | undefined;
if (args.check) {
checks = [defaultRegistry.get(args.check)];
} else if (args.recipe) {
const recipe = builtInRecipesByName.get(args.recipe);
if (!recipe) {
console.error(`\n ${c.red('\u2716')} Unknown recipe '${args.recipe}'.`);
console.error(` ${c.dim('Run opensip-tools fit --recipes to see available recipes.')}\n`);
process.exitCode = EXIT_CODES.CONFIGURATION_ERROR;
return;
}
recipeName = args.recipe;
const slugs = resolveChecks(recipe.checks, defaultRegistry);
checks = slugs.map(slug => defaultRegistry.get(slug));
} else {
checks = defaultRegistry.listEnabled();
}
// Apply exclusions
if (args.exclude.length > 0) {
checks = checks.filter(check => !args.exclude.includes(check.config.slug));
}
if (checks.length === 0) {
console.error(`\n ${c.red('\u2716')} No checks to run.`);
console.error(` ${c.dim('Ensure @opensip-tools/fitness is installed.')}\n`);
process.exitCode = EXIT_CODES.RUNTIME_ERROR;
return;
}
if (!args.json) {
printBanner();
const label = recipeName ? `recipe ${c.cyan(recipeName)}` : `${checks.length} checks`;
console.log(` ${c.bold('Fitness Checks')} ${c.dim('—')} running ${label}`);
console.log(` ${c.dim(args.cwd)}\n`);
}
// Run all checks in parallel with bounded concurrency
const CONCURRENCY = 8;
const results: { slug: string; category: string; result: CheckResult; error?: string }[] = new Array(checks.length);
await runWithConcurrency(
checks.map((check, index) => ({ check, index })),
async ({ check, index }) => {
const slug = check.config.slug;
const category = check.config.category ?? 'quality';
try {
const result = await check.run(args.cwd);
results[index] = { slug, category, result };
} catch (err) {
results[index] = {
slug,
category,
result: { passed: false, errors: 1, warnings: 0, signals: [], info: { label: 'Error' }, metadata: { totalItems: 0, signals: [] } },
error: err instanceof Error ? err.message : String(err),
};
}
},
CONCURRENCY,
);
// Print results in original order after all checks complete
if (!args.json) {
for (const r of results) {
const icon = r.result.passed ? c.green('\u2713') : c.red('\u2717');
const count = r.result.signals.length > 0 ? c.dim(` (${r.result.signals.length})`) : '';
const duration = r.result.metadata?.durationMs ? c.dim(` ${r.result.metadata.durationMs}ms`) : '';
const errorMsg = r.error ? c.red(` (error: ${r.error})`) : '';
console.log(` ${icon} ${r.slug}${count}${duration}${errorMsg}`);
// Show findings in verbose mode
if (args.verbose && r.result.signals.length > 0) {
for (const signal of r.result.signals.slice(0, 5)) {
const loc = signal.filePath ? c.dim(`${signal.filePath}${signal.line ? `:${signal.line}` : ''}`) : '';
console.log(` ${c.dim('\u2514')} ${signal.message} ${loc}`);
}
if (r.result.signals.length > 5) {
console.log(` ${c.dim(` ... and ${r.result.signals.length - 5} more`)}`);
}
}
}
}
// Compute summary
const passedCount = results.filter(r => r.result.passed).length;
const failedCount = results.filter(r => !r.result.passed).length;
const totalSignals = results.reduce((sum, r) => r.result.signals.length + sum, 0);
const errorCount = results.reduce((sum, r) => (r.result.errors ?? 0) + sum, 0);
const warningCount = results.reduce((sum, r) => (r.result.warnings ?? 0) + sum, 0);
const score = checks.length > 0 ? Math.round((passedCount / checks.length) * 100) : 0;
const durationMs = Date.now() - start;
// Build output
const output: CliOutput = {
version: '1.0',
tool: 'fit',
timestamp: new Date().toISOString(),
recipe: recipeName,
score,
passed: failedCount === 0,
summary: {
total: checks.length,
passed: passedCount,
failed: failedCount,
errors: errorCount,
warnings: warningCount,
},
checks: results.map(r => ({
checkSlug: r.slug,
passed: r.result.passed,
findings: r.result.signals.map(s => ({
ruleId: s.ruleId,
message: s.message,
severity: (s.severity === 'critical' || s.severity === 'high' ? 'error' : 'warning') as 'error' | 'warning',
filePath: s.filePath ?? s.code?.file,
line: s.line ?? s.code?.line,
column: s.column ?? s.code?.column,
suggestion: s.suggestion,
category: r.category,
})),
durationMs: r.result.metadata?.durationMs ?? 0,
})),
durationMs,
};
// Persist session for history and dashboard
try {
saveSession({
id: generateSessionId(),
tool: 'fit',
timestamp: output.timestamp,
cwd: args.cwd,
recipe: recipeName,
score,
passed: output.passed,
summary: output.summary,
checks: output.checks,
durationMs,
});
} catch {
// Best effort — don't fail the run if persistence fails
}
// Output
if (args.json) {
process.stdout.write(JSON.stringify(output, null, 2) + '\n');
} else {
const scoreColor = score >= 90 ? c.green : score >= 70 ? c.yellow : c.red;
console.log('');
console.log(` ${c.bold('Score:')} ${scoreColor(`${score}%`)} ${c.dim('|')} ${c.green(`${passedCount} passed`)} ${c.dim('|')} ${failedCount > 0 ? c.red(`${failedCount} failed`) : c.dim('0 failed')} ${c.dim('|')} ${totalSignals} findings ${c.dim('|')} ${c.dim(`${(durationMs / 1000).toFixed(1)}s`)}`);
console.log('');
}
// Cloud reporting
if (args.reportTo) {
await reportToCloud(output, args.reportTo, args.apiKey);
}
}
// =============================================================================
// CLOUD REPORTING
// =============================================================================
async function reportToCloud(output: CliOutput, url: string, apiKey?: string): Promise<void> {
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
if (apiKey) headers['X-API-Key'] = apiKey;
try {
const res = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify({
source: 'fitness',
signals: output.checks.flatMap(ch => ch.findings),
}),
signal: AbortSignal.timeout(10_000),
});
if (!res.ok) {
const body = await res.text().catch(() => '');
console.error(`${c.red('Report failed:')} ${res.status} ${res.statusText} ${c.dim(body)}`);
return;
}
const findingCount = output.checks.reduce((sum, ch) => sum + ch.findings.length, 0);
console.log(` ${c.green('\u2713')} Reported ${findingCount} findings to ${c.dim(url)}`);
} catch (err) {
console.error(`${c.red('Report failed:')} ${err instanceof Error ? err.message : String(err)}`);
}
}
// =============================================================================
// MAIN
// =============================================================================
const HELP = `
${c.bold('opensip-tools')} ${c.dim('\u2014 codebase analysis toolkit')}
${c.bold('Commands:')}
fit Run fitness checks
asm Run assessments (coming soon)
sim Run simulations (coming soon)
${c.bold('Options:')}
--cwd <path> Target directory (default: current directory)
--json Output structured JSON
--recipe <name> Use a named recipe (default, quick-smoke, backend, etc.)
--check <slug> Run a single check by slug
--list List available checks
--recipes List available recipes
--exclude <slug> Exclude a check (repeatable)
--verbose, -v Show finding details
--history Show run history
--dashboard Generate HTML report and open in browser
--report-to <url> POST findings to a URL (OpenSIP Cloud or compatible)
--api-key <key> API key for --report-to authentication
--help, -h Show this help message
${c.bold('Examples:')}
opensip-tools fit
opensip-tools fit /path/to/project
opensip-tools fit --recipe quick-smoke
opensip-tools fit --verbose
opensip-tools fit --json
opensip-tools fit --history
opensip-tools fit --dashboard
opensip-tools fit --check no-console-log
opensip-tools fit --list
`.trim();
async function main(): Promise<void> {
const args = parseArgs(process.argv);
if (args.help || args.command === 'help') {
console.log(HELP);
return;
}
switch (args.command) {
case 'fit':
if (args.list) { await listChecks(); return; }
if (args.listRecipes) { listRecipesFn(); return; }
if (args.history) { showHistory(); return; }
if (args.dashboard) { openDashboard(); return; }
await runFit(args);
break;
case 'asm':
console.log('Assessments coming soon.');
break;
case 'sim':
console.log('Simulations coming soon.');
break;
default:
console.log(HELP);
break;
}
}
// =============================================================================
// EXIT CODES
// =============================================================================
export const EXIT_CODES = {
SUCCESS: 0,
RUNTIME_ERROR: 1,
CONFIGURATION_ERROR: 2,
CHECK_NOT_FOUND: 3,
REPORT_FAILED: 4,
} as const;
// =============================================================================
// ERROR SUGGESTIONS
// =============================================================================
interface ErrorSuggestion {
message: string;
action?: string;
exitCode: number;
}
export function getErrorSuggestion(err: unknown): ErrorSuggestion | null {
const message = err instanceof Error ? err.message : String(err);
// Check not found
if (message.includes('Check not found:') || message.includes('not found')) {
const slug = message.match(/Check not found: (.+)/)?.[1] ?? message.match(/not found: (.+)/)?.[1];
return {
message: `Check '${slug ?? 'unknown'}' not found.`,
action: 'Run opensip-tools fit --list to see available checks.',
exitCode: EXIT_CODES.CHECK_NOT_FOUND,
};
}
// Recipe not found
if (message.includes('Unknown recipe')) {
return {
message: message,
action: 'Run opensip-tools fit --recipes to see available recipes.',
exitCode: EXIT_CODES.CONFIGURATION_ERROR,
};
}
// Config file error
if (message.includes('.opensip-tools.yml') || message.includes('YAML') || message.includes('config')) {
return {
message: 'Configuration error.',
action: 'Check .opensip-tools.yml for syntax errors.',
exitCode: EXIT_CODES.CONFIGURATION_ERROR,
};
}
// Permission denied
if (message.includes('EACCES') || message.includes('permission denied')) {
return {
message: 'Permission denied reading files.',
action: 'Check file permissions in the target directory.',
exitCode: EXIT_CODES.RUNTIME_ERROR,
};
}
// No files found
if (message.includes('No checks registered') || message.includes('No checks to run')) {
return {
message: 'No checks available to run.',
action: 'Ensure @opensip-tools/fitness is installed.',
exitCode: EXIT_CODES.RUNTIME_ERROR,
};
}
// Network error (report-to)
if (message.includes('fetch') || message.includes('ECONNREFUSED') || message.includes('network')) {
return {
message: 'Network error sending report.',
action: 'Check the --report-to URL and your network connection.',
exitCode: EXIT_CODES.REPORT_FAILED,
};
}
return null;
}
// =============================================================================
// TOP-LEVEL ERROR HANDLER
// =============================================================================
main().catch((err) => {
const suggestion = getErrorSuggestion(err);
if (suggestion) {
console.error(`\n ${c.red('\u2716')} ${suggestion.message}`);
if (suggestion.action) {
console.error(` ${c.dim(suggestion.action)}`);
}
console.error('');
process.exitCode = suggestion.exitCode;
} else {
// Unknown error — show message without stack trace
const message = err instanceof Error ? err.message : String(err);
console.error(`\n ${c.red('\u2716')} ${message}\n`);
process.exitCode = EXIT_CODES.RUNTIME_ERROR;
}
});
|