// tools/suggest-tooling/observability-catalog.ts — Observability tooling recommendations (SPEC-026a)
// Generates observability-specific tooling recommendations based on detected stack.
// === Alert spec templates (base specs without specId) ===
const ALERT_TEMPLATES = [
    {
        name: 'High Error Rate',
        condition: 'error_rate > 1% for 5 minutes',
        severity: 'critical',
        notifyTeam: 'on-call',
        runbook: 'https://docs.internal/runbooks/high-error-rate',
    },
    {
        name: 'Slow Response Time',
        condition: 'p99_latency_ms > 2000 for 5 minutes',
        severity: 'warning',
        notifyTeam: 'backend-team',
        runbook: 'https://docs.internal/runbooks/slow-response',
    },
    {
        name: 'Low Success Rate',
        condition: 'success_rate < 99% for 10 minutes',
        severity: 'warning',
        notifyTeam: 'backend-team',
        runbook: 'https://docs.internal/runbooks/low-success-rate',
    },
    {
        name: 'Service Down',
        condition: 'up == 0 for 1 minute',
        severity: 'critical',
        notifyTeam: 'on-call',
        runbook: 'https://docs.internal/runbooks/service-down',
    },
    {
        name: 'High Memory Usage',
        condition: 'memory_usage_percent > 90% for 5 minutes',
        severity: 'warning',
        notifyTeam: 'infrastructure',
        runbook: 'https://docs.internal/runbooks/high-memory',
    },
];
// === Observability tooling recommendation lines ===
/**
 * Builds observability tooling recommendation lines based on detected monitoring stack.
 * For existing projects: shows what is already configured.
 * For new/incomplete projects: recommends what to add.
 */
export function buildObservabilityToolingLines(knowledge, monitoring) {
    const { detected } = monitoring;
    const allDetected = [
        ...detected.metrics,
        ...detected.tracing,
        ...detected.logging,
        ...detected.errorTracking,
        ...detected.alerting,
    ];
    const lines = ['## Observability Stack', ''];
    if (allDetected.length > 0) {
        lines.push('**Detected observability tools:**');
        lines.push('');
        if (detected.errorTracking.length > 0) {
            lines.push(`- **Error Tracking:** ${detected.errorTracking.join(', ')}`);
        }
        if (detected.metrics.length > 0) {
            lines.push(`- **Metrics:** ${detected.metrics.join(', ')}`);
        }
        if (detected.tracing.length > 0) {
            lines.push(`- **Tracing:** ${detected.tracing.join(', ')}`);
        }
        if (detected.logging.length > 0) {
            lines.push(`- **Logging:** ${detected.logging.join(', ')}`);
        }
        if (detected.alerting.length > 0) {
            lines.push(`- **Alerting:** ${detected.alerting.join(', ')}`);
        }
        lines.push('');
    }
    else {
        lines.push('**No observability tools detected.** Recommendations for your stack:');
        lines.push('');
        lines.push(...buildRecommendationLines(knowledge));
    }
    // Gaps
    const gaps = detectObservabilityGaps(detected);
    if (gaps.length > 0) {
        lines.push('### Observability Gaps');
        lines.push('');
        for (const gap of gaps) {
            lines.push(`- [${gap.severity.toUpperCase()}] ${gap.description}`);
        }
        lines.push('');
    }
    return lines;
}
/**
 * Generates alert specifications for new features.
 * Returns standard alerts suitable for a production feature.
 */
export function generateAlertSpecs(specId) {
    return ALERT_TEMPLATES.map((template) => ({
        ...template,
        specId,
    }));
}
/**
 * Builds alert spec output lines for suggest_tooling.
 */
export function buildAlertSpecLines(specId) {
    const alerts = generateAlertSpecs(specId);
    const lines = ['## Recommended Alert Specifications', ''];
    if (specId) {
        lines.push(`For feature **${specId}**, configure the following alerts:`);
    }
    else {
        lines.push('Standard production alerts to configure:');
    }
    lines.push('');
    for (const alert of alerts) {
        lines.push(`### ${alert.name}`);
        lines.push(`- **Condition:** \`${alert.condition}\``);
        lines.push(`- **Severity:** ${alert.severity}`);
        lines.push(`- **Notify:** ${alert.notifyTeam}`);
        lines.push(`- **Runbook:** ${alert.runbook}`);
        lines.push('');
    }
    return lines;
}
// === Observability phase for execution plan ===
/**
 * Returns the observability phase block for PLAN.md.
 */
export function buildObservabilityPhaseLines() {
    return [
        '## Phase: Observability (Required for Production Features)',
        '',
        '### Steps',
        '1. **Implement metrics** — add counters for critical operations, histograms for latencies, gauges for states',
        '2. **Implement structured logs** — include fields: timestamp, trace_id, spec_id, level, message',
        '3. **Implement traces** — add spans for operations crossing service boundaries',
        '4. **Configure alerts** — set up conditions, severities, runbooks (see Alert Specs above)',
        '5. **Verify in staging** — confirm metrics/logs/traces are flowing before production deploy',
        '',
        '### DoD for this phase',
        '- [ ] All critical operations have counters',
        '- [ ] Latency histograms configured for slow operations',
        '- [ ] Structured logging with mandatory fields',
        '- [ ] Distributed traces for cross-service calls',
        '- [ ] At least 1 critical alert configured',
        '- [ ] Runbook exists for each critical alert',
        '',
    ];
}
// === Internal helpers ===
function detectObservabilityGaps(detected) {
    const gaps = [];
    if (detected.errorTracking.length === 0) {
        gaps.push({
            severity: 'critical',
            description: 'No error tracking configured. Add Sentry, Bugsnag, or Rollbar.',
        });
    }
    if (detected.metrics.length === 0) {
        gaps.push({
            severity: 'warning',
            description: 'No metrics configured. Add Prometheus/Grafana or Datadog.',
        });
    }
    if (detected.tracing.length === 0) {
        gaps.push({
            severity: 'warning',
            description: 'No distributed tracing configured. Add OpenTelemetry or Jaeger.',
        });
    }
    if (detected.logging.length === 0) {
        gaps.push({
            severity: 'warning',
            description: 'No structured logging library detected. Add Pino, Winston, or structured stdout.',
        });
    }
    if (detected.alerting.length === 0) {
        gaps.push({
            severity: 'warning',
            description: 'No alerting configured. Set up Prometheus AlertManager or Datadog monitors.',
        });
    }
    return gaps;
}
function buildRecommendationLines(knowledge) {
    const lines = [];
    const fw = (knowledge.framework ?? '').toLowerCase();
    const lang = knowledge.language.toLowerCase();
    // Error tracking — always recommend Sentry first
    lines.push('#### 1. Error Tracking (Critical)');
    lines.push('**Recommended:** Sentry');
    if (fw.includes('next') || fw.includes('react')) {
        lines.push('**Install:** `npm install @sentry/nextjs` — run `npx @sentry/wizard@latest -i nextjs`');
    }
    else if (lang === 'python') {
        lines.push('**Install:** `pip install sentry-sdk` — call `sentry_sdk.init(dsn="...")` in entry point');
    }
    else {
        lines.push('**Install:** `npm install @sentry/node` — call `Sentry.init({ dsn })` in entry point');
    }
    lines.push('');
    // Metrics
    lines.push('#### 2. Metrics (Recommended)');
    if (lang === 'python') {
        lines.push('**Recommended:** Prometheus + Grafana via `prometheus_client`');
        lines.push('**Install:** `pip install prometheus-client`');
    }
    else {
        lines.push('**Recommended:** OpenTelemetry (vendor-neutral)');
        lines.push('**Install:** `npm install @opentelemetry/sdk-node @opentelemetry/auto-instrumentations-node`');
    }
    lines.push('');
    // Logging
    lines.push('#### 3. Structured Logging (Recommended)');
    if (lang === 'typescript' || lang === 'javascript') {
        lines.push('**Recommended:** Pino (fastest structured logger for Node.js)');
        lines.push('**Install:** `npm install pino` — outputs JSON by default');
    }
    else if (lang === 'python') {
        lines.push('**Recommended:** structlog');
        lines.push('**Install:** `pip install structlog`');
    }
    lines.push('');
    return lines;
}
//# sourceMappingURL=observability-catalog.js.map