> ## 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.

# Generazione automatica dei postmortem degli incidenti

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="Genera automaticamente i postmortem degli incidenti" description="Quando un incidente PagerDuty viene risolto, Devin redige un postmortem strutturato con cronologia, analisi della causa principale e azioni da intraprendere." prompt="Aiutami a configurare una pipeline PagerDuty-to-Devin per i postmortem. Segui la guida su https://docs.devin.ai/use-cases/gallery/api-pagerduty-postmortem e guidami in ogni passaggio: distribuire il bridge webhook, configurare PagerDuty e collegare gli MCP di osservabilità." category="Risposta agli incidenti" features="API, MCP" />

<div className="uc-detail-wrapper">
  <Tip>Per una guida più dettagliata sull'integrazione con PagerDuty, [fai clic qui](/it/enterprise/integrations/pagerduty).</Tip>

  <Steps>
    <Step title="Distribuire un bridge per webhook">
      Crea un piccolo servizio che rimanga in ascolto degli eventi PagerDuty `incident.resolved` e avvii una sessione Devin per scrivere il postmortem. Distribuiscilo come funzione serverless (AWS Lambda, Cloudflare Worker) o come container leggero:

      ```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);
      ```

      Crea un [utente di servizio](/it/api-reference/v3/overview) in **Settings > Service Users** su [app.devin.ai](https://app.devin.ai/?utm_source=docs\&utm_medium=use-case-gallery) con l'autorizzazione `ManageOrgSessions`. Copia il token API mostrato dopo la creazione e salvalo come `DEVIN_API_KEY` sul tuo servizio bridge. Imposta `DEVIN_ORG_ID` con l'ID della tua organizzazione — puoi ottenerlo chiamando `GET https://api.devin.ai/v3/enterprise/organizations` con il tuo token. Imposta `WEBHOOK_SECRET` su un segreto condiviso che configurerai anche in PagerDuty.
    </Step>

    <Step title="Configura PagerDuty">
      1. In PagerDuty, vai a **Services > \[il tuo servizio] > Integrations**
      2. Fai clic su **Add Integration** e seleziona **Generic Webhooks (v3)**
      3. Imposta **Webhook URL** sull'endpoint del bridge (ad esempio, `https://your-bridge.example.com/pagerduty-resolved`)
      4. In **Custom Headers**, aggiungi `X-Webhook-Secret` con lo stesso valore che hai salvato come `WEBHOOK_SECRET`
      5. In **Event Subscription**, filtra per il tipo di evento `incident.resolved` in modo che il postmortem venga attivato solo dopo la chiusura dell'incidente

      <Note>
        Puoi anche sottoscrivere `incident.acknowledged` se vuoi che Devin inizi a raccogliere dati mentre l'incidente è ancora in corso, per poi finalizzare il postmortem alla risoluzione.
      </Note>
    </Step>

    <Step title="Collega gli MCP di osservabilità (facoltativo)">
      Devin scrive analisi post-mortem migliori quando può accedere ai tuoi dati di telemetria. Abilita uno o più MCP in modo che Devin possa recuperare dati reali per la finestra temporale dell'incidente:

      **Datadog MCP** — Vai a **Settings > Connections > server MCP**, trova **Datadog**, fai clic su **Enable** e inserisci le chiavi API/Application. Devin interrogherà log, metriche, eventi di deploy e cronologia dei monitor.

      **Sentry MCP** — Trova **Sentry** nel MCP Marketplace, fai clic su **Enable** e completa il flusso OAuth. Devin recupererà dettagli sugli errori, stack trace e tag di release.

      Una volta connesso, Devin correla automaticamente la telemetria con la timeline dell'incidente per creare un'analisi post-mortem basata su evidenze. Scopri di più su [come connettere i server MCP](/it/work-with-devin/mcp).
    </Step>

    <Step title="Cosa genera Devin">
      Quando un incidente PagerDuty si risolve, Devin analizza l'intervallo dell'incidente e prepara un postmortem strutturato:

      <PromptBlock>
        ```txt Genera il postmortem dell'incidente theme={null}
        Un incidente PagerDuty si è risolto. Redigi un postmortem.

        Incidente: "Esaurimento del pool di connessioni al database su orders-service"
        Servizio: orders-service
        Creato: 2026-02-10T14:32:00Z
        Risolto: 2026-02-10T15:18:00Z

        Utilizzando gli MCP di Datadog e Sentry:
        1. Recupera log e metriche per orders-service tra le 14:00 e le 15:30 UTC
        2. Verifica eventuali deploy, modifiche di configurazione o errori nei sistemi upstream in quell'intervallo
        3. Crea una cronologia dettagliata dal primo avviso fino alla risoluzione
        4. Identifica i fattori contribuenti e la causa principale
        5. Definisci azioni correttive per prevenire il ripetersi del problema
        6. Esegui il commit del postmortem come file Markdown in docs/postmortems/
        ```
      </PromptBlock>

      Esempio di postmortem prodotto da 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="Personalizza il resoconto post-incidente">
      Adatta la pipeline al processo di postmortem del tuo team:

      **Usa un [Playbook](/it/product-guides/creating-playbooks)** per definire il modello di postmortem: sezioni, classificazione della gravità, campi obbligatori e dove archiviare l'output. Passa un `playbook_id` nella richiesta API per standardizzare ogni postmortem.

      **Instrada in base alla gravità.** Aggiungi logica nel tuo bridge per generare postmortem solo per incidenti P1/P2. Gli incidenti meno gravi potrebbero non richiedere un resoconto completo.

      **Aggiungi [Knowledge](/it/product-guides/knowledge)** sulla tua architettura, sui responsabili dei servizi e sugli incidenti passati, così Devin può collegare i vari elementi — ad esempio, "orders-service dipende da inventory-service, che è noto per problemi di timeout sotto carico."

      **Pubblica sul tuo wiki.** Invece di fare il commit su una repo, fai in modo che Devin pubblichi il postmortem su Confluence, Notion o sul tuo wiki interno tramite il prompt della session.
    </Step>
  </Steps>
</div>
