Skip to content

MCP: track PR command receipts to completion and report ultrafix cycle progress and final outcome #2595

Closed

Description

@propr-dev

Context

run_ultrafix, review_pull_request, fix_review_findings and comment_on_pull_request (all in packages/api/mcp/toolsPullRequests.ts) post a GitHub comment and return { state: 'posted', commentId }. The existing trackExecution in packages/api/mcp/operationTracking.ts links the receipt to a task by the triggering comment id and follows it, but the receipt never says:

  • whether the command was actually picked up (a worker task exists for this comment),
  • for ultrafix: which cycle the loop is on, the latest review score, the goal, and whether it ended because it reached its goal, exhausted its cycles, was stopped (label removed via stop_ultrafix or by a human), or failed.

The user story from the request: "having fired three ultrafix runs in a row, the caller could not afterwards confirm whether any of them had actually started, were still cycling, had completed, or had quietly given up." With the lifecycle from the previous issue, this issue fills in lifecycle.state, lifecycle.artifacts and lifecycle.progress for PR commands.

Requirements

  1. Pick-up detection for all four PR command tools: once a task whose persisted job data references the receipt's commentId exists, the receipt moves to running (markStarted) and artifacts.taskId is recorded. If no task appears within 10 minutes of posting (configurable constant PICKUP_DEADLINE_MS), lifecycle.failure is set to { code: 'COMMAND_NOT_PICKED_UP', stage: 'queue', retryable: true, message: 'No worker picked up the command comment. Check that event intake is running (get_setup_status) and that the PR carries a processing label or the author is allowed.' } and the lifecycle becomes unknown (not failed — the webhook may still arrive).
  2. Ultrafix progress (run_ultrafix only): compute from the tasks belonging to this loop's work epoch (the existing epoch logic in trackExecution) and their task_history.metadata:
    { "kind": "ultrafix", "goal": 9, "maxCycles": 3, "cycle": 2, "lastScore": 7,
      "phase": "review" | "fix" | "waiting_for_ci" | "paused" | "done",
      "outcome": null | "goal_reached" | "cycles_exhausted" | "stopped" | "failed",
      "cycles": [{ "cycle": 1, "reviewTaskId": "...", "fixTaskId": "...", "score": 5 }] }
    Recorded with operations.recordProgress. cycles bounded to the last 10.
  3. Ultrafix terminal outcome is persisted durably by the worker (not inferred from absence): when the ultrafix loop ends, the worker appends a task_history entry (or metadata on the final state entry) with { ultrafixOutcome, ultrafixCycle, ultrafixScore, ultrafixGoal, ultrafixMaxCycles }. The MCP tracker maps it: goal_reached → completed; cycles_exhausted → completed with progress.outcome = 'cycles_exhausted' (the loop behaved correctly; the goal was not met — this must be visible, not hidden as success); stopped → cancelled; failed → failed with failure envelope { code: 'ULTRAFIX_CYCLE_FAILED', stage: 'workflow' } and the failing task id in details.
  4. Review / fix / comment receipts: completed when the linked task is terminal-successful; artifacts include the posted review comment id (review) or the new head SHA (fix), which trackExecution already discovers.
  5. The receipt text should be self-explanatory: add lifecycle.summary — a one-line human sentence, e.g. "Ultrafix cycle 2 of 3 is reviewing; last score 7/10 (goal 9)." or "Ultrafix stopped after exhausting 3 cycles; last score 7/10 did not reach goal 9."
  6. stop_ultrafix receipts, when they cleared the label on a PR that has an open run_ultrafix receipt from the same grant, mark that loop's progress phase: 'stopping' so the caller sees the relationship.

Implementation Specification

  • New module packages/api/mcp/commandProgress.ts with ultrafixProgress(db, { repository, pullRequest, sinceMs, goal, maxCycles }), summarizeLifecycle(tool, lifecycle), detectPickup(...).
  • Edit packages/api/mcp/operationTracking.ts (trackExecution): call into commandProgress for the four PR tools, then operations.recordProgress / markStarted / finish.
  • Worker side: locate the ultrafix loop continuation/termination code in src/ (search for ultrafix and for the "max cycles exhausted" warning comment and the code that removes the ultrafix label when the goal is reached). At each terminal branch, write the outcome metadata described above through the existing worker state manager (packages/core/src/utils/workerStateManager*) so it lands in task_history.metadata. When the label is found missing before starting the next cycle, record stopped.
  • Tests: packages/api/test/mcpCommandProgress.test.ts with seeded tasks/task_history rows for each outcome.

Acceptance Criteria

  • A run_ultrafix receipt with no linked task after 10 minutes shows COMMAND_NOT_PICKED_UP and retryable: true.
  • With seeded history for cycle 2 in review, get_operation returns progress.cycle === 2, phase === 'review', lifecycle.state === 'running'.
  • Seeded ultrafixOutcome: 'cycles_exhausted' yields lifecycle.state === 'completed', progress.outcome === 'cycles_exhausted', and a summary stating the goal was not reached.
  • Seeded ultrafixOutcome: 'stopped' yields cancelled.
  • Three ultrafix receipts on the same PR resolve to their own epochs (an earlier receipt cannot be satisfied by a later loop — existing guarantee preserved).
  • list_operations({ tool: 'run_ultrafix' }) shows progress for each without extra GitHub calls.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Sep 28, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    We compute progress from ProPR's own persisted task history rather than from GitHub comments. Parsing PR comments on every poll was rejected: it costs GitHub API quota, comment prose is untrusted, and comments can be edited or deleted. Task history already records each review/fix task of the loop; the only missing fact is why the loop ended, which today only exists as a GitHub warning comment. We therefore make the worker write an explicit, durable ultrafixOutcome marker — cheap to add and removes all guessing ("quietly gave up") from the MCP side.

    Progress is written back through recordProgress (from the lifecycle issue), so list_operations can show it without re-polling.

    File: packages/api/mcp/commandProgress.ts (new file)

    Why this file: Isolates the ultrafix/PR-command interpretation of task history from the generic tracker, keeping operationTracking.ts readable and the logic unit-testable with plain DB fixtures.

    import type { Knex } from 'knex';
    
    export const PICKUP_DEADLINE_MS = 10 * 60_000;
    export type UltrafixOutcome = 'goal_reached' | 'cycles_exhausted' | 'stopped' | 'failed';
    export type UltrafixPhase = 'review' | 'fix' | 'waiting_for_ci' | 'paused' | 'stopping' | 'done';
    
    export interface UltrafixProgress {
      kind: 'ultrafix';
      goal: number;
      maxCycles: number;
      cycle: number;
      lastScore: number | null;
      phase: UltrafixPhase;
      outcome: UltrafixOutcome | null;
      failedTaskId?: string;
      cycles: Array<{ cycle: number; reviewTaskId?: string; fixTaskId?: string; score?: number | null }>;
    }
    
    const TERMINAL = ['completed', 'failed', 'cancelled'];
    
    function parseMetadata(value: unknown): Record<string, unknown> {
      try { return typeof value === 'string' ? JSON.parse(value) : (value as Record<string, unknown>) ?? {}; } catch { return {}; }
    }
    
    /**
     * Rebuild loop progress from the tasks of one ultrafix work epoch.
     * `taskIds` must already be restricted to this receipt's epoch by the caller
     * (trackExecution owns epoch selection so a newer loop cannot satisfy an older receipt).
     */
    export async function ultrafixProgress(db: Knex, options: { taskIds: string[]; goal: number; maxCycles: number }): Promise<UltrafixProgress> {
      const progress: UltrafixProgress = { kind: 'ultrafix', goal: options.goal, maxCycles: options.maxCycles, cycle: 0,
        lastScore: null, phase: 'review', outcome: null, cycles: [] };
      if (!options.taskIds.length) return progress;
      const rows = await db('task_history').whereIn('task_id', options.taskIds)
        .orderBy('history_id', 'asc').select('task_id', 'state', 'metadata');
      const byCycle = new Map<number, UltrafixProgress['cycles'][number]>();
      let lastState: string | undefined;
      for (const row of rows) {
        const meta = parseMetadata(row.metadata);
        const cycle = Number(meta.ultrafixCycleNumber ?? meta.cycle ?? meta.ultrafixCycle);
        if (Number.isSafeInteger(cycle) && cycle > 0) {
          const entry = byCycle.get(cycle) ?? { cycle };
          // commandMode distinguishes the review half from the fix half of a cycle.
          if (meta.commandMode === 'review') entry.reviewTaskId = row.task_id;
          if (meta.commandMode === 'fix') entry.fixTaskId = row.task_id;
          const score = Number(meta.ultrafixScore ?? meta.score);
          if (Number.isFinite(score)) { entry.score = score; progress.lastScore = score; }
          byCycle.set(cycle, entry);
          progress.cycle = Math.max(progress.cycle, cycle);
          progress.phase = meta.commandMode === 'fix' ? 'fix' : 'review';
        }
        if (typeof meta.ultrafixOutcome === 'string') {
          progress.outcome = meta.ultrafixOutcome as UltrafixOutcome;
          progress.phase = 'done';
        }
        if (row.state === 'failed' && !progress.outcome) { progress.failedTaskId = row.task_id; }
        if (meta.nextAction === 'waiting_for_ci') progress.phase = 'waiting_for_ci';
        lastState = row.state;
      }
      // A failed cycle without an explicit outcome still ends the loop: the worker
      // does not start another cycle after a failed task.
      if (!progress.outcome && progress.failedTaskId && lastState && TERMINAL.includes(lastState)) {
        progress.outcome = 'failed';
        progress.phase = 'done';
      }
      progress.cycles = [...byCycle.values()].sort((a, b) => a.cycle - b.cycle).slice(-10);
      return progress;
    }
    
    /** Lifecycle outcome implied by a finished loop. cycles_exhausted is a completed loop that missed its goal. */
    export function lifecycleForUltrafix(progress: UltrafixProgress): 'completed' | 'cancelled' | 'failed' | null {
      switch (progress.outcome) {
        case 'goal_reached': case 'cycles_exhausted': return 'completed';
        case 'stopped': return 'cancelled';
        case 'failed': return 'failed';
        default: return null;
      }
    }
    
    /** One human sentence an agent can relay verbatim. */
    export function summarizeUltrafix(p: UltrafixProgress): string {
      const score = p.lastScore == null ? 'no score yet' : `last score ${p.lastScore}/10`;
      switch (p.outcome) {
        case 'goal_reached': return `Ultrafix reached its goal of ${p.goal} in cycle ${p.cycle} (${score}).`;
        case 'cycles_exhausted': return `Ultrafix stopped after exhausting ${p.maxCycles} cycles; ${score} did not reach goal ${p.goal}.`;
        case 'stopped': return `Ultrafix was stopped (circuit breaker label removed) during cycle ${p.cycle}; ${score}.`;
        case 'failed': return `Ultrafix cycle ${p.cycle} failed (task ${p.failedTaskId ?? 'unknown'}); ${score}.`;
        default: return p.cycle === 0
          ? 'Ultrafix has been picked up and is starting its first review.'
          : `Ultrafix cycle ${p.cycle} of ${p.maxCycles} is ${p.phase === 'fix' ? 'applying fixes' : p.phase === 'waiting_for_ci' ? 'waiting for CI' : 'reviewing'}; ${score} (goal ${p.goal}).`;
      }
    }
    
    export function pickupOverdue(createdAt: number, hasTask: boolean, now = Date.now()): boolean {
      return !hasTask && now - createdAt > PICKUP_DEADLINE_MS;
    }

    File: packages/api/mcp/operationTracking.ts

    Why this file: trackExecution already resolves which tasks belong to a PR command receipt (by exact comment id and work epoch). We extend it rather than re-implementing that association.

    Inside trackExecution, after the existing code has determined the linked task ids for a PR command receipt (call that list epochTaskIds), add:

    import { PICKUP_DEADLINE_MS, lifecycleForUltrafix, pickupOverdue, summarizeUltrafix, ultrafixProgress } from './commandProgress.js';
    import { McpOperations } from './operations.js';
    
    const PR_COMMAND_TOOLS = ['run_ultrafix', 'review_pull_request', 'fix_review_findings', 'comment_on_pull_request'];
    
    // ...inside trackExecution(deps, row, principal, receipt), for PR command tools:
    if (PR_COMMAND_TOOLS.includes(row.tool)) {
      const operations = new McpOperations(deps.db);
      if (epochTaskIds.length) {
        // The command comment was consumed by a worker: that is "started".
        await operations.markStarted(row.id);
        await operations.recordArtifacts(row.id, { taskId: epochTaskIds[epochTaskIds.length - 1] });
      } else if (pickupOverdue(Number(row.created_at), false)) {
        // Not failed: a delayed webhook may still arrive. Tell the caller what to check.
        await deps.db('mcp_operations').where({ id: row.id }).whereIn('lifecycle', ['accepted'])
          .update({ lifecycle: 'unknown', failure: JSON.stringify({ code: 'COMMAND_NOT_PICKED_UP', stage: 'queue', retryable: true, status: 504,
            message: `No worker picked up the command comment within ${PICKUP_DEADLINE_MS / 60000} minutes. Check event intake (get_setup_status) and that the PR carries a processing label or the author is allowed.` }) });
      }
      if (row.tool === 'run_ultrafix') {
        const args = row.result ? JSON.parse(row.result) : {};
        const progress = await ultrafixProgress(deps.db, { taskIds: epochTaskIds, goal: Number(args.goal ?? 9), maxCycles: Number(args.maxCycles ?? 3) });
        await operations.recordProgress(row.id, { ...progress, summary: summarizeUltrafix(progress) });
        const outcome = lifecycleForUltrafix(progress);
        if (outcome === 'failed') {
          await operations.finish(row.id, 'failed', { code: 'ULTRAFIX_CYCLE_FAILED', stage: 'workflow', retryable: true, status: 500,
            message: summarizeUltrafix(progress), details: { taskId: progress.failedTaskId, cycle: progress.cycle } });
        } else if (outcome) await operations.finish(row.id, outcome);
        receipt.state = outcome ?? receipt.state; // keep legacy state consistent for old clients
      }
    }

    The run_ultrafix receipt must include goal and maxCycles in its stored result so the tracker knows the target. Update toolsPullRequests.ts so the returned data for ultrafix adds goal: args.goal, maxCycles: args.maxCycles (it already returns repository, pullRequest, commentId).

    In stop_ultrafix, after removing the label, mark any active run_ultrafix receipt for the same PR and grant as stopping (progress only — the worker's stopped marker finalises it):

    const active = await deps.db('mcp_operations').where({ owner_id: principal.user.id, grant_id: principal.grant.id, tool: 'run_ultrafix', repository: args.repository })
      .whereIn('lifecycle', ['accepted', 'running']).select('id', 'result', 'progress');
    for (const operation of active) {
      const result = operation.result ? JSON.parse(operation.result) : {};
      if (Number(result.pullRequest) !== args.pullRequest) continue;
      const progress = operation.progress ? JSON.parse(operation.progress) : {};
      await deps.db('mcp_operations').where({ id: operation.id }).update({ progress: JSON.stringify({ ...progress, phase: 'stopping' }) });
    }

    File: worker ultrafix loop (in src/, locate by searching for ultrafix and the "max cycles" warning comment)

    Why this file: Only the worker knows why the loop ended. Persisting an explicit marker turns "quietly gave up" into an observable fact.

    At each loop exit point, record a history entry through the existing worker state manager (the same API that writes ultrafixCycle/commandMode metadata today):

    // Pseudocode — adapt to the existing continuation function's variables.
    async function recordUltrafixOutcome(stateManager, taskId: string, outcome: 'goal_reached' | 'cycles_exhausted' | 'stopped' | 'failed',
      context: { cycle: number; score: number | null; goal: number; maxCycles: number }) {
      // Written as metadata on a history row so MCP receipts can resolve the loop
      // outcome from the database alone, without reading PR comments.
      await stateManager.appendHistoryMetadata(taskId, {
        ultrafixOutcome: outcome,
        ultrafixCycle: true,
        ultrafixCycleNumber: context.cycle,
        ultrafixScore: context.score,
        ultrafixGoal: context.goal,
        ultrafixMaxCycles: context.maxCycles,
      });
    }
    // goal reached branch (where the `ultrafix` label is removed):  recordUltrafixOutcome(..., 'goal_reached', ...)
    // max cycles branch (where the warning comment is posted):      recordUltrafixOutcome(..., 'cycles_exhausted', ...)
    // label missing before next cycle (circuit breaker):            recordUltrafixOutcome(..., 'stopped', ...)

    If the state manager has no metadata-append helper, add the outcome to the metadata of the terminal state update that already happens at these points; do not add a new table.

    File: packages/api/test/mcpCommandProgress.test.ts (new file)

    Why this file: Verifies each outcome mapping and the summary text against seeded history, independent of GitHub.

    import assert from 'node:assert/strict';
    import { test } from 'node:test';
    import knex from 'knex';
    import { lifecycleForUltrafix, summarizeUltrafix, ultrafixProgress } from '../mcp/commandProgress.js';
    
    async function seeded(rows: Array<{ task_id: string; state: string; metadata: Record<string, unknown> }>) {
      const db = knex({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true });
      await db.schema.createTable('task_history', t => { t.increments('history_id'); t.string('task_id'); t.string('state'); t.text('metadata'); });
      await db('task_history').insert(rows.map(row => ({ ...row, metadata: JSON.stringify(row.metadata) })));
      return db;
    }
    
    test('reports the current cycle while running', async () => {
      const db = await seeded([
        { task_id: 'r1', state: 'completed', metadata: { commandMode: 'review', ultrafixCycleNumber: 1, ultrafixScore: 5 } },
        { task_id: 'f1', state: 'completed', metadata: { commandMode: 'fix', ultrafixCycleNumber: 1 } },
        { task_id: 'r2', state: 'processing', metadata: { commandMode: 'review', ultrafixCycleNumber: 2 } },
      ]);
      const progress = await ultrafixProgress(db, { taskIds: ['r1', 'f1', 'r2'], goal: 9, maxCycles: 3 });
      assert.equal(progress.cycle, 2);
      assert.equal(progress.phase, 'review');
      assert.equal(progress.lastScore, 5);
      assert.equal(lifecycleForUltrafix(progress), null);
      await db.destroy();
    });
    
    test('cycles_exhausted completes but says the goal was missed', async () => {
      const db = await seeded([{ task_id: 'r3', state: 'completed', metadata: { commandMode: 'review', ultrafixCycleNumber: 3, ultrafixScore: 7, ultrafixOutcome: 'cycles_exhausted' } }]);
      const progress = await ultrafixProgress(db, { taskIds: ['r3'], goal: 9, maxCycles: 3 });
      assert.equal(lifecycleForUltrafix(progress), 'completed');
      assert.match(summarizeUltrafix(progress), /did not reach goal 9/);
      await db.destroy();
    });
    
    test('stopped maps to cancelled and failures to failed', async () => {
      const stopped = await seeded([{ task_id: 'r1', state: 'completed', metadata: { ultrafixCycleNumber: 1, ultrafixOutcome: 'stopped' } }]);
      assert.equal(lifecycleForUltrafix(await ultrafixProgress(stopped, { taskIds: ['r1'], goal: 9, maxCycles: 3 })), 'cancelled');
      const failed = await seeded([{ task_id: 'f1', state: 'failed', metadata: { commandMode: 'fix', ultrafixCycleNumber: 1 } }]);
      assert.equal(lifecycleForUltrafix(await ultrafixProgress(failed, { taskIds: ['f1'], goal: 9, maxCycles: 3 })), 'failed');
      await stopped.destroy(); await failed.destroy();
    });
  2. propr-dev commented on Sep 29, 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: 2595/gpt-5.6-sol-mcp-track-pr-command-rece-20260929-0951-b2i
    • Base Branch: 2593-epic-mcp-observability-cf6
    • Worktree: issue-2595-20260929-0951-gpt-5.6-sol-b2i

    🔍 Track Task Execution

  3. added a commit that references this issue on Sep 29, 2026
  4. added a commit that references this issue on Sep 29, 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