> ## Documentation Index
> Fetch the complete documentation index at: https://docs.devinenterprise.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Gerar automaticamente post-mortems de incidentes

export const UseCaseHero = ({title, description, prompt, category, features, devinUrl, agent, intent, playbookId, type}) => {
  const encodedPrompt = encodeURIComponent(prompt || '');
  const tag = 'docs-use-case-gallery';
  const utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=hero-cta';
  const agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  const devinHref = type === 'schedule' ? 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + (prompt ? '&prompt=' + encodedPrompt : '') : type === 'review' ? 'https://app.devin.ai/review?' + utm : agent === 'ada' ? 'https://app.devin.ai/search?' + utm + '&noSubmit=true' + (prompt ? '&prompt=' + encodedPrompt : '') : devinUrl ? devinUrl.includes('?') ? devinUrl + '&' + utm + agentParams : devinUrl + '?' + utm + agentParams : prompt ? 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encodedPrompt : 'https://app.devin.ai/?' + utm + agentParams;
  const buttonLabel = type === 'schedule' ? 'Schedule in Devin ↗' : type === 'review' ? 'Set Up Devin Review ↗' : agent === 'advanced' ? 'Try in Devin ↗' : agent === 'dana' ? 'Try in Dana ↗' : agent === 'ada' ? 'Try in Ask Devin ↗' : 'Try in Devin ↗';
  const featureList = features ? features.split(',').map(f => f.trim()) : [];
  return <div className="uc-hero">
      <div className="uc-hero-inner">
        <div className="uc-hero-left">
          <h1 className="uc-hero-title">{title}</h1>
          <p className="uc-hero-desc">{description}</p>
          <div>
            <a href={devinHref} target="_blank" rel="noopener noreferrer" className="try-in-devin-btn">
              {buttonLabel}
            </a>
          </div>
        </div>
        <div className="uc-hero-meta">
          <div className="uc-meta-item">
            <span className="uc-meta-label">Author</span>
            <span className="uc-meta-value">Cognition</span>
          </div>
          <div className="uc-meta-item">
            <span className="uc-meta-label">Category</span>
            <span className="uc-meta-value">{category}</span>
          </div>
          {featureList.length > 0 && <div className="uc-meta-item">
              <span className="uc-meta-label">Features</span>
              <span className="uc-meta-value">{featureList.join(', ')}</span>
            </div>}
        </div>
      </div>
    </div>;
};

export const PromptBlock = ({children, type, agent, intent, playbookId}) => {
  var utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=prompt-block';
  var tag = 'docs-use-case-gallery';
  var agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  var label = type === 'schedule' ? 'Schedule in Devin' : type === 'playbook' ? 'Create Playbook' : type === 'knowledge' ? 'Add to Knowledge' : agent === 'advanced' ? 'Try in Devin' : agent === 'dana' ? 'Try in Dana' : agent === 'ada' ? 'Try in Ask Devin' : 'Try in Devin';
  var buildUrl = function (text) {
    var encoded = encodeURIComponent(text);
    if (type === 'schedule') return 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + '&prompt=' + encoded;
    if (type === 'playbook') return 'https://app.devin.ai/settings/playbooks/create?' + utm + '&body=' + encoded;
    if (type === 'knowledge') return 'https://app.devin.ai/knowledge?' + utm + '&body=' + encoded;
    if (agent === 'ada') return 'https://app.devin.ai/search?' + utm + '&noSubmit=true&prompt=' + encoded;
    return 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encoded;
  };
  const ref = React.useRef(null);
  const [href, setHref] = React.useState('#');
  React.useEffect(() => {
    if (!ref.current) return;
    var codeEl = ref.current.querySelector('pre code');
    if (codeEl) {
      var text = codeEl.textContent.trim();
      if (text) setHref(buildUrl(text));
    }
    var header = ref.current.querySelector('[data-component-part="code-block-header"]');
    if (header && !header.querySelector('.prompt-block-devin-link')) {
      var link = document.createElement('a');
      link.href = href;
      link.target = '_blank';
      link.rel = 'noopener noreferrer';
      link.className = 'prompt-block-devin-link';
      link.style.cssText = 'display:inline-flex;align-items:center;gap:6px;text-decoration:none;color:#fff;font-size:11px;font-weight:500;padding:4px 10px;border-radius:6px;white-space:nowrap;background:#317CFF;transition:background 0.2s;margin-left:8px;';
      link.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg> ' + label;
      link.onmouseenter = function () {
        link.style.background = '#2968D9';
      };
      link.onmouseleave = function () {
        link.style.background = '#317CFF';
      };
      header.appendChild(link);
    }
    var existingLink = ref.current.querySelector('.prompt-block-devin-link');
    if (existingLink && href !== '#') existingLink.href = href;
  });
  return <div className="prompt-block" ref={ref}>{children}</div>;
};

<UseCaseHero title="Gerar automaticamente post-mortems de incidentes" description="Quando um incidente no PagerDuty é encerrado, Devin elabora um post-mortem estruturado com linha do tempo, análise de causa raiz e itens de ação." prompt="Ajude-me a configurar um pipeline de post-mortem entre o PagerDuty e o Devin. Siga o guia em https://docs.devin.ai/use-cases/gallery/api-pagerduty-postmortem e oriente-me em cada etapa: implantar a ponte de webhook, configurar o PagerDuty e conectar MCPs de observabilidade." category="Resposta a incidentes" features="API, MCP" />

<div className="uc-detail-wrapper">
  <Tip>Para um guia mais detalhado de integração com o PagerDuty, [clique aqui](/pt-BR/enterprise/integrations/pagerduty).</Tip>

  <Steps>
    <Step title="Implantar uma ponte para webhooks">
      Crie um pequeno serviço que monitore eventos `incident.resolved` do PagerDuty e inicie uma sessão do Devin para redigir o postmortem. Implante isso como uma função serverless (AWS Lambda, Cloudflare Worker) ou um contêiner leve:

      ```javascript theme={null}
      const express = require('express');
      const crypto = require('crypto');
      const app = express();
      app.use(express.json());

      function verifySignature(req) {
        const secret = Buffer.from(req.headers['x-webhook-secret'] || '');
        const expected = Buffer.from(process.env.WEBHOOK_SECRET || '');
        if (!expected.length) throw new Error('WEBHOOK_SECRET environment variable is not set');
        if (secret.length !== expected.length) return false;
        return crypto.timingSafeEqual(secret, expected);
      }

      app.post('/pagerduty-resolved', async (req, res) => {
        if (!verifySignature(req)) return res.status(401).send('Bad signature');

        const event = req.body?.event;
        if (!event || event.event_type !== 'incident.resolved') {
          return res.sendStatus(200);
        }

        const incident = event.data;
        const title = incident.title || 'Unknown incident';
        const service = incident.service?.summary || 'unknown-service';
        const urgency = incident.urgency || 'high';
        const incidentUrl = incident.html_url || '';
        const createdAt = incident.created_at || '';
        const resolvedAt = incident.resolved_at || new Date().toISOString();

        const orgId = process.env.DEVIN_ORG_ID;
        const response = await fetch(
          `https://api.devin.ai/v3/organizations/${orgId}/sessions`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${process.env.DEVIN_API_KEY}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            prompt: [
              `A PagerDuty incident has been resolved. Draft a postmortem.`,
              ``,
              `Incident: "${title}"`,
              `Service: ${service}`,
              `Urgency: ${urgency}`,
              `Created: ${createdAt}`,
              `Resolved: ${resolvedAt}`,
              `Incident URL: ${incidentUrl}`,
              ``,
              `Write a structured postmortem:`,
              `1. Use the Datadog MCP to pull logs and metrics for ${service} during the incident window`,
              `2. Identify the root cause — check for deploys, config changes, or upstream failures`,
              `3. Build a detailed timeline from first alert to resolution`,
              `4. List action items to prevent recurrence`,
              `5. Post the postmortem as a PR to our docs/postmortems/ directory`,
            ].join('\n'),
            tags: ['pagerduty-postmortem', `service:${service}`],
          }),
        });

        const { session_id } = await response.json();
        console.log(`Started postmortem session ${session_id} for: ${title}`);
        res.sendStatus(200);
      });

      app.listen(3000);
      ```

      Crie um [usuário de serviço](/pt-BR/api-reference/v3/overview) em **Configurações > Service Users** no [app.devin.ai](https://app.devin.ai/?utm_source=docs\&utm_medium=use-case-gallery) com a permissão `ManageOrgSessions`. Copie o token da API exibido após a criação e armazene-o como `DEVIN_API_KEY` no seu serviço de bridge. Defina `DEVIN_ORG_ID` como o ID da sua organização — obtenha-o fazendo uma chamada a `GET https://api.devin.ai/v3/enterprise/organizations` com seu token. Defina `WEBHOOK_SECRET` como um segredo compartilhado que você também configurará no PagerDuty.
    </Step>

    <Step title="Configurar PagerDuty">
      1. No PagerDuty, vá para **Services > \[seu serviço] > Integrations**
      2. Clique em **Add Integration** e selecione **Generic Webhooks (v3)**
      3. Defina a **Webhook URL** como o endpoint da sua bridge (por exemplo, `https://your-bridge.example.com/pagerduty-resolved`)
      4. Em **Custom Headers**, adicione `X-Webhook-Secret` com o mesmo valor que você armazenou como `WEBHOOK_SECRET`
      5. Em **Event Subscription**, filtre pelo tipo de evento `incident.resolved` para que o postmortem seja acionado somente após o incidente ser encerrado

      <Note>
        Você também pode se inscrever em `incident.acknowledged` se quiser que o Devin comece a coletar dados enquanto o incidente ainda estiver em andamento e depois finalize o postmortem quando ele for resolvido.
      </Note>
    </Step>

    <Step title="Conecte MCPs de observabilidade (opcional)">
      Devin escreve post-mortems melhores quando pode acessar seus dados de telemetria. Ative um ou mais MCPs para que o Devin possa buscar dados reais do período do incidente:

      **Datadog MCP** — Vá para **Configurações > Connections > MCP servers**, encontre **Datadog**, clique em **Ativar** e insira suas chaves de API e de aplicativo. Devin consultará logs, métricas, eventos de deploy e histórico dos monitores.

      **Sentry MCP** — Encontre **Sentry** no MCP Marketplace, clique em **Ativar** e conclua o fluxo de OAuth. Devin buscará detalhes de erros, stack traces e tags de release.

      Depois de conectado, Devin correlaciona automaticamente a telemetria com a linha do tempo do incidente para elaborar um post-mortem baseado em evidências. Saiba mais sobre [como conectar servidores MCP](/pt-BR/work-with-devin/mcp).
    </Step>

    <Step title="O que Devin gera">
      Quando um incidente no PagerDuty é resolvido, Devin analisa o período do incidente e elabora um postmortem estruturado:

      <PromptBlock>
        ```txt Gerar postmortem de incidente theme={null}
        Um incidente no PagerDuty foi resolvido. Elabore um postmortem.

        Incidente: "Esgotamento do pool de conexões com o banco de dados no orders-service"
        Serviço: orders-service
        Criado em: 2026-02-10T14:32:00Z
        Resolvido em: 2026-02-10T15:18:00Z

        Usando os MCPs do Datadog e do Sentry:
        1. Obtenha logs e métricas do orders-service entre 14:00 e 15:30 UTC
        2. Verifique deploys, alterações de configuração ou falhas em serviços upstream nesse período
        3. Build uma linha do tempo detalhada desde o primeiro alerta até a resolução
        4. Identifique os fatores contribuintes e a causa raiz
        5. Elabore ações para evitar recorrência
        6. Faça commit do postmortem como um arquivo Markdown em docs/postmortems/
        ```
      </PromptBlock>

      Exemplo de postmortem produzido pelo Devin:

      ```markdown theme={null}
      # Postmortem: Database Connection Pool Exhaustion — orders-service
      **Date:** 2026-02-10 | **Duration:** 46 minutes | **Severity:** P1

      ## Summary
      orders-service experienced connection pool exhaustion between
      14:32 and 15:18 UTC, causing 502 errors for ~12% of order
      placement requests.

      ## Timeline
      - 14:15 UTC — Deploy #387 released (commit e4f29a1)
      - 14:28 UTC — Connection pool usage climbed from 60% to 92%
      - 14:32 UTC — Pool exhausted; PagerDuty incident triggered
      - 14:38 UTC — On-call engineer acknowledged
      - 14:45 UTC — Identified Deploy #387 added a new inventory
                    check that opens a DB connection per line item
                    without releasing it in the finally block
      - 15:02 UTC — Rollback to Deploy #386 initiated
      - 15:18 UTC — Connection pool recovered; incident resolved

      ## Root Cause
      Deploy #387 introduced `checkInventoryAvailability()` in
      `src/services/orders.ts:142`. The function opens a new DB
      connection for each line item in an order but only releases
      it on the success path. When inventory checks fail (timeout
      or stock unavailable), connections leak.

      Orders with 5+ line items reliably exhausted the pool within
      15 minutes of the deploy.

      ## Action Items
      - [ ] Fix connection leak: add `finally` block to release
            connection (PR #388 opened)
      - [ ] Add connection pool usage monitor with alert at 80%
      - [ ] Add integration test for multi-item orders with
            simulated inventory failures
      - [ ] Review other DB access patterns for similar leak risks
      ```
    </Step>

    <Step title="Personalize o post-mortem">
      Adapte o pipeline para se alinhar ao processo de postmortem da sua equipe:

      **Use um [Playbook](/pt-BR/product-guides/creating-playbooks)** para definir seu modelo de postmortem — seções, classificação de severidade, campos obrigatórios e onde armazenar o resultado. Passe um `playbook_id` na solicitação da API para padronizar cada postmortem.

      **Encaminhe por severidade.** Adicione lógica à sua integração para gerar postmortems apenas para incidentes P1/P2. Incidentes de menor severidade podem não precisar de um relatório completo.

      **Adicione [Knowledge](/pt-BR/product-guides/knowledge)** sobre sua arquitetura, os responsáveis pelos serviços e incidentes anteriores para que Devin consiga ligar os pontos — por exemplo, "orders-service depende de inventory-service, que é conhecido por problemas de timeout sob carga."

      **Publique no seu wiki.** Em vez de fazer commit em um repo, faça com que Devin publique o postmortem no Confluence, Notion ou no wiki interno da sua empresa por meio do prompt da sessão.
    </Step>
  </Steps>
</div>
