All files / src/cli/commands init.ts

75.14% Statements 127/169
58.13% Branches 50/86
88.88% Functions 16/18
78.12% Lines 125/160

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                                            4x                           45x       45x 45x         37x       37x 37x         8x     8x               14x                                                                                     14x 14x                                                                       15x 15x   15x                     39x 39x               39x 39x                       9x 9x       9x 9x   9x 9x   9x 18x   18x 18x   18x 18x     18x 18x 18x 18x         18x         18x 1x     18x 18x 18x     9x             30x 30x 30x 60x 60x             15x 15x 15x 15x 17x 17x 17x   14x                 10x 10x   2x     2x 2x 2x 2x         2x       2x 1x     2x 2x 2x             16x       16x 16x   1x 1x       15x   15x 15x     15x 15x 15x 1x   14x 14x 14x   15x     15x 15x 13x   15x 15x 15x 1x   14x 14x 14x   15x     15x 15x 15x           15x 1x 1x 14x 9x 9x 9x 9x 5x                               5x 5x   15x     15x 15x                                 15x 15x     15x         15x         15x 15x 15x 15x 15x     15x 15x       15x   15x    
import {
  cpSync,
  existsSync,
  lstatSync,
  mkdirSync,
  readdirSync,
  readFileSync,
  rmSync,
  symlinkSync,
  writeFileSync,
} from 'node:fs';
import { dirname, join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
import chalk from 'chalk';
import figures from 'figures';
import { getRepoRoot, getGitHubRepoUrl } from '../git.js';
import { readSingleKey } from '../input.js';
import { ICON_CHECK, ICON_SKIPPED } from '../output/icons.js';
import type { Reporter } from '../output/reporter.js';
import type { CLIOptions } from '../args.js';
import { getMajorVersion } from '../../utils/index.js';
 
const INSTALLABLE_BUNDLED_SKILLS = new Set([
  'warden',
  'warden-sweep',
]);
 
/**
 * Render a section heading in the init output.
 */
function renderSection(
  reporter: Reporter,
  title: string,
  filepath: string,
  description: string,
): void {
  Iif (reporter.mode.isTTY) {
    reporter.text(chalk.bold(title) + chalk.dim(`  ${filepath}`));
    reporter.text(`  ${chalk.dim(description)}`);
  } else {
    reporter.text(`${title}: ${filepath}`);
    reporter.text(`  ${description}`);
  }
}
 
function renderCreated(reporter: Reporter, detail?: string): void {
  Iif (reporter.mode.isTTY) {
    const suffix = detail ? ` ${chalk.dim(detail)}` : '';
    reporter.text(`  ${chalk.green(ICON_CHECK)} Created${suffix}`);
  } else {
    const suffix = detail ? ` ${detail}` : '';
    reporter.text(`  Created${suffix}`);
  }
}
 
function renderSkipped(reporter: Reporter, reason: string): void {
  Iif (reporter.mode.isTTY) {
    reporter.text(`  ${chalk.yellow(ICON_SKIPPED)} Skipped ${chalk.dim(`(${reason})`)}`);
  } else {
    reporter.text(`  Skipped (${reason})`);
  }
}
 
/**
 * Template for warden.toml configuration file.
 */
function generateWardenToml(): string {
  return `# Warden Configuration
# https://github.com/getsentry/warden
#
# Warden reviews code using AI-powered skills triggered by GitHub events.
# Built-in skills are available by name. Add more skills as needed.
#
# Add built-in reviews with:
#   warden add security-review
#   warden add code-review
 
version = 1
 
# Default settings inherited by all skills
[defaults]
runtime = "pi"
# Severity levels: critical, high, medium, low, info
# failOn: minimum severity that fails the check
failOn = "high"
# reportOn: minimum severity that creates PR annotations
reportOn = "medium"
 
# Skills define what to analyze and when to run
# Add built-in reviews with:
#   warden add security-review
#   warden add code-review
#
# Example skill with path filters and triggers:
#
# [[skills]]
# name = "security-review"
# paths = ["src/**/*.ts", "src/**/*.tsx"]
# ignorePaths = ["**/*.test.ts", "**/__fixtures__/**"]
#
# [[skills.triggers]]
# type = "pull_request"
# actions = ["opened", "synchronize", "reopened"]
`;
}
 
/**
 * Template for GitHub Actions workflow file.
 */
function generateWorkflowYaml(): string {
  const majorVersion = getMajorVersion();
  return `name: Warden
 
on:
  pull_request:
    types: [opened, synchronize, reopened]
 
# contents: write required for resolving review threads via GraphQL
# See: https://github.com/orgs/community/discussions/44650
permissions:
  contents: write
  pull-requests: write
  checks: write
 
jobs:
  review:
    runs-on: ubuntu-latest
    env:
      WARDEN_MODEL: \${{ secrets.WARDEN_MODEL }}
      WARDEN_SENTRY_DSN: \${{ secrets.WARDEN_SENTRY_DSN }}
      WARDEN_OPENAI_API_KEY: \${{ secrets.WARDEN_OPENAI_API_KEY }}
      WARDEN_ANTHROPIC_API_KEY: \${{ secrets.WARDEN_ANTHROPIC_API_KEY }}
    steps:
      - uses: actions/checkout@v4
        with:
          ref: \${{ github.event.pull_request.head.sha }}
      - uses: getsentry/warden@v${majorVersion}
`;
}
 
/**
 * Check for existing warden configuration files.
 */
function checkExistingFiles(repoRoot: string): {
  hasWardenToml: boolean;
  hasWorkflow: boolean;
} {
  const wardenTomlPath = join(repoRoot, 'warden.toml');
  const workflowPath = join(repoRoot, '.github', 'workflows', 'warden.yml');
 
  return {
    hasWardenToml: existsSync(wardenTomlPath),
    hasWorkflow: existsSync(workflowPath),
  };
}
 
/**
 * Resolve the warden package root directory from the compiled/source location.
 * Works from both src/cli/commands/init.ts and dist/cli/commands/init.js (3 levels up).
 */
function resolvePackageRoot(): string {
  const __filename = fileURLToPath(import.meta.url);
  return join(dirname(__filename), '..', '..', '..');
}
 
/**
 * Resolve the bundled skills directory shipped with the warden package.
 * Returns null if the directory doesn't exist (e.g., running from a non-standard location).
 */
function resolveBundledSkillsDir(): string | null {
  const dir = join(resolvePackageRoot(), 'skills');
  return existsSync(dir) ? dir : null;
}
 
/**
 * Install bundled skills into .agents/skills/.
 * Skips skills that already exist unless force is true.
 */
function installBundledSkills(
  repoRoot: string,
  force: boolean,
  reporter: Reporter,
): number {
  const bundledDir = resolveBundledSkillsDir();
  Iif (!bundledDir) {
    return 0;
  }
 
  const targetDir = join(repoRoot, '.agents', 'skills');
  mkdirSync(targetDir, { recursive: true });
 
  let installed = 0;
  const entries = readdirSync(bundledDir, { withFileTypes: true });
 
  for (const entry of entries) {
    Iif (!entry.isDirectory()) continue;
 
    const skillName = entry.name;
    Iif (!INSTALLABLE_BUNDLED_SKILLS.has(skillName)) continue;
 
    const src = join(bundledDir, skillName);
    const dest = join(targetDir, skillName);
 
    // Check if destination exists (as file, dir, or symlink)
    let destExists = false;
    try {
      lstatSync(dest);
      destExists = true;
    } catch {
      // doesn't exist
    }
 
    Iif (destExists && !force) {
      continue;
    }
 
    // Remove first to handle symlinks cleanly (cpSync would follow them)
    if (destExists) {
      rmSync(dest, { recursive: true, force: true });
    }
 
    cpSync(src, dest, { recursive: true });
    reporter.text(`  ${chalk.dim(`.agents/skills/${skillName}`)}`);
    installed++;
  }
 
  return installed;
}
 
/**
 * List bundled skill names that would be installed.
 */
function listBundledSkillNames(): string[] {
  const bundledDir = resolveBundledSkillsDir();
  Iif (!bundledDir) return [];
  return readdirSync(bundledDir, { withFileTypes: true })
    .filter((e) => e.isDirectory() && INSTALLABLE_BUNDLED_SKILLS.has(e.name))
    .map((e) => e.name);
}
 
/**
 * Check if any bundled skills are already installed.
 */
function allSkillsInstalled(repoRoot: string): boolean {
  const names = listBundledSkillNames();
  Iif (names.length === 0) return true;
  const targetDir = join(repoRoot, '.agents', 'skills');
  return names.every((name) => {
    try {
      lstatSync(join(targetDir, name));
      return true;
    } catch {
      return false;
    }
  });
}
 
/**
 * Ensure .claude/skills symlink points to ../.agents/skills if .claude/ exists.
 */
function ensureClaudeSymlink(repoRoot: string, force: boolean, reporter: Reporter): boolean {
  const claudeDir = join(repoRoot, '.claude');
  if (!existsSync(claudeDir)) return false;
 
  const skillsLink = join(claudeDir, 'skills');
 
  // Check if it already exists (file, dir, or symlink — including broken symlinks)
  let linkExists = false;
  try {
    lstatSync(skillsLink);
    linkExists = true;
  } catch {
    // Doesn't exist
  }
 
  Iif (linkExists && !force) {
    return false;
  }
 
  if (linkExists) {
    rmSync(skillsLink, { recursive: true, force: true });
  }
 
  symlinkSync('../.agents/skills', skillsLink);
  reporter.text(`  ${chalk.dim('.claude/skills -> ../.agents/skills')}`);
  return true;
}
 
/**
 * Run the init command to scaffold warden configuration.
 */
export async function runInit(options: CLIOptions, reporter: Reporter): Promise<number> {
  const cwd = process.cwd();
 
  // Find repo root
  let repoRoot: string;
  try {
    repoRoot = getRepoRoot(cwd);
  } catch {
    reporter.error('Not a git repository. Run this command from a git repository.');
    return 1;
  }
 
  // Check for existing files
  const existing = checkExistingFiles(repoRoot);
 
  let filesCreated = 0;
  let skillsSkipped = false;
 
  // --- CONFIG section ---
  const wardenTomlPath = join(repoRoot, 'warden.toml');
  renderSection(reporter, 'CONFIG', relative(cwd, wardenTomlPath), 'Severity thresholds and skill settings');
  if (existing.hasWardenToml && !options.force) {
    renderSkipped(reporter, 'already exists');
  } else {
    writeFileSync(wardenTomlPath, generateWardenToml(), 'utf-8');
    renderCreated(reporter);
    filesCreated++;
  }
  reporter.blank();
 
  // --- WORKFLOW section ---
  const workflowDir = join(repoRoot, '.github', 'workflows');
  if (!existsSync(workflowDir)) {
    mkdirSync(workflowDir, { recursive: true });
  }
  const workflowPath = join(workflowDir, 'warden.yml');
  renderSection(reporter, 'WORKFLOW', relative(cwd, workflowPath), 'Runs Warden on pull requests via GitHub Actions');
  if (existing.hasWorkflow && !options.force) {
    renderSkipped(reporter, 'already exists');
  } else {
    writeFileSync(workflowPath, generateWorkflowYaml(), 'utf-8');
    renderCreated(reporter);
    filesCreated++;
  }
  reporter.blank();
 
  // --- SKILLS section ---
  const skillNames = listBundledSkillNames();
  const skillPath = join(repoRoot, '.agents', 'skills');
  renderSection(
    reporter,
    'SKILLS',
    relative(cwd, skillPath),
    `Bundled skills for AI agents (${skillNames.join(', ')})`,
  );
  if (allSkillsInstalled(repoRoot) && !options.force) {
    Iif (ensureClaudeSymlink(repoRoot, false, reporter)) filesCreated++;
    renderSkipped(reporter, 'already installed');
  } else if (options.force) {
    const count = installBundledSkills(repoRoot, true, reporter);
    if (ensureClaudeSymlink(repoRoot, true, reporter)) filesCreated++;
    renderCreated(reporter);
    filesCreated += count;
  I} else if (reporter.mode.isTTY && process.stdin.isTTY) {
    process.stderr.write(`  ${chalk.cyan(figures.arrowRight)} Install? ${chalk.dim('[Y/n]')} `);
    const key = await readSingleKey();
    process.stderr.write(key === '\r' || key === '\n' ? 'y' : key);
    process.stderr.write('\n');
 
    if (key.toLowerCase() !== 'n') {
      const count = installBundledSkills(repoRoot, false, reporter);
      if (ensureClaudeSymlink(repoRoot, false, reporter)) filesCreated++;
      renderCreated(reporter);
      filesCreated += count;
    } else {
      skillsSkipped = true;
      renderSkipped(reporter, 'declined');
    }
  } else {
    skillsSkipped = true;
    renderSkipped(reporter, 'non-interactive');
  }
  reporter.blank();
 
  // Ensure .warden/ is in .gitignore (silent housekeeping)
  const gitignorePath = join(repoRoot, '.gitignore');
  Iif (existsSync(gitignorePath)) {
    const gitignoreContent = readFileSync(gitignorePath, 'utf-8');
    const lines = gitignoreContent.split('\n');
    const hasWardenEntry = lines.some((line) => {
      const trimmed = line.trim();
      return trimmed === '.warden/' || trimmed === '.warden';
    });
    if (!hasWardenEntry) {
      // Remove old specific entries that are superseded by .warden/
      const oldPatterns = new Set(['.warden/logs/', '.warden/logs', '.warden/sessions/', '.warden/sessions']);
      const cleaned = lines.filter((line) => !oldPatterns.has(line.trim()));
      const cleanedContent = cleaned.join('\n');
      const newline = cleanedContent.endsWith('\n') ? '' : '\n';
      writeFileSync(gitignorePath, cleanedContent + newline + '.warden/\n', 'utf-8');
      filesCreated++;
    }
  } else {
    writeFileSync(gitignorePath, '.warden/\n', 'utf-8');
    filesCreated++;
  }
 
  Iif (filesCreated === 0 && !skillsSkipped) {
    reporter.tip('All configuration files already exist. Use --force to overwrite.');
    return 0;
  }
 
  Iif (filesCreated === 0) {
    return 0;
  }
 
  // Print next steps
  reporter.bold('Next steps:');
  reporter.text(`  1. Add built-in reviews: ${chalk.cyan('warden add security-review')}`);
  reporter.text(`     ${chalk.cyan('warden add code-review')}`);
  reporter.text(`  2. Set ${chalk.cyan('WARDEN_MODEL')} and the WARDEN-prefixed provider API key for that model`);
  reporter.text(`  3. Add the same values to organization or repository secrets`);
 
  // Show GitHub secrets URL if available
  const githubUrl = getGitHubRepoUrl(repoRoot);
  Iif (githubUrl) {
    reporter.text(`     ${chalk.dim(githubUrl + '/settings/secrets/actions')}`);
  }
 
  reporter.text('  4. Commit and open a PR to test');
 
  return 0;
}