All files / src sentry.ts

65.48% Statements 74/113
59.15% Branches 42/71
67.85% Functions 19/28
67.61% Lines 71/105

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                40x         4x 4x       4x 4x 4x   4x                         4x 4x           40x             4x 4x 4x                   62x 2x 2x                 62x 2x 2x 2x     2x             2x   2x 2x 2x 2x   2x 2x   2x     2x 2x   2x 2x   2x       2x 2x                 2x                         148x 2x 2x                   2x 2x 1x   2x 1x   2x               54x           11x 1x   1x         1x 1x         1x       1x       1x         1x 3x 3x                   6x                               17x                                   6x                   2x               6x                                   41x 1x 1x 1x   1x 1x   1x         5x                                  
import * as Sentry from '@sentry/node';
import type { Severity, SkillReport } from './types/index.js';
import { SEVERITY_ORDER } from './types/index.js';
import { getVersion } from './utils/index.js';
import { genAiProviderName } from './sdk/otel.js';
 
export type SentryContext = 'cli' | 'action';
 
let initialized = false;
 
type TelemetryAttributes = Record<string, string | number | boolean>;
 
function getGitHubServerUrl(): string {
  const serverUrl = process.env['GITHUB_SERVER_URL'] || 'https://github.com';
  return serverUrl.replace(/\/+$/, '');
}
 
export function initSentry(context: SentryContext): void {
  const dsn = process.env['WARDEN_SENTRY_DSN'];
  Iif (!dsn || initialized) return;
  initialized = true;
 
  Sentry.init({
    dsn,
    release: `warden@${getVersion()}`,
    environment: context === 'action' ? 'github-action' : 'cli',
    tracesSampleRate: 1.0,
    enableLogs: true,
    integrations: [
      Sentry.consoleLoggingIntegration({ levels: ['warn', 'error'] }),
      Sentry.anthropicAIIntegration({ recordInputs: true, recordOutputs: true }),
      Sentry.httpIntegration(),
    ],
  });
 
  Sentry.setTag('service.version', getVersion());
  Sentry.getGlobalScope().setAttributes({
    'warden.source': context === 'action' ? 'github-action' : 'cli',
  });
}
 
export { Sentry };
export const { logger } = Sentry;
 
/**
 * Set attributes on the global Sentry scope.
 * These automatically apply to ALL metrics and spans.
 */
export function setGlobalAttributes(attrs: TelemetryAttributes): void {
  Iif (!initialized) return;
  try {
    Sentry.getGlobalScope().setAttributes(attrs);
  } catch {
    // Never break the workflow
  }
}
 
/**
 * Set repository metadata on the global Sentry scope.
 */
export function setRepositoryScope(repository: string | undefined): void {
  if (!repository || !initialized) return;
  const [owner, name] = repository.split('/');
  const attrs: TelemetryAttributes = name
    ? {
        'vcs.owner.name': owner ?? '',
        'vcs.repository.name': name,
      }
    : {
        'vcs.repository.name': repository,
      };
 
  if (owner && name && owner !== 'local') {
    const serverUrl = getGitHubServerUrl();
    attrs['vcs.provider.name'] = 'github';
    attrs['vcs.repository.url.full'] = `${serverUrl}/${owner}/${name}`;
  }
 
  setGlobalAttributes(attrs);
}
 
/**
 * Set GitHub Actions metadata on the global Sentry scope.
 */
export function setGitHubActionScope(eventName: string | undefined): void {
  Iif (!initialized) return;
 
  const repository = process.env['GITHUB_REPOSITORY'];
  const runId = process.env['GITHUB_RUN_ID'];
  const serverUrl = getGitHubServerUrl();
  const attrs: TelemetryAttributes = {};
 
  Eif (eventName) {
    attrs['github.event.name'] = eventName;
  }
  Iif (process.env['GITHUB_WORKFLOW']) {
    attrs['cicd.pipeline.name'] = process.env['GITHUB_WORKFLOW'];
  }
  Eif (runId) {
    attrs['cicd.pipeline.run.id'] = runId;
  }
  Eif (repository && runId) {
    attrs['cicd.pipeline.run.url.full'] = `${serverUrl}/${repository}/actions/runs/${runId}`;
  }
  Iif (process.env['GITHUB_JOB']) {
    attrs['cicd.pipeline.task.name'] = process.env['GITHUB_JOB'];
  }
 
  Eif (Object.keys(attrs).length > 0) {
    setGlobalAttributes(attrs);
  }
}
 
/**
 * Get the trace ID from the active span, if available.
 * Useful for correlating runs to Sentry traces in logs and output.
 */
export function getTraceId(): string | undefined {
  Eif (!initialized) return undefined;
  try {
    return Sentry.getActiveSpan()?.spanContext().traceId;
  } catch {
    return undefined;
  }
}
 
/**
 * Run a metrics callback only when Sentry is initialized.
 * Swallows errors so metrics never break the main workflow.
 */
function safeEmit(fn: () => void): void {
  if (!initialized) return;
  try {
    fn();
  } catch {
    // Metrics emission should never break the main workflow
  }
}
 
/**
 * Build agent-scoped metric attributes that match span attribute names.
 */
function agentMetricAttributes(skill: string, model?: string, runtime?: string): TelemetryAttributes {
  const attrs: TelemetryAttributes = { 'gen_ai.agent.name': skill };
  if (model) {
    attrs['gen_ai.request.model'] = model;
  }
  if (runtime) {
    attrs['warden.runtime.name'] = runtime;
  }
  return attrs;
}
 
/**
 * Emit a single run count. Call once per analysis workflow execution.
 * Inherits warden.source, repository, and GitHub Actions attributes from global scope.
 */
export function emitRunMetric(): void {
  safeEmit(() => {
    Sentry.metrics.count('warden.workflow.runs', 1);
  });
}
 
export function emitSkillMetrics(report: SkillReport): void {
  safeEmit(() => {
    const attrs = agentMetricAttributes(report.skill, report.model, report.runtime);
 
    Sentry.metrics.distribution('warden.skill.duration', report.durationMs ?? 0, {
      unit: 'millisecond',
      attributes: attrs,
    });
 
    Eif (report.usage) {
      const tokenAttrs = {
        ...attrs,
        'gen_ai.operation.name': 'invoke_agent',
        'gen_ai.provider.name': genAiProviderName(report.runtime, report.model),
      };
      Sentry.metrics.distribution('gen_ai.client.token.usage', report.usage.inputTokens, {
        unit: '{token}',
        attributes: { ...tokenAttrs, 'gen_ai.token.type': 'input' },
      });
      Sentry.metrics.distribution('gen_ai.client.token.usage', report.usage.outputTokens, {
        unit: '{token}',
        attributes: { ...tokenAttrs, 'gen_ai.token.type': 'output' },
      });
      Iif (report.usage.costUSD) {
        Sentry.metrics.distribution('warden.gen_ai.cost.usd', report.usage.costUSD, { attributes: attrs });
      }
    }
 
    for (const severity of Object.keys(SEVERITY_ORDER) as Severity[]) {
      const count = report.findings.filter((f) => f.severity === severity).length;
      Iif (count > 0) {
        Sentry.metrics.count('warden.findings', count, {
          attributes: { ...attrs, 'warden.finding.severity': severity },
        });
      }
    }
  });
}
 
export function emitExtractionMetrics(skill: string, method: 'regex' | 'llm' | 'none', count: number): void {
  safeEmit(() => {
    const attrs = { ...agentMetricAttributes(skill), 'warden.extraction.method': method };
    Sentry.metrics.count('warden.extraction.attempts', 1, { attributes: attrs });
    Sentry.metrics.count('warden.extraction.findings', count, { attributes: attrs });
  });
}
 
export function emitFixEvalMetrics(
  evaluated: number,
  resolved: number,
  failed: number,
  skipped: number,
  uniqueFindingsEvaluated: number,
  uniqueFindingsCodeChanged: number,
  uniqueFindingsResolved: number
): void {
  safeEmit(() => {
    Sentry.metrics.count('warden.fix_eval.evaluated', evaluated);
    Sentry.metrics.count('warden.fix_eval.resolved', resolved);
    Sentry.metrics.count('warden.fix_eval.failed', failed);
    Sentry.metrics.count('warden.fix_eval.skipped', skipped);
    Sentry.metrics.count('warden.fix_eval.unique_findings.evaluated', uniqueFindingsEvaluated);
    Sentry.metrics.count('warden.fix_eval.unique_findings.code_changed', uniqueFindingsCodeChanged);
    Sentry.metrics.count('warden.fix_eval.unique_findings.resolved', uniqueFindingsResolved);
  });
}
 
export function emitFixGateMetrics(
  skill: string,
  checked: number,
  strippedDeterministic: number,
  strippedSemantic: number,
  semanticUnavailable: number
): void {
  safeEmit(() => {
    const attrs = agentMetricAttributes(skill);
    Sentry.metrics.count('warden.fix_gate.checked', checked, { attributes: attrs });
    Sentry.metrics.count('warden.fix_gate.stripped_deterministic', strippedDeterministic, { attributes: attrs });
    Sentry.metrics.count('warden.fix_gate.stripped_semantic', strippedSemantic, { attributes: attrs });
    Sentry.metrics.count('warden.fix_gate.semantic_unavailable', semanticUnavailable, { attributes: attrs });
  });
}
 
export function emitRetryMetric(skill: string, attempt: number): void {
  safeEmit(() => {
    Sentry.metrics.count('warden.skill.retries', 1, {
      attributes: { ...agentMetricAttributes(skill), 'warden.retry.attempt': attempt },
    });
  });
}
 
export function emitDedupMetrics(skill: string, total: number, unique: number): void {
  safeEmit(() => {
    const attrs = agentMetricAttributes(skill);
    Sentry.metrics.distribution('warden.dedup.total', total, { attributes: attrs });
    Sentry.metrics.distribution('warden.dedup.unique', unique, { attributes: attrs });
    if (total > 0) {
      Sentry.metrics.distribution('warden.dedup.removed', total - unique, { attributes: attrs });
    }
  });
}
 
/**
 * Emit the final fix-evaluation outcome for one comment.
 */
export function emitFixEvalVerdictMetric(
  verdict: string,
  skill?: string,
  options: { usedFallback?: boolean } = {}
): void {
  safeEmit(() => {
    const attrs: TelemetryAttributes = { 'warden.fix_eval.verdict': verdict };
    Eif (options.usedFallback !== undefined) {
      attrs['warden.fix_eval.used_fallback'] = options.usedFallback;
    }
    Eif (skill) {
      Object.assign(attrs, agentMetricAttributes(skill));
    }
    Sentry.metrics.count('warden.fix_eval.verdict', 1, { attributes: attrs });
  });
}
 
export function emitStaleResolutionMetric(count: number, skill?: string): void {
  safeEmit(() => {
    const attrs = skill ? agentMetricAttributes(skill) : undefined;
    Sentry.metrics.count('warden.stale.resolved', count, attrs ? { attributes: attrs } : undefined);
  });
}
 
/**
 * Flush pending Sentry events. Safe to call even if Sentry is not initialized.
 */
export async function flushSentry(timeoutMs = 2000): Promise<void> {
  if (!initialized) return;
  try {
    await Sentry.flush(timeoutMs);
  } catch {
    // Sentry flush failure should not prevent normal operation
  }
}