Skip to content

Post automatic follow-up comments when enabled repo CI fails #1927

Closed

Description

@propr-dev

Context

ProPR already receives check_run and legacy status webhooks for auto-merge and Ultrafix readiness. The new behavior should inspect failing CI, post a concise follow-up comment containing the failure evidence, and let the normal PR comment worker process that comment. This must only happen for repositories with autoFollowupOnFailedCi enabled.

Requirements

  • React only to completed failing check runs and failing/error status events.
  • Check the repo-level autoFollowupOnFailedCi flag before posting anything.
  • Include the failing check name, conclusion/state, commit SHA, URL, and the most useful failure excerpt available.
  • Prefer check-run annotations over long summaries because annotations usually identify the exact failing file/line/test.
  • Deduplicate by repo, PR, SHA, and CI source to avoid repeated comments for webhook redelivery.
  • Add a hidden marker so bot-authored CI follow-up comments can bypass normal author filtering safely.
  • Strip the hidden marker before sending instructions to the agent.
  • Add tests for disabled repos, enabled repos, dedupe, and bot marker processing.

Implementation Specification

  1. Add packages/core/src/webhook/ciFailureFollowup.ts with failure extraction, comment body construction, and posting logic.
  2. Call the helper from packages/core/src/webhook/checkRunHandler.ts for both check-run and status events.
  3. Update packages/core/src/webhook/commentEventHandler.ts so ProPR-authored comments with the CI marker are accepted and treated as triggered follow-ups.
  4. Export helper functions from packages/core/src/index.ts for tests.
  5. Add unit tests in test/checkRunHandler.test.ts and test/commentEventHandler.switch-use.test.ts or a new focused test file.

Acceptance Criteria

  • A failing check on a repo with the option disabled does not post a comment.
  • A failing check on an enabled repo posts exactly one comment with a failure excerpt and marker.
  • Webhook redelivery does not create duplicate follow-up comments.
  • The created bot comment is accepted by the comment event pipeline despite normal bot filtering.
  • The agent instructions do not include the hidden marker.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Aug 24, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    This implementation posts a normal GitHub PR comment and then lets the existing comment pipeline process it. Directly enqueueing a worker job was considered, but posting a comment first leaves an auditable GitHub artifact and keeps user-visible follow-up behavior consistent with manual comments. The hidden marker is used only to identify ProPR-created CI comments; it avoids opening a general bypass for bot-authored comments.

    File: packages/core/src/webhook/ciFailureFollowup.ts (new file)

    Why this file: CI failure extraction and comment construction are distinct from auto-merge logic. Keeping them in a separate module makes the behavior testable without expanding checkRunHandler.ts further.

    import { createHash } from 'node:crypto';
    import { Redis } from 'ioredis';
    import type { CheckRunEvent, StatusEvent } from '@octokit/webhooks-types';
    import logger from '../utils/logger.js';
    import { getAuthenticatedOctokit } from '../auth/githubAuth.js';
    import { isAutoCiFollowupEnabledForRepository } from '../daemon/configLoader.js';
    import { redactSecrets } from '../utils/github/logFiles.js';
    
    export const AUTO_CI_FOLLOWUP_MARKER_PREFIX = '<!-- propr-auto-ci-followup:';
    const AUTO_CI_FOLLOWUP_MARKER_PATTERN = /\n?<!-- propr-auto-ci-followup:[\s\S]*?-->\n?/g;
    const DEDUPE_TTL_SECONDS = 7 * 24 * 60 * 60;
    const MAX_EXCERPT_CHARS = 6000;
    const MAX_ANNOTATIONS = 20;
    
    type Octokit = Awaited<ReturnType<typeof getAuthenticatedOctokit>>;
    
    type FailureSource =
      | {
          kind: 'check_run';
          id: number;
          name: string;
          conclusion: string;
          sha: string;
          htmlUrl?: string | null;
          detailsUrl?: string | null;
          outputTitle?: string | null;
          outputSummary?: string | null;
          outputText?: string | null;
        }
      | {
          kind: 'status';
          context: string;
          state: string;
          sha: string;
          description?: string | null;
          targetUrl?: string | null;
        };
    
    interface PullRequestRef {
      number: number;
    }
    
    export function isAutoCiFollowupComment(body: string | null | undefined): boolean {
      return Boolean(body?.includes(AUTO_CI_FOLLOWUP_MARKER_PREFIX));
    }
    
    export function stripAutoCiFollowupMarker(body: string): string {
      // Remove the routing marker before the agent sees the instructions. The marker
      // is useful for ProPR's event pipeline but has no value as task context.
      return body.replace(AUTO_CI_FOLLOWUP_MARKER_PATTERN, '\n').trim();
    }
    
    function isFailingCheckRunConclusion(conclusion: string | null | undefined): conclusion is string {
      return conclusion === 'failure' || conclusion === 'timed_out' || conclusion === 'action_required';
    }
    
    function isFailingStatusState(state: string | null | undefined): state is string {
      return state === 'failure' || state === 'error';
    }
    
    function shortSha(sha: string): string {
      return sha.slice(0, 12);
    }
    
    function truncateExcerpt(value: string): string {
      const redacted = redactSecrets(value).trim();
      if (redacted.length <= MAX_EXCERPT_CHARS) return redacted;
      return `${redacted.slice(0, MAX_EXCERPT_CHARS)}\n\n...(truncated)`;
    }
    
    function dedupeKey(owner: string, repo: string, prNumber: number, source: FailureSource): string {
      const rawSource = source.kind === 'check_run'
        ? `check_run:${source.id}`
        : `status:${source.context}:${source.state}`;
      const digest = createHash('sha256').update(rawSource).digest('hex').slice(0, 20);
    
      // Include the PR number and SHA so a rerun on a newer commit can still create
      // a fresh follow-up while webhook redelivery for the same failure is ignored.
      return `ci-followup:${owner}:${repo}:${prNumber}:${source.sha}:${digest}`;
    }
    
    async function claimFollowup(redisClient: Redis, key: string): Promise<boolean> {
      const result = await redisClient.set(key, new Date().toISOString(), 'EX', DEDUPE_TTL_SECONDS, 'NX');
      return result === 'OK';
    }
    
    async function releaseFollowupClaim(redisClient: Redis, key: string): Promise<void> {
      // If GitHub posting fails after the dedupe claim, delete the claim so a later
      // webhook delivery can retry instead of losing the follow-up permanently.
      await redisClient.del(key);
    }
    
    async function fetchCheckRunAnnotations(
      octokit: Octokit,
      owner: string,
      repo: string,
      checkRunId: number,
    ): Promise<string[]> {
      const { data } = await octokit.request('GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations', {
        owner,
        repo,
        check_run_id: checkRunId,
        per_page: MAX_ANNOTATIONS,
      });
    
      return data.map((annotation) => {
        const location = annotation.path
          ? `${annotation.path}${annotation.start_line ? `:${annotation.start_line}` : ''}`
          : 'unknown location';
        const title = annotation.title ? `${annotation.title}\n` : '';
        return `${location}\n${title}${annotation.message}`;
      });
    }
    
    function buildCheckRunExcerpt(source: Extract<FailureSource, { kind: 'check_run' }>, annotations: string[]): string {
      if (annotations.length > 0) {
        return truncateExcerpt(annotations.map((entry, index) => `Annotation ${index + 1}:\n${entry}`).join('\n\n'));
      }
    
      const parts = [source.outputTitle, source.outputSummary, source.outputText]
        .map((part) => part?.trim())
        .filter((part): part is string => Boolean(part));
    
      return truncateExcerpt(parts.length > 0 ? parts.join('\n\n') : 'GitHub did not provide check annotations or output text for this failed check. Use the linked workflow details for the full log.');
    }
    
    function buildStatusExcerpt(source: Extract<FailureSource, { kind: 'status' }>): string {
      return truncateExcerpt(source.description || 'Legacy commit status failed but did not provide a detailed description. Use the linked target URL for the full CI details.');
    }
    
    function buildCommentBody(source: FailureSource, excerpt: string): string {
      const sourceName = source.kind === 'check_run' ? source.name : source.context;
      const state = source.kind === 'check_run' ? source.conclusion : source.state;
      const url = source.kind === 'check_run' ? source.htmlUrl || source.detailsUrl : source.targetUrl;
      const marker = source.kind === 'check_run'
        ? `${AUTO_CI_FOLLOWUP_MARKER_PREFIX}check_run:${source.id}:${source.sha} -->`
        : `${AUTO_CI_FOLLOWUP_MARKER_PREFIX}status:${source.context}:${source.sha} -->`;
    
      return [
        'ProPR follow-up request: CI failed on this pull request.',
        '',
        `Please fix the failing CI evidence below. Focus on the failing check named \`${sourceName}\` for commit \`${shortSha(source.sha)}\`.`,
        '',
        `- Check: \`${sourceName}\``,
        `- Result: \`${state}\``,
        ...(url ? [`- Details: ${url}`] : []),
        '',
        'Failure excerpt:',
        '',
        'text',
        excerpt.replace(//g, '``\u200b`'),
        '',
        '',
        marker,
      ].join('\n');
    }
    
    async function postFollowupForPr(
      octokit: Octokit,
      redisClient: Redis,
      owner: string,
      repo: string,
      prNumber: number,
      source: FailureSource,
      excerpt: string,
      correlationId: string,
    ): Promise<void> {
      const correlatedLogger = logger.withCorrelation(correlationId);
    
      if (!(await isAutoCiFollowupEnabledForRepository(owner, repo))) {
        correlatedLogger.debug({ owner, repo, prNumber }, 'CI failure follow-up is disabled for repository');
        return;
      }
    
      const key = dedupeKey(owner, repo, prNumber, source);
      if (!(await claimFollowup(redisClient, key))) {
        correlatedLogger.debug({ owner, repo, prNumber, key }, 'CI failure follow-up already posted or queued');
        return;
      }
    
      try {
        await octokit.request('POST /repos/{owner}/{repo}/issues/{issue_number}/comments', {
          owner,
          repo,
          issue_number: prNumber,
          body: buildCommentBody(source, excerpt),
        });
      } catch (error) {
        await releaseFollowupClaim(redisClient, key);
        throw error;
      }
    }
    
    export async function maybePostCheckRunFailureFollowup(
      payload: CheckRunEvent,
      redisClient: Redis,
      correlationId: string,
    ): Promise<void> {
      if (payload.action !== 'completed' || !isFailingCheckRunConclusion(payload.check_run.conclusion)) return;
    
      const owner = payload.repository.owner.login;
      const repo = payload.repository.name;
      const prs = (payload.check_run.pull_requests || [])
        .map((pr) => ({ number: pr.number }))
        .filter((pr): pr is PullRequestRef => Number.isInteger(pr.number));
      if (prs.length === 0) return;
    
      const octokit = await getAuthenticatedOctokit();
      const source: FailureSource = {
        kind: 'check_run',
        id: payload.check_run.id,
        name: payload.check_run.name,
        conclusion: payload.check_run.conclusion,
        sha: payload.check_run.head_sha,
        htmlUrl: payload.check_run.html_url,
        detailsUrl: payload.check_run.details_url,
        outputTitle: payload.check_run.output?.title,
        outputSummary: payload.check_run.output?.summary,
        outputText: payload.check_run.output?.text,
      };
      const annotations = await fetchCheckRunAnnotations(octokit, owner, repo, payload.check_run.id);
      const excerpt = buildCheckRunExcerpt(source, annotations);
    
      await Promise.all(prs.map((pr) => postFollowupForPr(octokit, redisClient, owner, repo, pr.number, source, excerpt, correlationId)));
    }
    
    async function findPullRequestsForStatus(octokit: Octokit, owner: string, repo: string, sha: string): Promise<PullRequestRef[]> {
      const { data } = await octokit.request('GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls', {
        owner,
        repo,
        commit_sha: sha,
        headers: { accept: 'application/vnd.github+json' },
      });
    
      return data
        .filter((pr) => pr.state === 'open')
        .map((pr) => ({ number: pr.number }));
    }
    
    export async function maybePostStatusFailureFollowup(
      payload: StatusEvent,
      redisClient: Redis,
      correlationId: string,
    ): Promise<void> {
      if (!isFailingStatusState(payload.state)) return;
    
      const owner = payload.repository.owner.login;
      const repo = payload.repository.name;
      const octokit = await getAuthenticatedOctokit();
      const prs = await findPullRequestsForStatus(octokit, owner, repo, payload.sha);
      if (prs.length === 0) return;
    
      const source: FailureSource = {
        kind: 'status',
        context: payload.context,
        state: payload.state,
        sha: payload.sha,
        description: payload.description,
        targetUrl: payload.target_url,
      };
      const excerpt = buildStatusExcerpt(source);
    
      await Promise.all(prs.map((pr) => postFollowupForPr(octokit, redisClient, owner, repo, pr.number, source, excerpt, correlationId)));
    }

    File: packages/core/src/webhook/commentEventHandler.ts

    Why this file: The posted CI comment is authored by the ProPR bot, and the normal comment pipeline intentionally filters bots. This file needs a narrow exception for marked ProPR CI comments so the comment can become a real follow-up job.

    --- a/packages/core/src/webhook/commentEventHandler.ts
    +++ b/packages/core/src/webhook/commentEventHandler.ts
    @@
     import type { DeliveryDisposition } from '../intake/routingWebSocketProtocol.js';
    +import { isAutoCiFollowupComment, stripAutoCiFollowupMarker } from './ciFailureFollowup.js';
    @@
    -    const { prNumber, comment } = eventDetails;
    +    const { prNumber, comment } = eventDetails;
     
         const commentAuthor = comment.user.login;
    -    const parsedCommand = parseSlashCommand(comment.body);
         const configuredBotUsernames = new Set(
             [getBotUsername(), process.env.GITHUB_BOT_USERNAME, 'propr-dev[bot]']
                 .filter((value): value is string => typeof value === 'string' && value.length > 0)
         );
    +    const isSystemCiFollowupComment = isAutoCiFollowupComment(comment.body)
    +        && configuredBotUsernames.has(commentAuthor);
    +    const commentForProcessing = isSystemCiFollowupComment
    +        ? { ...comment, body: stripAutoCiFollowupMarker(comment.body) }
    +        : comment;
    +    const parsedCommand = parseSlashCommand(commentForProcessing.body);
    @@
    -    if (filterResult.shouldFilter && !isSystemUltrafixComment) return { status: 'ignored', reason: 'filtered_author' };
    +    if (filterResult.shouldFilter && !isSystemUltrafixComment && !isSystemCiFollowupComment) return { status: 'ignored', reason: 'filtered_author' };
     
    -    // Check for ignore keywords
    -    const ignoreKeywords = await loadFollowupIgnoreKeywords();
    -    const ignoreResult = checkCommentIgnore(comment.body, ignoreKeywords, correlationId);
    -    if (ignoreResult.shouldIgnore) return { status: 'ignored', reason: 'ignore_keyword' };
    +    // Do not apply user-authored ignore keywords to ProPR's own CI follow-up
    +    // comment. The failure excerpt can contain arbitrary CI output, and a stray
    +    // ignored word in a test log should not cancel the admin-enabled automation.
    +    if (!isSystemCiFollowupComment) {
    +        const ignoreKeywords = await loadFollowupIgnoreKeywords();
    +        const ignoreResult = checkCommentIgnore(commentForProcessing.body, ignoreKeywords, correlationId);
    +        if (ignoreResult.shouldIgnore) return { status: 'ignored', reason: 'ignore_keyword' };
    +    }
    @@
    -            await handleSlashCommand({ parsedCommand, comment, commentAuthor, eventContext: { eventType, prNumber, owner, repo }, payload, config, correlationId, correlatedLogger });
    +            await handleSlashCommand({ parsedCommand, comment: commentForProcessing, commentAuthor, eventContext: { eventType, prNumber, owner, repo }, payload, config, correlationId, correlatedLogger });
    @@
    -    const triggerResult = checkCommentTrigger(comment.body, correlationId);
    -    if (!hasProcessingLabel && !triggerResult.isTriggered) {
    +    const triggerResult = checkCommentTrigger(commentForProcessing.body, correlationId);
    +    if (!isSystemCiFollowupComment && !hasProcessingLabel && !triggerResult.isTriggered) {
    @@
    -        await storeCommentForBatch(comment, commentAuthor, { eventType, prNumber, owner, repo }, config as StoreCommentConfig);
    +        await storeCommentForBatch(commentForProcessing, commentAuthor, { eventType, prNumber, owner, repo }, config as StoreCommentConfig);
    @@
    -    await enqueueNewCommentJob(comment, commentAuthor, { eventType, prNumber, owner, repo }, { payload, redisClient, PR_FOLLOWUP_TRIGGER_KEYWORDS: config.PR_FOLLOWUP_TRIGGER_KEYWORDS, MODEL_LABEL_PATTERN: config.MODEL_LABEL_PATTERN, correlationId });
    +    await enqueueNewCommentJob(commentForProcessing, commentAuthor, { eventType, prNumber, owner, repo }, { payload, redisClient, PR_FOLLOWUP_TRIGGER_KEYWORDS: config.PR_FOLLOWUP_TRIGGER_KEYWORDS, MODEL_LABEL_PATTERN: config.MODEL_LABEL_PATTERN, correlationId });

    File: packages/core/src/webhook/checkRunHandler.ts

    Why this file: This is where CI-related webhook events are already handled. Calling the new helper here keeps auto-merge, Ultrafix, and CI follow-up decisions in the same event path.

    --- a/packages/core/src/webhook/checkRunHandler.ts
    +++ b/packages/core/src/webhook/checkRunHandler.ts
    @@
     import logger from '../utils/logger.js';
    +import { maybePostCheckRunFailureFollowup, maybePostStatusFailureFollowup } from './ciFailureFollowup.js';
    @@
     export async function handleCheckRunEvent(payload: CheckRunEvent, correlationId: string): Promise<void> {
       const correlatedLogger = logger.withCorrelation(correlationId);
    @@
    +  try {
    +    // Run after the existing check-run handling so the follow-up feature cannot
    +    // block auto-merge/Ultrafix bookkeeping. Failures are logged and swallowed
    +    // because missed comments can be retried by webhook redelivery.
    +    await maybePostCheckRunFailureFollowup(payload, getCheckRunRedisClient(), correlationId);
    +  } catch (error) {
    +    correlatedLogger.warn({ error: (error as Error).message }, 'Failed to post CI failure follow-up comment');
    +  }
     }
    @@
     export async function handleStatusEvent(payload: StatusEventPayload, correlationId: string): Promise<void> {
       const correlatedLogger = logger.withCorrelation(correlationId);
    @@
    +  try {
    +    await maybePostStatusFailureFollowup(payload, getCheckRunRedisClient(), correlationId);
    +  } catch (error) {
    +    correlatedLogger.warn({ error: (error as Error).message }, 'Failed to post legacy status failure follow-up comment');
    +  }
     }

    Note: if checkRunHandler.ts does not already expose a Redis client, add a small shared accessor in checkRunHelpers.ts and reuse the same connection lifecycle that auto-merge/Ultrafix state uses.

    File: packages/core/src/index.ts

    Why this file: Tests and API/daemon integration import webhook helpers through the core barrel.

    --- a/packages/core/src/index.ts
    +++ b/packages/core/src/index.ts
    @@
     export { handleCheckRunEvent, handleStatusEvent, reevaluatePRAutoMerge, setUltrafixCheckRunHook, type StatusEventPayload } from './webhook/checkRunHandler.js';
    +export { isAutoCiFollowupComment, stripAutoCiFollowupMarker, maybePostCheckRunFailureFollowup, maybePostStatusFailureFollowup } from './webhook/ciFailureFollowup.js';
  2. propr-dev commented on Aug 24, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using codex agent with gpt-5.6-sol model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: codex
    • Model: gpt-5.6-sol
    • Branch: 1927/gpt-5.6-sol-post-automatic-follow-up--20260824-0854-lkd
    • Base Branch: 1926-epic-automatic-ci-vn4
    • Worktree: issue-1927-20260824-0854-gpt-5.6-sol-lkd

    🔍 Track Task Execution

  3. added a commit that references this issue on Aug 24, 2026
  4. added a commit that references this issue on Aug 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions