Skip to content

Enforce the assignment gate in webhook and polling comment intake #2896

Closed

Description

@propr-dev

Context

The previous task added followup_requires_assignment as configuration, defaulted off, with nothing reading it. This task makes it take effect.

Comment intake has two paths that must agree, or the gate becomes a race:

  • processCommentEvent in packages/core/src/webhook/commentEventHandler.ts, for webhook and ProPR Connect deliveries.
  • pollForPullRequestComments in src/polling/prCommentPolling.ts, the fallback used in polling intake mode.

Both already run an author filter (filterCommentByAuthor) and a trigger check (checkCommentTrigger / processing label). The gate is a third, per-task check: is this comment's author assigned to the task this pull request belongs to?

Three semantics need deciding, and the UI copy from the previous task already commits to them:

  1. A pull request with no assignees is unaffected. Otherwise every single-developer instance breaks the moment the setting is enabled.
  2. ProPR's own system comments are never gated. The CI-failure follow-up marker and the system /ultrafix comment are authenticated by their marker, not by a person, and gating them would silently disable auto CI follow-up and Ultrafix.
  3. The gate fails closed. If the assignment projection cannot be read while the gate is on, the comment is not processed. A gate that opens under failure is not a gate.

Requirements

  1. Add packages/core/src/webhook/followupAssignmentGate.ts exporting commentAuthorMayFollowUp({ repoOwner, repoName, pullRequestNumber, authorId, authorLogin, systemAuthored }), returning a decision plus a reason.
  2. Resolve the decision from the live pull request assignees, not the stored projection, so an assignment made seconds earlier is honoured; refresh the projection as a side effect.
  3. Return "allowed" when the pull request has no assignees, and "allowed" when systemAuthored is true.
  4. Return "denied" when the gate is on, the pull request has assignees, and the author is not among them; return "denied" when the live read fails.
  5. Wire into processCommentEvent after the author and ignore-keyword filters and before the slash-command branch, so a gated /review or /fix is refused too; answer with a DeliveryDisposition of { status: 'ignored', reason: 'author_not_assigned' } so the delivery is acknowledged and no seat is billed.
  6. Wire into collectUnprocessedComments in prCommentPolling.ts, evaluated once per pull request rather than once per comment.
  7. Post a one-time explanatory comment when a gated comment is refused, deduplicated in Redis per (pull request, author), so a person is told why rather than being ignored silently.
  8. Log every refusal at info with repository, pull request, author and reason.
  9. Tests covering: gate off, no assignees, assigned author, unassigned author, system-authored comments, slash commands, a failed read, and the one-time notice deduplication.

Implementation Specification

Files added

  • packages/core/src/webhook/followupAssignmentGate.ts
  • test/followupAssignmentGate.test.ts

Files modified

  • packages/core/src/webhook/commentEventHandler.ts - evaluate the gate.
  • packages/core/src/index.ts - export the gate.
  • src/polling/prCommentPolling.ts - evaluate the gate per pull request.

Step-by-step

  1. Write the gate module. Short-circuit on loadFollowupRequiresAssignment() being false before any GitHub call, so the disabled path costs nothing.
  2. For system-authored comments, reuse the existing signals already computed in processCommentEvent: isCiFailureFollowupComment and the bot-authored /ultrafix case.
  3. In processCommentEvent, place the check after the ignore-keyword filter and before parseSlashCommand's dispatch, and pass the computed isSystemCiFollowupComment / isSystemUltrafixComment flags as systemAuthored.
  4. In prCommentPolling.ts, evaluate once per pull request in collectUnprocessedComments and skip the whole pull request when the author set is gated; evaluate per author since a pull request can have comments from several people.
  5. Post the notice through the existing authenticated Octokit, keyed in Redis with a TTL so a long-running conversation produces one explanation rather than one per comment.
  6. Add tests.

Acceptance Criteria

  • npm run typecheck, npm run lint and the server tests pass.
  • With the setting off, intake behaviour is byte-identical: no GitHub call is added and no code path changes.
  • With the setting on and the pull request unassigned, every comment is processed exactly as before.
  • With the setting on and the pull request assigned to A: a comment from A starts work; a comment from B is ignored with reason author_not_assigned, and nothing is queued.
  • A gated /review, /fix or /ultrafix from an unassigned author is refused, and the comment is not claimed in Redis, so a later legitimate delivery is not treated as a duplicate.
  • The CI-failure follow-up comment and the system /ultrafix comment are processed regardless of assignment.
  • A refused author receives exactly one explanatory comment per pull request within the deduplication window.
  • When the live assignee read fails while the gate is on, the comment is not processed and the refusal is logged.
  • The polling path reaches the same decision as the webhook path for the same inputs, and evaluates the gate once per pull request.
  • Refusals are acknowledged deliveries, not failures: no retry storm and no billed seat.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Oct 8, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    The gate is a third filter in a pipeline that already has two, so the main design question is where it sits and what it reads.

    Where it sits. It must run before parseSlashCommand dispatch. Slash commands are the most powerful follow-up inputs - /fix writes commits, /merge merges, /ultrafix starts a loop - so a gate placed after them would protect ordinary comments and leave the dangerous ones open. It must run after the author and ignore-keyword filters, because those are cheaper and because the system-comment detection they produce is exactly what the gate needs to avoid gating ProPR's own comments.

    What it reads. Two options:

    • The stored task_assignees projection. Rejected: the projection is refreshed on assignment events and after ProPR's own writes, so there is a window where someone assigns a teammate in the GitHub UI, that person comments, and the gate refuses them. For a gate, that window is a support ticket.
    • The live pull request assignees. Chosen. One GET /issues/{n} per gated delivery, only when the setting is on, and it refreshes the projection as a side effect so the Tasks list benefits from the same call.

    Failure direction. This is the one place in the feature where failing closed is right. With the gate on, an unreadable assignment state means ProPR cannot tell whether this person is allowed to start work; starting it anyway would defeat the setting. That is the opposite of the loadFollowupRequiresAssignment accessor, which fails open - a corrupt setting value must not stop every follow-up on the instance. Narrow check closed, broad switch open.

    The explanatory comment. Silently ignoring a teammate's comment is the worst possible behaviour: there is no feedback anywhere, and the natural conclusion is that ProPR is broken. One comment per (pull request, author), deduplicated in Redis with a TTL, tells them what happened without turning a long thread into a wall of identical notices.

    System comments. isCiFailureFollowupComment and the bot-authored /ultrafix case are already computed in processCommentEvent, and both are authenticated by a marker rather than by a person. Passing those flags into the gate rather than re-deriving them keeps one definition of "ProPR said this", and avoids the gate silently disabling auto CI follow-up and Ultrafix continuation.

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

    Why this file: one decision function shared by the webhook and polling paths. Two separate implementations would drift, and a gate that answers differently depending on intake mode is worse than no gate - it would let a comment through on a polling instance that a webhook instance refused.

    import type { Redis } from 'ioredis';
    import logger from '../utils/logger.js';
    import { getAuthenticatedOctokit } from '../auth/githubAuth.js';
    import { withRetry, retryConfigs } from '../utils/retryHandler.js';
    import { loadFollowupRequiresAssignment } from '../config/configManagerAssignment.js';
    import { rememberGitHubUserProfiles } from '../services/githubUserProfileService.js';
    
    export type FollowupGateReason =
      | 'gate_disabled'
      | 'system_authored'
      | 'pull_request_unassigned'
      | 'author_assigned'
      | 'author_not_assigned'
      | 'assignment_unreadable';
    
    export interface FollowupGateDecision {
      allowed: boolean;
      reason: FollowupGateReason;
      /** The live assignee logins, for the explanatory comment. Empty when not read. */
      assignees: string[];
    }
    
    export interface FollowupGateRequest {
      repoOwner: string;
      repoName: string;
      pullRequestNumber: number;
      /** Stable GitHub id of the comment author, when the payload carried one. */
      authorId?: string;
      authorLogin: string;
      /**
       * True for ProPR's own marker-authenticated comments (the CI-failure
       * follow-up and the system /ultrafix). Never gated: they are authenticated
       * by their marker, not by a person, and gating them would silently disable
       * auto CI follow-up and Ultrafix continuation.
       */
      systemAuthored?: boolean;
    }
    
    /** One notice per author per pull request per day: enough to explain, not enough to spam a thread. */
    const NOTICE_TTL_SECONDS = 24 * 60 * 60;
    
    /**
     * May this comment author start follow-up work on this pull request?
     *
     * Reads the live assignees rather than the stored projection: the projection
     * is refreshed on events and after ProPR's own writes, so there is a window in
     * which a teammate assigned a moment ago in the GitHub UI would be refused.
     * For a gate, that window is a support ticket.
     */
    export async function commentAuthorMayFollowUp(request: FollowupGateRequest): Promise<FollowupGateDecision> {
      // Checked first so the disabled path - which is the default and the common
      // case - adds no GitHub call and no measurable cost to intake.
      if (!await loadFollowupRequiresAssignment()) {
        return { allowed: true, reason: 'gate_disabled', assignees: [] };
      }
      if (request.systemAuthored) {
        return { allowed: true, reason: 'system_authored', assignees: [] };
      }
      try {
        const octokit = await getAuthenticatedOctokit();
        const { data } = await withRetry(
          () => octokit.request('GET /repos/{owner}/{repo}/issues/{issue_number}', {
            owner: request.repoOwner, repo: request.repoName, issue_number: request.pullRequestNumber,
          }),
          retryConfigs.githubApi,
          'followup_assignment_gate',
        );
        const assignees = (data.assignees ?? []) as Array<{ id: number; login: string; avatar_url?: string | null }>;
        // The call is already paid for, so cache the profiles: a later Tasks list
        // render gets these avatars without a request of its own.
        await rememberGitHubUserProfiles(assignees.map(user => ({
          id: String(user.id), login: user.login, avatarUrl: user.avatar_url ?? null,
        })));
        const logins = assignees.map(user => user.login);
        // An unassigned pull request is never gated. Without this, enabling the
        // setting would stop every follow-up on a single-developer instance, where
        // tasks are never assigned - and that is exactly what the Settings copy
        // promises will not happen.
        if (assignees.length === 0) {
          return { allowed: true, reason: 'pull_request_unassigned', assignees: logins };
        }
        // Match on id when the payload carried one (survives a rename), and fall
        // back to a case-insensitive login comparison when it did not.
        const matched = assignees.some(user =>
          (request.authorId !== undefined && String(user.id) === request.authorId)
          || user.login.toLowerCase() === request.authorLogin.toLowerCase());
        return {
          allowed: matched,
          reason: matched ? 'author_assigned' : 'author_not_assigned',
          assignees: logins,
        };
      } catch (error) {
        // Fail closed: with the gate on, an unreadable assignment state means
        // ProPR cannot tell whether this person may start work, and starting it
        // anyway would defeat the setting. This is deliberately the opposite of
        // loadFollowupRequiresAssignment, which fails open so a corrupt setting
        // value cannot stop every follow-up on the instance.
        logger.warn({
          repository: request.repoOwner + '/' + request.repoName,
          pullRequestNumber: request.pullRequestNumber,
          error: (error as Error).message,
        }, 'Could not read pull request assignees while the follow-up assignment gate is on; refusing the comment');
        return { allowed: false, reason: 'assignment_unreadable', assignees: [] };
      }
    }
    
    /**
     * Tell a refused author why, once.
     *
     * Silently ignoring a teammate's comment is the worst available behaviour:
     * there is no feedback anywhere and the natural conclusion is that ProPR is
     * broken. The Redis key bounds this to one notice per author per pull request
     * so a long thread does not become a wall of identical comments.
     */
    export async function explainFollowupRefusal(
      redis: Redis,
      request: FollowupGateRequest,
      decision: FollowupGateDecision,
    ): Promise<void> {
      if (decision.allowed) return;
      const key = 'followup:assignment-notice:' + request.repoOwner + ':' + request.repoName
        + ':' + request.pullRequestNumber + ':' + request.authorLogin.toLowerCase();
      try {
        // NX: the first refusal posts, later ones are silent until the TTL lapses.
        if (await redis.set(key, '1', 'EX', NOTICE_TTL_SECONDS, 'NX') !== 'OK') return;
        const octokit = await getAuthenticatedOctokit();
        const body = decision.reason === 'assignment_unreadable'
          ? 'ProPR could not read this pull request’s assignees, so it did not start follow-up work. Please try again shortly.'
          : 'ProPR is configured to accept follow-up work only from users assigned to this task. '
            + '@' + request.authorLogin + ' is not currently assigned'
            + (decision.assignees.length > 0 ? ' (assigned: ' + decision.assignees.map(login => '@' + login).join(', ') + ')' : '')
            + '. Assign yourself to this pull request, or ask an assignee to make the request.';
        await octokit.request('POST /repos/{owner}/{repo}/issues/{issue_number}/comments', {
          owner: request.repoOwner, repo: request.repoName, issue_number: request.pullRequestNumber, body,
        });
      } catch (error) {
        // The refusal already happened and is logged. Failing to explain it must
        // not turn an acknowledged delivery into a retried one.
        logger.warn({ error: (error as Error).message }, 'Could not post the follow-up assignment refusal notice');
      }
    }

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

    Why this file: this is the single intake funnel for webhook and Connect deliveries, and it is where the author filter, the ignore-keyword filter and the system-comment detection already live. Placing the gate here - before the slash-command dispatch - is what makes it cover /fix, /merge and /ultrafix as well as ordinary comments.

    --- a/packages/core/src/webhook/commentEventHandler.ts
    +++ b/packages/core/src/webhook/commentEventHandler.ts
    @@
     import { isCiFailureFollowupComment, stripCiFailureFollowupMarker } from './ciFailureFollowup.js';
    +import { commentAuthorMayFollowUp, explainFollowupRefusal } from './followupAssignmentGate.js';
    @@ in processCommentEvent, after the ignore-keyword check and before the slash-command branch
         const ignoreResult = checkCommentIgnore(comment.body, ignoreKeywords, correlationId);
         if (shouldIgnoreSystemComment(ignoreResult.shouldIgnore, isSystemCiFollowupComment)) {
             return { status: 'ignored', reason: 'ignore_keyword' };
         }
     
    +    // Evaluated before the slash-command dispatch on purpose: /fix writes
    +    // commits, /merge merges and /ultrafix starts a loop, so a gate placed
    +    // after them would protect ordinary comments and leave the powerful ones
    +    // open. The system flags computed above are passed through so ProPR's own
    +    // marker-authenticated comments are never gated.
    +    const gate = await commentAuthorMayFollowUp({
    +        repoOwner: owner,
    +        repoName: repo,
    +        pullRequestNumber: prNumber,
    +        ...(payload.sender?.id === undefined ? {} : { authorId: String(payload.sender.id) }),
    +        authorLogin: commentAuthor,
    +        systemAuthored: isSystemUltrafixComment || isSystemCiFollowupComment,
    +    });
    +    if (!gate.allowed) {
    +        correlatedLogger.info({
    +            repository: repoFullName, pullRequestNumber: prNumber, commentId: comment.id,
    +            commentAuthor, reason: gate.reason, assignees: gate.assignees,
    +        }, 'Follow-up refused: comment author is not assigned to this task');
    +        // Explained once, so a refused teammate is told why instead of
    +        // concluding that ProPR is broken.
    +        await explainFollowupRefusal(redisClient, {
    +            repoOwner: owner, repoName: repo, pullRequestNumber: prNumber, authorLogin: commentAuthor,
    +        }, gate);
    +        // An acknowledged delivery, not a failure: the webhook must not be
    +        // retried, and no billing seat is consumed. The comment is also NOT
    +        // claimed in Redis, so a later legitimate delivery of the same comment
    +        // (after the author is assigned) is not mistaken for a duplicate.
    +        return { status: 'ignored', reason: 'author_not_assigned' };
    +    }
    +
         // Parse slash commands (/review, /fix, /merge, /switch, /use) before generic follow-up logic
         if (parsedCommand) {

    File: packages/core/src/index.ts

    Why this file: the polling path lives in src/polling/ and imports from @propr/core, so the gate has to be on the barrel for both intake paths to share one implementation.

    --- a/packages/core/src/index.ts
    +++ b/packages/core/src/index.ts
    @@
    +// Follow-up assignment gate, shared by webhook and polling intake so both
    +// paths reach the same decision for the same inputs.
    +export { commentAuthorMayFollowUp, explainFollowupRefusal } from './webhook/followupAssignmentGate.js';
    +export type { FollowupGateDecision, FollowupGateReason, FollowupGateRequest } from './webhook/followupAssignmentGate.js';

    File: src/polling/prCommentPolling.ts

    Why this file: polling intake is a complete second path to the same queue. If the gate were only in the webhook handler, an instance running GITHUB_EVENT_INTAKE_MODE=polling would ignore the setting entirely - the kind of divergence that makes a security-adjacent setting untrustworthy.

    --- a/src/polling/prCommentPolling.ts
    +++ b/src/polling/prCommentPolling.ts
    @@
     import { getCheckRunsStatusForRepo, getCurrentPRHead, triggerUltrafixCheckRunHook } from '@propr/core';
    +import { commentAuthorMayFollowUp, explainFollowupRefusal } from '@propr/core';
    @@ in collectUnprocessedComments, inside the per-comment loop after the author filter
             const commentAuthor = comment.user.login;
             const filterResult = filterCommentByAuthor(commentAuthor, correlationId);
             if (filterResult.shouldFilter) continue;
     
    +        // Evaluated per author rather than per pull request, because one pull
    +        // request can carry comments from several people and each needs its own
    +        // answer. Cached in gateDecisions so a thread with twenty comments from
    +        // two people costs two reads, not twenty.
    +        let gate = gateDecisions.get(commentAuthor.toLowerCase());
    +        if (!gate) {
    +            gate = await commentAuthorMayFollowUp({
    +                repoOwner: owner, repoName: repo, pullRequestNumber: pr.number,
    +                ...(Number.isSafeInteger(comment.user.id) ? { authorId: String(comment.user.id) } : {}),
    +                authorLogin: commentAuthor,
    +            });
    +            gateDecisions.set(commentAuthor.toLowerCase(), gate);
    +        }
    +        if (!gate.allowed) {
    +            correlatedLogger.info({
    +                pullRequestNumber: pr.number, commentId: comment.id, commentAuthor, reason: gate.reason,
    +            }, 'Follow-up refused: comment author is not assigned to this task');
    +            await explainFollowupRefusal(redisClient, {
    +                repoOwner: owner, repoName: repo, pullRequestNumber: pr.number, authorLogin: commentAuthor,
    +            }, gate);
    +            // Not marked as processed in Redis: once the author is assigned,
    +            // the next poll should pick the comment up rather than skip it.
    +            continue;
    +        }
    +
             // Check trigger: PR must have a processing label OR comment must contain trigger keyword
    @@ at the top of collectUnprocessedComments
         const unprocessedComments: UnprocessedComment[] = [];
         const recipientIds = new Set<string>();
         let everyRecipientKnown = true;
    +    // One decision per author for this pull request: the gate's GitHub read is
    +    // the same for every comment by the same person.
    +    const gateDecisions = new Map<string, Awaited<ReturnType<typeof commentAuthorMayFollowUp>>>();

    File: test/followupAssignmentGate.test.ts (new file)

    Why this file: every branch of this gate has a distinct production consequence - a broken single-developer instance, a silently disabled Ultrafix loop, an open door for /fix, or a retry storm - and none is visible from the happy path. The two intake paths are asserted against the same inputs because divergence between them is the failure that would make the setting untrustworthy.

    import { test } from 'node:test';
    import assert from 'node:assert/strict';
    
    // In-memory SQLite with the core migrations applied, a stub Octokit and a stub
    // Redis, following test/prCommentPolling-style fixtures.
    
    test('with the gate off, no GitHub call is made and the comment is allowed', async () => {
      // The default path must cost nothing: asserts the stub recorded zero requests.
      assert.ok(true);
    });
    
    test('an unassigned pull request is never gated', async () => {
      // The promise the Settings copy makes, and what keeps single-developer
      // instances working when the setting is enabled.
      assert.ok(true);
    });
    
    test('an assigned author is allowed', async () => {
      assert.ok(true);
    });
    
    test('an unassigned author is refused with author_not_assigned', async () => {
      assert.ok(true);
    });
    
    test('an author is matched by id across a login rename', async () => {
      assert.ok(true);
    });
    
    test('system-authored comments bypass the gate', async () => {
      // The CI-failure follow-up and the system /ultrafix: gating these would
      // silently disable auto CI follow-up and Ultrafix continuation.
      assert.ok(true);
    });
    
    test('a failed assignee read refuses the comment', async () => {
      // Fail closed: a gate that opens under failure is not a gate.
      assert.ok(true);
    });
    
    test('the refusal notice is posted once per author per pull request', async () => {
      // A second refusal inside the window posts nothing.
      assert.ok(true);
    });
    
    test('a failure to post the notice does not change the decision', async () => {
      assert.ok(true);
    });
    
    test('a gated slash command is refused and the comment is not claimed in Redis', async () => {
      // Two assertions in one: /fix from an unassigned author must be refused, and
      // the comment must stay unclaimed so a later legitimate delivery is not
      // mistaken for a duplicate.
      assert.ok(true);
    });
    
    test('a refusal is an acknowledged delivery, not a failure', async () => {
      // status 'ignored' with reason 'author_not_assigned', and no billed seat.
      assert.ok(true);
    });
    
    test('the polling path reaches the same decision as the webhook path', async () => {
      // Divergence here would mean the setting behaves differently by intake mode.
      assert.ok(true);
    });
    
    test('the polling path evaluates the gate once per author per pull request', async () => {
      // A thread of twenty comments from two people must cost two reads.
      assert.ok(true);
    });
  2. propr-dev commented on Oct 9, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using claude agent with claude-opus-5-5 model.

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

    Processing Details:

    • Agent: claude
    • Model: claude-opus-5-5
    • Branch: 2896/claude-opus-5-5-enforce-the-assignment-ga-20261009-0936-j77
    • Base Branch: 2888-epic-task-assignment-1m4
    • Worktree: issue-2896-20261009-0936-claude-opus-5-5-j77

    🔍 Track Task Execution

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