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

# 失敗中の CI ビルドを自動修正

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="失敗しているCIビルドを自動修正" description="PRのCI失敗を修正するためにDevinを呼び出すGitHub Actionを追加します。" prompt="失敗しているCIビルドを自動的に修正するようDevinをトリガーするGitHub Actionのセットアップを手伝ってください。https://docs.devin.ai/use-cases/gallery/api-github-actions-ci-fix のガイドに従い、APIキーの保存、ワークフローファイルの追加、どの失敗を対象にするかの設定という各ステップを順に説明してください。" category="自動化" features="API" />

<div className="uc-detail-wrapper">
  <Tip>手動でのセットアップが面倒ですか？このページのリンクを Devin のセッションに貼り付けて、すべてのセットアップを依頼してください。</Tip>

  <Steps>
    <Step title="Store your Devin API key in GitHub">
      The workflow calls Devin's [v3 API](/ja/api-reference/v3/overview) to create sessions programmatically. Create a service user and store its token as a GitHub Actions secret:

      1. Go to [app.devin.ai](https://app.devin.ai/?utm_source=docs\&utm_medium=use-case-gallery) > **Settings** > **Service Users** and create a service user with `ManageOrgSessions` permission
      2. Copy the API token shown after creation — it's only displayed once
      3. In your GitHub repo, navigate to **Settings > Secrets and variables > Actions**
      4. Add two secrets: `DEVIN_API_KEY` (the token) and `DEVIN_ORG_ID` (your organization ID — get it by calling `GET https://api.devin.ai/v3/enterprise/organizations` with your token)

      Devin がリポジトリをクローン、ビルド、プッシュできるように、リポジトリがすでに [Devin の Machine でセットアップ済み](/ja/onboard-devin/environment) であることを確認してください。
    </Step>

    <Step title="ワークフローファイルを追加する">
      Create `.github/workflows/devin-ci-fix.yml`. This workflow fires whenever your existing CI workflow completes with a failure, extracts the failing job names, and calls the [Devin API](/ja/api-reference/v3/sessions/post-organizations-sessions) to start a fix session:

      ```yaml theme={null}
      name: Auto-fix CI with Devin

      on:
        workflow_run:
          workflows: ["CI"]
          types: [completed]

      jobs:
        trigger-devin-fix:
          if: >
            github.event.workflow_run.conclusion == 'failure' &&
            github.event.workflow_run.pull_requests[0]
          runs-on: ubuntu-latest
          steps:
            - name: Get failure details
              id: failure
              uses: actions/github-script@v7
              with:
                script: |
                  const run = context.payload.workflow_run;
                  const pr = run.pull_requests[0];
                  const jobs = await github.rest.actions.listJobsForWorkflowRun({
                    owner: context.repo.owner,
                    repo: context.repo.repo,
                    run_id: run.id
                  });
                  const failed = jobs.data.jobs
                    .filter(j => j.conclusion === 'failure')
                    .map(j => j.name);
                  core.setOutput('pr_number', pr.number);
                  core.setOutput('branch', pr.head.ref);
                  core.setOutput('failed_jobs', failed.join(', '));
                  core.setOutput('run_url', run.html_url);

            - name: Trigger Devin session
              run: |
                curl -s -X POST "https://api.devin.ai/v3/organizations/${{ secrets.DEVIN_ORG_ID }}/sessions" \
                  -H "Authorization: Bearer ${{ secrets.DEVIN_API_KEY }}" \
                  -H "Content-Type: application/json" \
                  -d "{
                    \"prompt\": \"CI failed on PR #${{ steps.failure.outputs.pr_number }} in ${{ github.repository }}. Failed jobs: ${{ steps.failure.outputs.failed_jobs }}. Run: ${{ steps.failure.outputs.run_url }}. Branch: ${{ steps.failure.outputs.branch }}. Read the CI logs, identify the root cause, and push a fix to the branch.\"
                  }"
      ```

      Replace `"CI"` in the `workflows` array with the exact `name:` from your existing CI workflow file (e.g., `"Tests"`, `"Build & Test"`).

      Use the `tags` field in the request body (e.g., `"tags": ["ci-fix", "pr-312"]`) to track which CI failures have already triggered sessions and avoid duplicates.
    </Step>

    <Step title="What happens when CI fails">
      PR の CI 実行が失敗すると、Action が失敗の詳細を抽出し、セッションプロンプトとして Devin に渡します。以下は、典型的な自動修正のフローです。

      1. **CI ログを読み取る** — Devin が実行 URL を開き、失敗したジョブのエラー出力、スタックトレース、テスト結果を解析します
      2. **エラーをコードまでたどる** — PR ブランチ上の関連するファイルと行 (例: `UserList.tsx:34`) を特定し、その周辺コードと直近の差分を読み取ります
      3. **修正をプッシュする** — 狙いを絞った変更を PR ブランチに直接コミットし、これにより CI が自動的に再トリガーされます
      4. **PR にコメントする** — root cause と変更内容を説明する要約を投稿します

      Devin による PR コメントの例:

      ```
      CI failure in test-unit — fixed

      Root cause: `UserList.tsx:34` calls `.map()` on `props.users`, which is
      undefined when the API returns an empty response body instead of `[]`.

      Fix: Added a fallback — `const users = props.users ?? [];`
      Added a test case for the empty-response scenario.
      All 312 tests passing.
      ```

      <PromptBlock>
        ```txt フレークテストの調査 theme={null}
        CI の失敗は、実際にはフレークテストが原因で、再実行するとパスします。  
        src/__tests__/UserList.test.tsx のテストを調査し、この不安定さを解消してください。  
        タイミングの問題か、レースコンディションか、実行間のクリーンアップ不足によるものかを確認してください。
        ```
      </PromptBlock>
    </Step>

    <Step title="対象を適切な失敗に絞る">
      すべての CI の失敗が自動修正の恩恵を受けられるわけではありません。インフラのタイムアウトや Docker ビルドの問題は、コード変更では解決できません。関連するジョブの失敗のときにだけ Devin がトリガーされるよう、条件を追加してください。

      ```yaml theme={null}
            - name: Trigger Devin session
              if: >
                contains(steps.failure.outputs.failed_jobs, 'test') ||
                contains(steps.failure.outputs.failed_jobs, 'lint') ||
                contains(steps.failure.outputs.failed_jobs, 'typecheck')
              run: |
                curl -s -X POST "https://api.devin.ai/v3/organizations/${{ secrets.DEVIN_ORG_ID }}/sessions" \
                ...
      ```

      ### 修正はレビューしやすい状態に保つ

      Devin は修正コミットをプッシュしますが、PR をマージする前には引き続き人間によるレビューが必要です。自動修正はコードレビューの代替ではなく、開発者にとってのたたき台として扱ってください。Devin が失敗を解決できない場合は、PR 上にコメントして判明した内容を説明し、エンジニアがそこから引き継げるようにします。
    </Step>
  </Steps>
</div>
