Skip to content

MCP: give operation receipts a readable lifecycle (accepted, running, completed, failed, cancelled) with timestamps, artifacts and list_operations #2594

Closed

Description

@propr-dev

Context

run_ultrafix, review_pull_request, comment_on_pull_request, create_task, publish_plan, etc. all return a durable receipt (operationId). The receipt is stored in mcp_operations (packages/api/mcp/operations.ts) with a single free-form state column whose values mix transport concepts (posted, queued, unknown, browser_required) with outcome concepts (completed, failed). get_operation (in packages/api/mcp/tools.ts) re-derives a best-effort state on every poll through trackTaskSubmission, trackExecution and trackCancellation, but:

  • it never records when the work started or finished;
  • it does not persist the transitions it discovers, so a later poll after Redis/job cleanup can regress to unknown;
  • the artefacts the operation produced (task id, pull request, issue numbers, comment id) are scattered across result, result.continuation and targetState;
  • there is no way to list receipts, so a caller who "fired three ultrafix runs in a row" and lost the ids cannot ask "what did I start in the last hour and did any of it finish?".

This issue introduces an explicit, persisted lifecycle. It depends on the error envelope from the previous issue (failures are stored as envelopes).

Requirements

  1. Add persisted lifecycle columns to mcp_operations: lifecycle (accepted | running | completed | failed | cancelled | unknown), accepted_at, started_at, finished_at (epoch ms), failure (JSON envelope), artifacts (JSON), progress (JSON). Backfill existing rows from state in the migration.
  2. The public lifecycle is separate from the legacy state field, which stays for backwards compatibility. Mapping of the legacy value on creation/finish:
    • running (in-flight synchronous call), accepted, posted, queued, browser_required → accepted
    • completed → completed
    • failed → failed
    • unknown → unknown
  3. McpOperations gains monotonic transition helpers: markStarted(id, at?), recordArtifacts(id, partial), recordProgress(id, progress), finish(id, outcome, failure?). Transitions must never move backwards (completed/failed/cancelled are terminal; running never returns to accepted). Use conditional UPDATE ... WHERE lifecycle IN (...) so concurrent pollers cannot race.
  4. project() returns a new lifecycle block on every receipt:
    { "lifecycle": { "state": "running", "acceptedAt": "...", "startedAt": "...", "finishedAt": null,
        "failure": null, "artifacts": { "taskId": "...", "pullRequest": { "repository": "a/b", "number": 42, "url": "..." } },
        "progress": null } }
    Timestamps are ISO 8601 strings in the projection.
  5. get_operation persists what the trackers discover: once receipt.targetState shows the task in processing/claude_execution/post_processing → markStarted; terminal task states → finish; artefacts discovered (taskId, pr_number, issue numbers, commentId) → recordArtifacts. Cancellation receipts resolving to cancellation: 'confirmed' → finish(sourceId, 'cancelled') on the source operation.
  6. New read-only tool list_operations (scope read): filters tool (exact name), lifecycle (one of the states or active = accepted+running), sinceMinutes (1..10080, default 1440), repository; paginated (offset, limit ≤ 50), newest first; scoped to the caller's owner_id + grant_id exactly like get_operation. Each item is the same projection as get_operation without re-running trackers (cheap), plus a hint refreshWith: "get_operation".
  7. Documented guarantee in the tool description: "accepted" means the request was recorded and handed to the backend; "running" means execution was observed; the loop/receipt is only completed when the backend reached a terminal success state.

Implementation Specification

  • New migration packages/core/src/db/migrations/20261001000000_add_mcp_operation_lifecycle.js.
  • Edit packages/api/mcp/operations.ts: extend Operation interface, run() writes lifecycle/accepted_at, add transition helpers, extend project().
  • Edit packages/api/mcp/tools.ts: in get_operation, after the trackers run, call a new syncLifecycle(operations, row, receipt); add the list_operations tool.
  • New helper packages/api/mcp/operationLifecycle.ts with lifecycleFromLegacy, artifactsFromReceipt, syncLifecycle (pure mapping + calls into McpOperations).
  • Tests: extend packages/api/test/mcpOperations.test.ts with lifecycle transitions and add a list_operations test.

Acceptance Criteria

  • New receipts include lifecycle.state === 'accepted' and acceptedAt.
  • Polling a create_task receipt while the associated task is processing persists startedAt; a later poll after the task completed reports completed with finishedAt and artifacts.taskId, even if task_history rows are later pruned.
  • A failed receipt exposes lifecycle.failure equal to the stored error envelope.
  • Transitions are monotonic under two concurrent get_operation calls (test with Promise.all).
  • list_operations({ tool: 'run_ultrafix', lifecycle: 'active' }) returns only the caller's still-open ultrafix receipts; another grant sees none of them.
  • Migration up/down works on SQLite and existing rows are backfilled.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Sep 28, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    We persist a small, explicit state machine next to the legacy state column instead of reinterpreting state. Reusing state was rejected because existing clients (and cancel_operation) branch on values like posted/queued, and changing their meaning would silently break them. A separate lifecycle column is additive: old clients ignore it, new clients get a stable five-state model.

    Transitions are written by whoever observes them first (usually a get_operation poll) using conditional updates. This avoids adding a background sweeper (more moving parts, needs its own lease) while still making observations durable, so a receipt cannot regress when task history is cleaned up or a job is removed from BullMQ.

    File: packages/core/src/db/migrations/20261001000000_add_mcp_operation_lifecycle.js (new file)

    Why this file: The lifecycle must survive restarts and be queryable for list_operations; that requires real columns with an index on (owner_id, grant_id, lifecycle, created_at).

    /**
     * Adds an explicit, monotonic lifecycle to MCP mutation receipts.
     * The legacy `state` column is kept unchanged for backwards compatibility.
     */
    export async function up(knex) {
      await knex.schema.alterTable('mcp_operations', table => {
        table.string('lifecycle', 16).nullable();
        table.bigInteger('accepted_at').nullable();
        table.bigInteger('started_at').nullable();
        table.bigInteger('finished_at').nullable();
        table.text('failure').nullable();   // JSON McpErrorEnvelope
        table.text('artifacts').nullable(); // JSON { taskId, pullRequest, issues, commentId, ... }
        table.text('progress').nullable();  // JSON tool-specific progress (e.g. ultrafix cycles)
      });
      // Backfill: every historic row was accepted when created; terminal legacy
      // states map directly. Unknown stays unknown - we must not invent outcomes.
      await knex.raw(`UPDATE mcp_operations SET accepted_at = created_at,
        lifecycle = CASE state
          WHEN 'completed' THEN 'completed'
          WHEN 'failed' THEN 'failed'
          WHEN 'unknown' THEN 'unknown'
          ELSE 'accepted' END,
        finished_at = CASE WHEN state IN ('completed', 'failed') THEN updated_at ELSE NULL END`);
      await knex.schema.alterTable('mcp_operations', table => {
        table.index(['owner_id', 'grant_id', 'lifecycle', 'created_at'], 'mcp_operations_lifecycle_idx');
      });
    }
    
    export async function down(knex) {
      await knex.schema.alterTable('mcp_operations', table => {
        table.dropIndex(['owner_id', 'grant_id', 'lifecycle', 'created_at'], 'mcp_operations_lifecycle_idx');
        for (const column of ['lifecycle', 'accepted_at', 'started_at', 'finished_at', 'failure', 'artifacts', 'progress']) table.dropColumn(column);
      });
    }

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

    Why this file: Keeps the pure mapping rules (legacy state → lifecycle, receipt → artefacts) out of the already-large tools.ts and makes them unit-testable.

    import type { McpOperations, Operation } from './operations.js';
    
    export type OperationLifecycle = 'accepted' | 'running' | 'completed' | 'failed' | 'cancelled' | 'unknown';
    export const TERMINAL_LIFECYCLES: OperationLifecycle[] = ['completed', 'failed', 'cancelled'];
    const RUNNING_TASK_STATES = ['processing', 'claude_execution', 'post_processing'];
    
    /** Map the legacy transport-oriented state onto the public lifecycle. */
    export function lifecycleFromLegacy(state: string): OperationLifecycle {
      if (state === 'completed') return 'completed';
      if (state === 'failed') return 'failed';
      if (state === 'unknown') return 'unknown';
      if (state === 'cancelled') return 'cancelled';
      return 'accepted';
    }
    
    export interface OperationArtifacts {
      taskId?: string;
      goalId?: string;
      planId?: string;
      submissionId?: string;
      issues?: number[];
      commentId?: number;
      pullRequest?: { repository: string; number: number; url?: string };
    }
    
    /** Collect artefacts from the heterogeneous result/continuation/targetState shapes. */
    export function artifactsFromReceipt(row: Operation, receipt: Record<string, unknown>): OperationArtifacts {
      const result = (receipt.result ?? {}) as Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
      const continuation = (result.continuation ?? {}) as Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
      const target = (receipt.targetState ?? {}) as Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
      const artifacts: OperationArtifacts = {};
      const taskId = continuation.taskId ?? result.taskId ?? target.taskId;
      if (typeof taskId === 'string') artifacts.taskId = taskId;
      if (typeof continuation.goalId === 'string') artifacts.goalId = continuation.goalId;
      if (typeof (continuation.planId ?? result.planId) === 'string') artifacts.planId = continuation.planId ?? result.planId;
      if (typeof result.submissionId === 'string') artifacts.submissionId = result.submissionId;
      if (Array.isArray(result.issues)) {
        artifacts.issues = result.issues.map((issue: unknown) => typeof issue === 'number' ? issue : Number((issue as { number?: number }).number)).filter(Number.isFinite);
      }
      if (typeof result.commentId === 'number') artifacts.commentId = result.commentId;
      const prNumber = Number(target.pr_number ?? target.prNumber ?? result.pullRequest);
      if (row.repository && Number.isSafeInteger(prNumber) && prNumber > 0) {
        artifacts.pullRequest = { repository: row.repository, number: prNumber, url: `https://github.com/${row.repository}/pull/${prNumber}` };
      }
      return artifacts;
    }
    
    /**
     * Persist what this poll observed. Called after trackers updated `receipt`.
     * All writes are conditional and monotonic inside McpOperations.
     */
    export async function syncLifecycle(operations: McpOperations, row: Operation, receipt: Record<string, unknown>): Promise<void> {
      const artifacts = artifactsFromReceipt(row, receipt);
      if (Object.keys(artifacts).length) await operations.recordArtifacts(row.id, artifacts);
      const targetState = (receipt.targetState as { state?: string } | undefined)?.state;
      if (targetState && RUNNING_TASK_STATES.includes(targetState)) await operations.markStarted(row.id);
      const state = String(receipt.state);
      if (state === 'completed') await operations.finish(row.id, 'completed');
      else if (state === 'failed') {
        const error = ((receipt.result ?? {}) as { error?: unknown }).error;
        await operations.finish(row.id, 'failed', error ?? { code: 'EXECUTION_FAILED', message: 'The backend reported the work as failed.', stage: 'workflow', retryable: false, status: 500 });
      } else if (state === 'cancelled') await operations.finish(row.id, 'cancelled');
    }

    File: packages/api/mcp/operations.ts

    Why this file: It owns the mcp_operations table. Transition helpers belong here so every writer uses the same monotonic SQL.

    --- a/packages/api/mcp/operations.ts
    +++ b/packages/api/mcp/operations.ts
    @@ -6,10 +6,13 @@ import type { McpPrincipal } from './policy.js';
     import { classifyError } from './errorEnvelope.js';
    +import { lifecycleFromLegacy, TERMINAL_LIFECYCLES, type OperationArtifacts, type OperationLifecycle } from './operationLifecycle.js';
     
     export interface OperationResult { status: number; data: unknown }
     export interface Operation {
       id: string; owner_id: string; grant_id: string; idempotency_key: string; tool: string; repository: string | null;
       state: string; result: string | null; created_at: number; updated_at: number; payload_hash: string;
    +  lifecycle: OperationLifecycle | null; accepted_at: number | null; started_at: number | null; finished_at: number | null;
    +  failure: string | null; artifacts: string | null; progress: string | null;
     }
    @@ -38,7 +41,8 @@ export class McpOperations {
         const inserted = await this.db('mcp_operations').insert({ ...identity, id, tool, repository: repository || null,
    -      payload_hash: payloadHash, state: 'running', created_at: Date.now(), updated_at: Date.now() }).onConflict(['owner_id', 'grant_id', 'idempotency_key']).ignore().returning('id');
    +      payload_hash: payloadHash, state: 'running', lifecycle: 'accepted', accepted_at: Date.now(),
    +      created_at: Date.now(), updated_at: Date.now() }).onConflict(['owner_id', 'grant_id', 'idempotency_key']).ignore().returning('id');
    @@
           const state = reported === 'browser_required' ? reported : ...;
           await this.db('mcp_operations').where({ id }).update({ state, result: JSON.stringify(result.data), updated_at: Date.now() });
    +      // A synchronous 200 completed the work inside this call; async (202) work
    +      // stays `accepted` until a poll observes execution.
    +      if (lifecycleFromLegacy(state) === 'completed') await this.finish(id, 'completed');
         } catch (error) {
           const envelope = classifyError(error, { sideEffectsPossible: true });
           await this.db('mcp_operations').where({ id }).update({ state: envelope.code === 'OUTCOME_UNKNOWN' ? 'unknown' : 'failed',
             result: JSON.stringify({ error: envelope }), updated_at: Date.now() });
    +      if (envelope.code === 'OUTCOME_UNKNOWN') {
    +        await this.db('mcp_operations').where({ id }).update({ lifecycle: 'unknown', failure: JSON.stringify(envelope) });
    +      } else await this.finish(id, 'failed', envelope);
         }
    @@
    +  /** accepted|unknown -> running. Never moves a terminal receipt. */
    +  async markStarted(id: string, at = Date.now()): Promise<void> {
    +    await this.db('mcp_operations').where({ id }).whereIn('lifecycle', ['accepted', 'unknown'])
    +      .update({ lifecycle: 'running', started_at: at, updated_at: Date.now() });
    +  }
    +
    +  /** Terminal transition. First writer wins; later observations are ignored. */
    +  async finish(id: string, outcome: Extract<OperationLifecycle, 'completed' | 'failed' | 'cancelled'>, failure?: unknown): Promise<void> {
    +    const now = Date.now();
    +    await this.db('mcp_operations').where({ id }).whereNotIn('lifecycle', TERMINAL_LIFECYCLES)
    +      .update({ lifecycle: outcome, finished_at: now, updated_at: now,
    +        // A task that completed without ever being seen running still gets a start time.
    +        started_at: this.db.raw('COALESCE(started_at, ?)', [now]),
    +        ...(failure ? { failure: JSON.stringify(failure) } : {}) });
    +  }
    +
    +  /** Merge newly discovered artefacts; existing keys are never cleared. */
    +  async recordArtifacts(id: string, artifacts: OperationArtifacts): Promise<void> {
    +    const row = await this.db<Operation>('mcp_operations').where({ id }).first('artifacts');
    +    const merged = { ...(row?.artifacts ? JSON.parse(row.artifacts) : {}), ...artifacts };
    +    await this.db('mcp_operations').where({ id }).update({ artifacts: JSON.stringify(merged) });
    +  }
    +
    +  async recordProgress(id: string, progress: Record<string, unknown>): Promise<void> {
    +    await this.db('mcp_operations').where({ id }).update({ progress: JSON.stringify(progress), updated_at: Date.now() });
    +  }
    +
       project(row: Operation): Record<string, unknown> {
         const stale = row.state === 'running' && Date.now() - Number(row.updated_at) > 120_000;
         const state = stale ? 'unknown' : row.state;
    +    const iso = (value: number | null) => value ? new Date(Number(value)).toISOString() : null;
         return { operationId: row.id, tool: row.tool, state, result: row.result ? JSON.parse(row.result) : null,
    +      lifecycle: {
    +        state: row.lifecycle ?? lifecycleFromLegacy(state),
    +        acceptedAt: iso(row.accepted_at ?? row.created_at), startedAt: iso(row.started_at), finishedAt: iso(row.finished_at),
    +        failure: row.failure ? JSON.parse(row.failure) : null,
    +        artifacts: row.artifacts ? JSON.parse(row.artifacts) : {},
    +        progress: row.progress ? JSON.parse(row.progress) : null,
    +      },
           ...([...].includes(state) ? { retryAfterSeconds: 3 } : {}),

    File: packages/api/mcp/tools.ts

    Why this file: get_operation is where trackers run; it must now persist their observations. list_operations sits next to it.

    --- a/packages/api/mcp/tools.ts
    +++ b/packages/api/mcp/tools.ts
    @@
    +import { syncLifecycle } from './operationLifecycle.js';
    @@ tools.push({ name: 'get_operation', ...
         await trackTaskSubmission(deps, row, principal, receipt);
         await trackExecution(deps, row, principal, receipt);
         await trackCancellation(deps, row, principal, receipt);
    @@
         if ([...].includes(String(receipt.state))) receipt.retryAfterSeconds = 3;
         else delete receipt.retryAfterSeconds;
    -    return ok(receipt);
    +    // Make this poll's observations durable and return the refreshed projection
    +    // so `lifecycle` reflects them immediately.
    +    await syncLifecycle(operations, row, receipt);
    +    const fresh = await operations.get(principal, row.id);
    +    receipt.lifecycle = operations.project(fresh).lifecycle;
    +    return ok(receipt);
       } });
    +  tools.push({ name: 'list_operations', description: 'List your recent mutation receipts, newest first, with their persisted lifecycle (accepted = recorded and handed to the backend, running = execution observed, completed/failed/cancelled = terminal). Use lifecycle=active for work that has not finished. This read does not re-poll the backend; call get_operation on an item to refresh it.', scope: 'read', readOnly: true,
    +    schema: z.object({ tool: z.string().regex(/^[a-z_]{3,64}$/).optional(), repository: repositorySchema.optional(),
    +      lifecycle: z.enum(['active', 'accepted', 'running', 'completed', 'failed', 'cancelled', 'unknown']).optional(),
    +      sinceMinutes: z.number().int().min(1).max(10080).default(1440), offset: z.number().int().min(0).max(10000).default(0),
    +      limit: z.number().int().min(1).max(50).default(20) }).strict(),
    +    run: async ({ principal, args }) => {
    +      // Same ownership boundary as get_operation: owner AND grant.
    +      const query = db<Operation>('mcp_operations').where({ owner_id: principal.user.id, grant_id: principal.grant.id })
    +        .where('created_at', '>=', Date.now() - args.sinceMinutes * 60_000);
    +      if (args.tool) query.where('tool', args.tool);
    +      if (args.repository) { await policy.repository(principal, args.repository); query.where('repository', args.repository); }
    +      if (args.lifecycle === 'active') query.whereIn('lifecycle', ['accepted', 'running']);
    +      else if (args.lifecycle) query.where('lifecycle', args.lifecycle);
    +      const rows = await query.orderBy('created_at', 'desc').orderBy('id', 'desc').offset(args.offset).limit(args.limit);
    +      return ok({ operations: rows.map(row => ({ ...operations.project(row), refreshWith: 'get_operation' })),
    +        nextOffset: rows.length === args.limit ? args.offset + args.limit : null });
    +    } });

    Also, in cancel_operation/trackCancellation: when the cancellation receipt resolves with result.cancellation === 'confirmed', call await operations.finish(sourceOperationId, 'cancelled') for the source receipt.

    File: packages/api/test/mcpOperations.test.ts

    Why this file: Existing durability tests live here; lifecycle monotonicity must be tested at the same level with a real SQLite file.

    test('lifecycle transitions are monotonic and persisted', async () => {
      // ...same setup as the existing test, running migrations including 20261001000000...
      const receipt = await operations.run(principal, { tool: 'create_task', args: { idempotencyKey: 'lifecycle-key-1' }, repository: 'acme/repo' },
        async () => ({ status: 202, data: { state: 'queued' } }));
      assert.equal((receipt.lifecycle as { state: string }).state, 'accepted');
      const id = String(receipt.operationId);
      await Promise.all([operations.markStarted(id), operations.markStarted(id)]);
      await Promise.all([operations.finish(id, 'completed'), operations.finish(id, 'failed', { code: 'X' })]);
      const row = await operations.get(principal, id);
      const lifecycle = operations.project(row).lifecycle as Record<string, unknown>;
      assert.ok(['completed', 'failed'].includes(String(lifecycle.state)));
      assert.ok(lifecycle.startedAt && lifecycle.finishedAt);
      await operations.markStarted(id); // must not reopen a terminal receipt
      assert.equal((operations.project(await operations.get(principal, id)).lifecycle as { state: string }).state, lifecycle.state);
    });
  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: 2594/gpt-5.6-sol-mcp-give-operation-receip-20260929-0054-naw
    • Base Branch: 2593-epic-mcp-observability-cf6
    • Worktree: issue-2594-20260929-0054-gpt-5.6-sol-naw

    🔍 Track Task Execution

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