Skip to content

SIDDARTHA577/envguard-node / .agents/skills/envguard-load-test

envguard-load-test

Verified

Guides capacity planning, workload profile design, local performance benchmarking, and threshold validation without fabricating production metrics or executing unauthorized traffic.

FileKindSize
SKILL.mdskill md7.7 KB
scripts/readiness-auditor.mjsscript27.1 KB
scripts/readiness/adapters/android-adapter.mjsscript30.0 KB
scripts/readiness/adapters/base-adapter.mjsscript4.6 KB
scripts/readiness/adapters/flutter-adapter.mjsscript28.9 KB
scripts/readiness/adapters/generic-adapter.mjsscript15.9 KB
scripts/readiness/adapters/index.mjsscript661 B
scripts/readiness/adapters/ios-adapter.mjsscript21.0 KB
scripts/readiness/adapters/java-spring-adapter.mjsscript39.9 KB
scripts/readiness/adapters/nextjs-react-adapter.mjsscript30.5 KB
scripts/readiness/adapters/node-typescript-adapter.mjsscript115.8 KB
scripts/readiness/adapters/python-adapter.mjsscript44.0 KB
scripts/readiness/adapters/react-native-adapter.mjsscript34.6 KB
scripts/readiness/adapters/registry.mjsscript3.7 KB
scripts/readiness/architecture/applicability.mjsscript21.8 KB
scripts/readiness/architecture/architecture-inventory.mjsscript16.9 KB
scripts/readiness/architecture/architecture-reporter.mjsscript9.4 KB
scripts/readiness/architecture/capacity-model.mjsscript16.9 KB
scripts/readiness/architecture/design-decisions.mjsscript42.0 KB
scripts/readiness/architecture/failure-modes.mjsscript13.3 KB
scripts/readiness/architecture/index.mjsscript895 B
scripts/readiness/architecture/requirements.mjsscript22.0 KB
scripts/readiness/architecture/tradeoffs.mjsscript4.5 KB
scripts/readiness/capacity/benchmark-runner.mjsscript13.4 KB
scripts/readiness/constants.mjsscript6.0 KB
scripts/readiness/deployment/cicd-gate-validator.mjsscript6.1 KB
scripts/readiness/deployment/container-validator.mjsscript10.1 KB
scripts/readiness/deployment/deployment-gate.mjsscript4.8 KB
scripts/readiness/deployment/index.mjsscript411 B
scripts/readiness/deployment/k8s-validator.mjsscript8.8 KB
scripts/readiness/deployment/reliability-validator.mjsscript9.4 KB
scripts/readiness/engine/discovery.mjsscript15.4 KB
scripts/readiness/engine/index.mjsscript341 B
scripts/readiness/engine/orchestrator.mjsscript21.0 KB
scripts/readiness/engine/planner.mjsscript4.2 KB
scripts/readiness/engine/sarif.mjsscript12.7 KB
scripts/readiness/engine/skills-selector.mjsscript10.0 KB
scripts/readiness/execution/git.mjsscript2.3 KB
scripts/readiness/execution/runner.mjsscript11.9 KB
scripts/readiness/index.mjsscript516 B
scripts/readiness/orchestration/engineering-workflow.mjsscript18.5 KB
scripts/readiness/orchestration/index.mjsscript170 B
scripts/readiness/policies/index.mjsscript189 B
scripts/readiness/policies/release-policy.mjsscript9.5 KB
scripts/readiness/remediation/checkpoint-manager.mjsscript34.0 KB
scripts/readiness/remediation/diff-viewer.mjsscript2.5 KB
scripts/readiness/remediation/index.mjsscript778 B
scripts/readiness/remediation/patch-generator.mjsscript17.5 KB
scripts/readiness/remediation/remediation-runner.mjsscript9.9 KB
scripts/readiness/reporters/comparator.mjsscript20.7 KB
scripts/readiness/reporters/index.mjsscript293 B
scripts/readiness/reporters/json-reporter.mjsscript193 B
scripts/readiness/reporters/markdown-reporter.mjsscript18.8 KB
scripts/readiness/validation/evidence-matrix.mjsscript21.5 KB
scripts/readiness/validation/independent-app-runner.mjsscript26.2 KB
scripts/readiness/validation/index.mjsscript328 B

scripts/readiness-auditor.mjs

View on GitHub
#!/usr/bin/env node

/**
 * EnvGuard Production Readiness Auditor CLI & Ecosystem Engine.
 * Multi-Platform Evidence-Based Application Production Readiness Analyzer.
 */

import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import {
  TOOL_VERSION,
  REPORT_SCHEMA_VERSION,
  EXIT_CODES,
  VALID_CATEGORIES,
  VALID_STATUSES,
  TEST_VERIFICATION_STATES,
  VALID_FORMATS,
  IGNORED_DIRECTORIES,
  stripAnsi,
  sanitizeOutput,
  escapeMarkdown,
  assertSafeProjectDir,
  assertSafeOutputDir,
  collectProjectFiles,
  parseYamlFallback,
  isEnvironmentIsolated,
  detectContainerEnvironment,
  TRUST_MODELS,
  validateWorkingDirectory,
  buildSanitizedEnv,
  runProjectCommand,
  previewExecutionCommands,
  checkGitTracking,
  parseGitignoreRules,
  isPathIgnoredByRules,
  buildInventoryGraph,
  runReadinessAudit,
  runOrchestratedPipeline,
  WORKFLOW_STATES,
  selectSkillsForProject,
  SKILL_PRIORITIES,
  formulateAssessmentPlan,
  BaseAdapter,
  GenericAdapter,
  NodeTypeScriptAdapter,
  NextJsReactAdapter,
  PythonAdapter,
  JavaSpringBootAdapter,
  ReactNativeAdapter,
  FlutterAdapter,
  AndroidAdapter,
  IosAdapter,
  AdapterRegistry,
  createDefaultRegistry,
  evaluateReleasePolicy,
  POLICY_OUTCOMES,
  DEFAULT_MANDATORY_CHECKS,
  DEFAULT_BLOCKING_CATEGORIES,
  DEFAULT_BLOCKING_SEVERITIES,
  checkWaiver,
  formatJsonReport,
  generateMarkdownReport,
  generateProfessionalEngineeringReport,
  validateReportSchema,
  getFindingKey,
  compareReadinessReports,
  formatComparisonMarkdown,
  buildArchitectureInventory,
  discoverArchitectureRequirements,
  REQUIREMENT_SOURCES,
  REQUIREMENT_STATUS,
  REQUIREMENT_CONFIDENCE,
  validateRequirementsConfig,
  loadProjectRequirementsFile,
  evaluateApplicability,
  APPLICABILITY_LEVELS,
  evaluateSystemDesignDecisions,
  SYSTEM_DESIGN_CONCEPTS,
  evaluateArchitectureTradeoffs,
  analyzeFailureModes,
  buildCapacityModel,
  generate10kVirtualUserScenario,
  CAPACITY_RESULT_CATEGORIES,
  validateCapacityInputs,
  generateArchitectureDecisionRecords,
  formatArchitectureMarkdown,
  runLocalBenchmark,
  generateUnifiedDiff,
  discoverEnvVarNames,
  discoverTestFramework,
  buildSafeGitignoreContent,
  generateRemediationPatches,
  assertSafeProjectRelativePath,
  resolveCanonicalProjectRoot,
  computeManifestIntegrityHash,
  inspectBackupPermissionSecurity,
  createCheckpoint,
  finalizeCheckpointPostApply,
  loadCheckpointManifest,
  restoreCheckpoint,
  cleanupCheckpoints,
  REMEDIATION_STATUSES,
  detectPreApplyConflicts,
  executeRemediationWorkflow,
  validateContainerSetup,
  validateKubernetesManifests,
  validateCicdDeploymentGates,
  validateOperationalReliability,
  evaluateDeploymentGate,
  DEPLOYMENT_GATE_VERDICTS,
  DEPLOYMENT_EXECUTION_GUARD,
} from './readiness/index.mjs';

export {
  TOOL_VERSION,
  REPORT_SCHEMA_VERSION,
  EXIT_CODES,
  VALID_CATEGORIES,
  VALID_STATUSES,
  TEST_VERIFICATION_STATES,
  VALID_FORMATS,
  IGNORED_DIRECTORIES,
  stripAnsi,
  sanitizeOutput,
  escapeMarkdown,
  assertSafeProjectDir,
  assertSafeOutputDir,
  collectProjectFiles,
  parseYamlFallback,
  isEnvironmentIsolated,
  detectContainerEnvironment,
  TRUST_MODELS,
  validateWorkingDirectory,
  buildSanitizedEnv,
  runProjectCommand,
  previewExecutionCommands,
  checkGitTracking,
  parseGitignoreRules,
  isPathIgnoredByRules,
  buildInventoryGraph,
  runReadinessAudit,
  runOrchestratedPipeline,
  WORKFLOW_STATES,
  selectSkillsForProject,
  SKILL_PRIORITIES,
  formulateAssessmentPlan,
  BaseAdapter,
  GenericAdapter,
  NodeTypeScriptAdapter,
  NextJsReactAdapter,
  PythonAdapter,
  JavaSpringBootAdapter,
  ReactNativeAdapter,
  FlutterAdapter,
  AndroidAdapter,
  IosAdapter,
  AdapterRegistry,
  createDefaultRegistry,
  evaluateReleasePolicy,
  POLICY_OUTCOMES,
  DEFAULT_MANDATORY_CHECKS,
  DEFAULT_BLOCKING_CATEGORIES,
  DEFAULT_BLOCKING_SEVERITIES,
  checkWaiver,
  formatJsonReport,
  generateMarkdownReport,
  generateProfessionalEngineeringReport,
  validateReportSchema,
  getFindingKey,
  compareReadinessReports,
  formatComparisonMarkdown,
  buildArchitectureInventory,
  discoverArchitectureRequirements,
  REQUIREMENT_SOURCES,
  REQUIREMENT_STATUS,
  REQUIREMENT_CONFIDENCE,
  validateRequirementsConfig,
  loadProjectRequirementsFile,
  evaluateApplicability,
  APPLICABILITY_LEVELS,
  evaluateSystemDesignDecisions,
  SYSTEM_DESIGN_CONCEPTS,
  evaluateArchitectureTradeoffs,
  analyzeFailureModes,
  buildCapacityModel,
  generate10kVirtualUserScenario,
  CAPACITY_RESULT_CATEGORIES,
  validateCapacityInputs,
  generateArchitectureDecisionRecords,
  formatArchitectureMarkdown,
  runLocalBenchmark,
  generateUnifiedDiff,
  discoverEnvVarNames,
  discoverTestFramework,
  buildSafeGitignoreContent,
  generateRemediationPatches,
  assertSafeProjectRelativePath,
  resolveCanonicalProjectRoot,
  computeManifestIntegrityHash,
  inspectBackupPermissionSecurity,
  createCheckpoint,
  finalizeCheckpointPostApply,
  loadCheckpointManifest,
  restoreCheckpoint,
  cleanupCheckpoints,
  REMEDIATION_STATUSES,
  detectPreApplyConflicts,
  executeRemediationWorkflow,
  validateContainerSetup,
  validateKubernetesManifests,
  validateCicdDeploymentGates,
  validateOperationalReliability,
  evaluateDeploymentGate,
  DEPLOYMENT_GATE_VERDICTS,
  DEPLOYMENT_EXECUTION_GUARD,
};

// Backward-compatible individual check wrappers
export function checkProjectDiscovery(projectDir, files, pkg) {
  const adapter = new NodeTypeScriptAdapter();
  return adapter.runStaticChecks({ path: '.', absPath: projectDir, manifest: pkg, type: 'backend', isRoot: true }, { projectDir, files }).filter((f) => f.category === 'discovery');
}

export function checkEnvConfiguration(projectDir, files, pkg) {
  const generic = new GenericAdapter();
  const nodeAdapter = new NodeTypeScriptAdapter();
  const target = { path: '.', absPath: projectDir, manifest: pkg, type: 'backend', isRoot: true };
  const context = { projectDir, files };
  return [
    ...nodeAdapter.runStaticChecks(target, context).filter((f) => f.category === 'env' && f.id === 'ENV-001'),
    ...generic.runStaticChecks(target, context).filter((f) => f.category === 'env' && f.id === 'ENV-002'),
    ...nodeAdapter.runStaticChecks(target, context).filter((f) => f.category === 'env' && f.id === 'ENV-003'),
    ...generic.runStaticChecks(target, context).filter((f) => f.category === 'env' && f.id === 'ENV-004'),
  ];
}

export function checkBuildAndTest(projectDir, pkg, allowExec, timeoutMs, options = {}) {
  const adapter = new NodeTypeScriptAdapter();
  const target = { path: '.', absPath: projectDir, manifest: pkg, type: 'backend', isRoot: true };
  const context = { projectDir, allowExec, timeoutMs, ...options };
  return adapter.runDynamicChecks(target, context, runProjectCommand);
}

export function checkSecurityReadiness(projectDir, files, pkg) {
  const generic = new GenericAdapter();
  const nodeAdapter = new NodeTypeScriptAdapter();
  const target = { path: '.', absPath: projectDir, manifest: pkg, type: 'backend', isRoot: true };
  const context = { projectDir, files };
  return [
    ...generic.runStaticChecks(target, context).filter((f) => f.category === 'security'),
    ...nodeAdapter.runStaticChecks(target, context).filter((f) => f.category === 'security'),
  ];
}

export function checkApiReadiness(projectDir, files, allowExec) {
  const nodeAdapter = new NodeTypeScriptAdapter();
  const target = { path: '.', absPath: projectDir, manifest: null, type: 'backend', isRoot: true };
  const context = { projectDir, files, allowExec };
  return nodeAdapter.runStaticChecks(target, context).filter((f) => f.category === 'api');
}

export function checkDatabaseReadiness(projectDir, files, pkg) {
  const nodeAdapter = new NodeTypeScriptAdapter();
  const target = { path: '.', absPath: projectDir, manifest: pkg, type: 'backend', isRoot: true };
  const context = { projectDir, files };
  return nodeAdapter.runStaticChecks(target, context).filter((f) => f.category === 'database');
}

export function checkDeploymentReadiness(projectDir, files) {
  const generic = new GenericAdapter();
  const nodeAdapter = new NodeTypeScriptAdapter();
  const target = { path: '.', absPath: projectDir, manifest: null, type: 'backend', isRoot: true };
  const context = { projectDir, files };
  return [
    ...generic.runStaticChecks(target, context).filter((f) => f.category === 'deployment' && f.id === 'DEP-001'),
    ...nodeAdapter.runStaticChecks(target, context).filter((f) => f.category === 'deployment'),
    ...generic.runStaticChecks(target, context).filter((f) => f.category === 'deployment' && f.id === 'DEP-004'),
    ...validateContainerSetup(projectDir, files),
    ...validateKubernetesManifests(projectDir, files),
    ...validateCicdDeploymentGates(projectDir, files),
    ...validateOperationalReliability(projectDir, files),
  ];
}

export function checkAccessibility(files, pkg) {
  const nodeAdapter = new NodeTypeScriptAdapter();
  const target = { path: '.', absPath: '.', manifest: pkg, type: 'frontend', isRoot: true };
  const context = { projectDir: '.', files };
  return nodeAdapter.runStaticChecks(target, context).filter((f) => f.category === 'accessibility');
}

export function checkPerformance(files, pkg) {
  const nodeAdapter = new NodeTypeScriptAdapter();
  const target = { path: '.', absPath: '.', manifest: pkg, type: 'backend', isRoot: true };
  const context = { projectDir: '.', files };
  return nodeAdapter.runStaticChecks(target, context).filter((f) => f.category === 'performance');
}

/**
 * Command-line CLI entry point.
 */
export function main(argv = process.argv.slice(2)) {
  let projectDir = '.';
  let outputDir = null;
  let format = null;
  let categories = [...VALID_CATEGORIES];
  let allowExec = false;
  let trustProject = false;
  let allowCrossProject = false;
  let previewCommands = false;
  let orchestrate = false;
  let remediate = false;
  let applyFix = false;
  let deploymentGate = false;
  let execCommands = null;
  let timeoutMs = 10000;
  let sarifPath = null;
  let compareFiles = null;

  for (let i = 0; i < argv.length; i++) {
    const arg = argv[i];
    if (arg === '--help' || arg === '-h') {
      console.log(`
EnvGuard Readiness Auditor v${TOOL_VERSION}
Evidence-based application production readiness analyzer.

Usage:
  node tools/readiness-auditor.mjs [scan] [options]
  node tools/readiness-auditor.mjs --compare <before.json> <after.json> [options]

Options:
  --project <dir>          Path to project directory (default: current directory)
  --output-dir <dir>       Directory to write assessment reports (JSON and Markdown)
  --format <type>          Output format: "json", "markdown", or "both" (default: "both" if --output-dir, else console)
  --checks <list>          Comma-separated list of check categories to run:
                           discovery, env, build_test, security, api, database, deployment, accessibility, performance
  --allow-exec             Explicitly authorize local project build and test command execution (default: read-only)
  --trust-project          Explicitly acknowledge executing scripts on unisolated host without container containment
  --exec-commands <list>   Comma-separated list of allowed scripts to execute (e.g. "test,build")
  --orchestrate            Run complete Senior Engineering Agent autonomous orchestration workflow
  --remediate              Formulate reviewable remediation patches and unified diffs without modifying files
  --apply-fix              Apply approved remediation patches with automated rollback checkpoints and retesting
  --deployment-gate        Evaluate comprehensive deployment readiness gate across containers, k8s, and reliability
  --preview-commands       Preview planned commands and their network/filesystem effects without running them
  --compare <b.json> <a.json>  Compare before vs after readiness reports to verify remediation
  --sarif <file>           Path to SARIF report to import static analysis findings (CodeQL, ESLint, Trivy)
  --timeout <ms>           Maximum execution time per command in ms (default: 10000, max: 120000)
  --help, -h               Show this help message

Exit Codes:
  0 - Success (assessment completed with zero policy blockers)
  1 - Tool error (internal unhandled exception)
  2 - Policy blockers exist (one or more BLOCKER/CRITICAL failures)
  3 - Invalid arguments (CLI options error)
  4 - Incomplete execution (critical command timed out or crashed)

Safety Boundaries:
  - Read-only by default. Does NOT run project scripts without --allow-exec.
  - Requires container containment or explicit --trust-project to execute scripts.
  - Minimizes environment variables and redacts secrets from output.
  - Never automatically publishes, deploys, or alters production databases.
`);
      return EXIT_CODES.SUCCESS_NO_BLOCKERS;
    } else if (arg === 'scan') {
      // optional subcommand keyword
    } else if (arg === '--compare') {
      const beforeVal = argv[++i];
      const afterVal = argv[++i];
      if (!beforeVal || beforeVal.startsWith('--') || !afterVal || afterVal.startsWith('--')) {
        console.error('Error: Option "--compare" requires two JSON report file paths: <before-report.json> <after-report.json>.');
        return EXIT_CODES.INVALID_ARGUMENTS;
      }
      compareFiles = [beforeVal, afterVal];
    } else if (arg === '--project') {
      const val = argv[++i];
      if (!val || val.startsWith('--')) {
        console.error('Error: Option "--project" requires a directory path.');
        return EXIT_CODES.INVALID_ARGUMENTS;
      }
      projectDir = val;
    } else if (arg === '--output-dir') {
      const val = argv[++i];
      if (!val || val.startsWith('--')) {
        console.error('Error: Option "--output-dir" requires a directory path.');
        return EXIT_CODES.INVALID_ARGUMENTS;
      }
      outputDir = val;
    } else if (arg === '--format') {
      const val = argv[++i]?.toLowerCase();
      if (!val || !VALID_FORMATS.includes(val)) {
        console.error(`Error: Invalid format "${val}". Supported formats: ${VALID_FORMATS.join(', ')}.`);
        return EXIT_CODES.INVALID_ARGUMENTS;
      }
      format = val;
    } else if (arg === '--checks') {
      const val = argv[++i];
      if (!val || val.startsWith('--')) {
        console.error('Error: Option "--checks" requires a comma-separated list of categories.');
        return EXIT_CODES.INVALID_ARGUMENTS;
      }
      const specified = val.split(',').map((s) => s.trim().toLowerCase()).filter(Boolean);
      if (specified.length === 0) {
        console.error('Error: Empty check category list provided.');
        return EXIT_CODES.INVALID_ARGUMENTS;
      }
      for (const cat of specified) {
        if (!VALID_CATEGORIES.includes(cat)) {
          console.error(`Error: Invalid check category "${cat}". Valid options: ${VALID_CATEGORIES.join(', ')}.`);
          return EXIT_CODES.INVALID_ARGUMENTS;
        }
      }
      categories = specified;
    } else if (arg === '--allow-exec') {
      allowExec = true;
    } else if (arg === '--trust-project') {
      trustProject = true;
    } else if (arg === '--preview-commands') {
      previewCommands = true;
    } else if (arg === '--orchestrate') {
      orchestrate = true;
    } else if (arg === '--remediate') {
      remediate = true;
    } else if (arg === '--apply-fix') {
      applyFix = true;
      remediate = true;
    } else if (arg === '--deployment-gate') {
      deploymentGate = true;
    } else if (arg === '--allow-cross-project') {
      allowCrossProject = true;
    } else if (arg === '--sarif') {
      const val = argv[++i];
      if (!val || val.startsWith('--')) {
        console.error('Error: Option "--sarif" requires a file path.');
        return EXIT_CODES.INVALID_ARGUMENTS;
      }
      sarifPath = val;
    } else if (arg === '--exec-commands') {
      const val = argv[++i];
      if (!val || val.startsWith('--')) {
        console.error('Error: Option "--exec-commands" requires a comma-separated list of script names.');
        return EXIT_CODES.INVALID_ARGUMENTS;
      }
      execCommands = val.split(',').map((s) => s.trim().toLowerCase()).filter(Boolean);
    } else if (arg === '--timeout') {
      const val = argv[++i];
      const parsedTimeout = parseInt(val, 10);
      if (Number.isNaN(parsedTimeout) || parsedTimeout < 100 || parsedTimeout > 120000) {
        console.error(`Error: Invalid timeout value "${val}". Must be an integer between 100 and 120000 ms.`);
        return EXIT_CODES.INVALID_ARGUMENTS;
      }
      timeoutMs = parsedTimeout;
    } else {
      console.error(`Error: Unrecognized option "${arg}". Run with --help for valid options.`);
      return EXIT_CODES.INVALID_ARGUMENTS;
    }
  }

  // Handle report comparison mode (--compare <before> <after>)
  if (compareFiles) {
    const [beforePath, afterPath] = compareFiles;
    let beforeJson, afterJson;
    try {
      if (!fs.existsSync(beforePath)) {
        console.error(`Error: Before report file not found: "${beforePath}"`);
        return EXIT_CODES.INVALID_ARGUMENTS;
      }
      if (!fs.existsSync(afterPath)) {
        console.error(`Error: After report file not found: "${afterPath}"`);
        return EXIT_CODES.INVALID_ARGUMENTS;
      }
      beforeJson = JSON.parse(fs.readFileSync(beforePath, 'utf8'));
      afterJson = JSON.parse(fs.readFileSync(afterPath, 'utf8'));
    } catch (err) {
      console.error(`Error parsing report JSON for comparison: ${err.message}`);
      return EXIT_CODES.INVALID_ARGUMENTS;
    }

    let comparison;
    try {
      comparison = compareReadinessReports(beforeJson, afterJson, { allowCrossProject });
    } catch (err) {
      console.error(`Error comparing readiness reports: ${err.message}`);
      return EXIT_CODES.TOOL_ERROR;
    }

    const comparisonJson = JSON.stringify(comparison, null, 2);
    const comparisonMd = formatComparisonMarkdown(comparison);

    if (outputDir) {
      try {
        const safeOutDir = assertSafeOutputDir(outputDir);
        if (!fs.existsSync(safeOutDir)) {
          fs.mkdirSync(safeOutDir, { recursive: true });
        }
        const targetFormat = format || 'both';
        if (targetFormat === 'json' || targetFormat === 'both') {
          const jsonOutPath = path.join(safeOutDir, 'readiness-comparison.json');
          fs.writeFileSync(jsonOutPath, comparisonJson, 'utf8');
          console.log(`Saved comparison JSON report to: ${jsonOutPath}`);
        }
        if (targetFormat === 'markdown' || targetFormat === 'both') {
          const mdOutPath = path.join(safeOutDir, 'readiness-comparison.md');
          fs.writeFileSync(mdOutPath, comparisonMd, 'utf8');
          console.log(`Saved comparison Markdown report to: ${mdOutPath}`);
        }
      } catch (err) {
        console.error(`Error writing comparison output to "${outputDir}": ${err.message}`);
        return EXIT_CODES.TOOL_ERROR;
      }
    } else {
      if (format === 'json') {
        console.log(comparisonJson);
      } else {
        console.log(comparisonMd);
      }
    }

    if (comparison.statusTransition.regressed || comparison.after.policyOutcome === 'BLOCKED') {
      return EXIT_CODES.POLICY_BLOCKERS;
    }
    return EXIT_CODES.SUCCESS_NO_BLOCKERS;
  }

  // Validate project path
  let safeProjectDir;
  try {
    safeProjectDir = assertSafeProjectDir(projectDir);
  } catch (err) {
    console.error(`Error: ${err.message}`);
    return EXIT_CODES.INVALID_ARGUMENTS;
  }

  // Handle command preview mode
  if (previewCommands) {
    let pkg = null;
    try {
      pkg = JSON.parse(fs.readFileSync(path.join(safeProjectDir, 'package.json'), 'utf8'));
    } catch {
      /* ignore missing or malformed package.json during preview */
    }
    const preview = previewExecutionCommands(safeProjectDir, pkg, timeoutMs, { allowExec, trustProject });
    console.log('\n=== EnvGuard Command Execution Preview ===');
    console.log(`Target Project: ${preview.projectDir}`);
    console.log(`Isolation Available: ${preview.isolationAvailable}`);
    console.log(`Execution Mode: ${preview.trustMode}`);
    console.log(`Timeout: ${preview.timeoutMs}ms`);
    console.log('Planned Commands:');
    if (preview.commands.length === 0) {
      console.log('  (None detected in package.json)');
    } else {
      for (const cmd of preview.commands) {
        console.log(`  - ${cmd.command} ${cmd.args.join(' ')}`);
      }
    }
    console.log('\nPotential Effects:');
    console.log(`  Network: ${preview.disclosures.network}`);
    console.log(`  Filesystem: ${preview.disclosures.filesystem}\n`);
    return EXIT_CODES.SUCCESS_NO_BLOCKERS;
  }

  // Validate output directory if provided
  let safeOutputDir = null;
  if (outputDir) {
    try {
      safeOutputDir = assertSafeOutputDir(outputDir);
    } catch (err) {
      console.error(`Error: ${err.message}`);
      return EXIT_CODES.INVALID_ARGUMENTS;
    }
  }

  // Handle autonomous orchestrator pipeline mode
  if (orchestrate) {
    let session;
    try {
      session = runOrchestratedPipeline({
        projectDir: safeProjectDir,
        categories,
        allowExec,
        trustProject,
        timeoutMs,
        sarifPath,
        allowedCommands: execCommands,
        outputDir: safeOutputDir,
        format,
        onStateTransition: (state) => {
          console.log(`[ORCHESTRATOR] State transition: ${state}`);
        },
      });
    } catch (err) {
      console.error(`Orchestrator Error: ${err.message}`);
      return EXIT_CODES.TOOL_ERROR;
    }

    if (session.state === WORKFLOW_STATES.FAILED) {
      console.error(`Orchestrator pipeline failed: ${session.error}`);
      return EXIT_CODES.TOOL_ERROR;
    }

    if (session.policyOutcome === 'BLOCKED') {
      return EXIT_CODES.POLICY_BLOCKERS;
    }
    return EXIT_CODES.SUCCESS_NO_BLOCKERS;
  }

  // Handle remediation workflow mode
  if (remediate) {
    let remResult;
    try {
      remResult = executeRemediationWorkflow({
        projectDir: safeProjectDir,
        applyFix,
        categories,
        allowExec,
        trustProject,
        timeoutMs,
      });
    } catch (err) {
      console.error(`Remediation Error: ${err.message}`);
      return EXIT_CODES.TOOL_ERROR;
    }

    if (remResult.status === REMEDIATION_STATUSES.NO_ACTIONABLE_PATCHES) {
      console.log('No actionable remediation patches available for current findings.');
      return EXIT_CODES.SUCCESS_NO_BLOCKERS;
    }

    if (remResult.status === REMEDIATION_STATUSES.PROPOSED_PENDING_APPROVAL) {
      console.log('\n=== Proposed EnvGuard Reviewable Remediation Patches ===');
      console.log(remResult.diffPreview);
      console.log(
        `\nFormulated ${remResult.summary.totalPatches} patches (${remResult.summary.filesToCreate} new, ${remResult.summary.filesToModify} modified).`
      );
      console.log('Pass "--apply-fix" to apply patches with automated rollback checkpoint and retesting.\n');
      return EXIT_CODES.SUCCESS_NO_BLOCKERS;
    }

    if (remResult.status === REMEDIATION_STATUSES.REVERTED_DUE_TO_REGRESSION) {
      console.error(`Remediation reverted: ${remResult.error}`);
      return EXIT_CODES.POLICY_BLOCKERS;
    }

    if (remResult.status === REMEDIATION_STATUSES.REMEDIATED_AND_VERIFIED) {
      console.log(`\nSuccessfully applied ${remResult.patches.length} remediation patches.`);
      console.log(`Rollback checkpoint created: ${remResult.checkpoint?.checkpointId}`);
      if (remResult.checkpoint?.security?.permissionWarning) {
        console.warn(`Security Notice: ${remResult.checkpoint.security.permissionWarning}`);
      }
      console.log(`Retesting verdict: ${remResult.verdict}\n`);
      if (remResult.afterReport?.policyEvaluation?.outcome === 'BLOCKED') {
        return EXIT_CODES.POLICY_BLOCKERS;
      }
      return EXIT_CODES.SUCCESS_NO_BLOCKERS;
    }

    if (remResult.status === REMEDIATION_STATUSES.CONFLICT) {
      console.error(`Remediation conflict: ${remResult.error}`);
      return EXIT_CODES.POLICY_BLOCKERS;
    }

    if (remResult.status === REMEDIATION_STATUSES.FAILED) {
      console.error(`Remediation failed: ${remResult.error}`);
      return EXIT_CODES.TOOL_ERROR;
    }
  }

  let report;
  try {
    report = runReadinessAudit({
      projectDir: safeProjectDir,
      categories,
      allowExec,
      trustProject,
      timeoutMs,
      sarifPath,
      allowedCommands: execCommands,
    });
  } catch (err) {
    console.error(`Readiness Audit Error: ${err.message}`);
    return EXIT_CODES.TOOL_ERROR;
  }

  // Generate outputs
  const jsonOutput = JSON.stringify(report, null, 2);
  const mdOutput = generateMarkdownReport(report);

  if (safeOutputDir) {
    try {
      if (!fs.existsSync(safeOutputDir)) {
        fs.mkdirSync(safeOutputDir, { recursive: true });
      }

      const targetFormat = format || 'both';
      if (targetFormat === 'json' || targetFormat === 'both') {
        const jsonFile = path.join(safeOutputDir, 'readiness-report.json');
        fs.writeFileSync(jsonFile, jsonOutput, 'utf8');
        console.log(`Saved JSON readiness report to: ${jsonFile}`);
      }
      if (targetFormat === 'markdown' || targetFormat === 'both') {
        const mdFile = path.join(safeOutputDir, 'readiness-report.md');
        fs.writeFileSync(mdFile, mdOutput, 'utf8');
        console.log(`Saved Markdown readiness report to: ${mdFile}`);
      }
    } catch (err) {
      console.error(`Error writing report files to "${safeOutputDir}": ${err.message}`);
      return EXIT_CODES.TOOL_ERROR;
    }
  } else {
    if (format === 'json') {
      console.log(jsonOutput);
    } else {
      console.log(mdOutput);
    }
  }

  if (deploymentGate) {
    const deploymentFindings = checkDeploymentReadiness(safeProjectDir, collectProjectFiles(safeProjectDir));
    const gateResult = evaluateDeploymentGate({
      deploymentFindings,
      policyFindings: report.findings,
    });
    console.log('\n=== EnvGuard Deployment Readiness Gate ===');
    console.log(`Verdict: ${gateResult.verdict}`);
    console.log(`Deployable: ${gateResult.deployable ? 'YES (requires separate manual execution)' : 'NO'}`);
    console.log(`Auto-deploy policy: ${gateResult.executionGuard.policy}`);
    if (gateResult.blockers.length > 0) {
      console.log(`\nBlockers (${gateResult.blockers.length}):`);
      for (const b of gateResult.blockers) {
        console.log(`  - [${b.id}] ${b.title}`);
      }
    }
    if (gateResult.missingPrerequisites.length > 0) {
      console.log(`\nMissing Prerequisites (${gateResult.missingPrerequisites.length}):`);
      for (const p of gateResult.missingPrerequisites) {
        console.log(`  - [${p.id}] ${p.title}: ${p.impact}`);
      }
    }
    if (gateResult.verdict === DEPLOYMENT_GATE_VERDICTS.BLOCKED) {
      return EXIT_CODES.POLICY_BLOCKERS;
    }
  }

  // Check exit codes:
  // Policy blockers (FAIL with critical/high severity) return 2
  const hasBlockers = report.findings.some(
    (f) => f.status === 'FAIL' && (f.severity === 'critical' || f.severity === 'high')
  );
  if (hasBlockers) {
    return EXIT_CODES.POLICY_BLOCKERS;
  }

  // Check for incomplete executions (e.g. timed out)
  const hasTimeouts = report.findings.some((f) => f.status === 'FAIL' && f.title?.includes('Timed Out'));
  if (hasTimeouts) {
    return EXIT_CODES.INCOMPLETE_EXECUTION;
  }

  return EXIT_CODES.SUCCESS_NO_BLOCKERS;
}

export { main as runAuditorCli };

// Direct invocation CLI runner
const isDirectCall =
  process.argv[1] &&
  (process.argv[1].endsWith('readiness-auditor.mjs') || process.argv[1].endsWith('readiness-auditor'));

if (isDirectCall) {
  const code = main(process.argv.slice(2));
  process.exit(code);
}
finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the workStars: 321kUpdated Claude CodeCodexVerifiedInstall
systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixesStars: 321kUpdated Claude CodeCodexVerifiedInstall
test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation codeStars: 321kUpdated Claude CodeCodexVerifiedInstall
skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Stars: 197kUpdated Claude CodeCodexVerifiedInstall