Skip to content

MCP publish_plan: record per-issue failure stage, release the draft on clean failure, and support resuming a partial publication #2596

Closed

Description

@propr-dev

Context

publish_plan in packages/api/mcp/toolsPlanning.ts claims the draft by setting status = 'executing', then creates one GitHub issue per plan task in a loop. If anything throws inside the loop (GitHub 422 on a label, a rate limit, policy.repository rejecting a revoked grant, a SQLite busy error while inserting plan_issues), the error escapes to McpOperations.run, which recorded OUTCOME_UNKNOWN. Two problems follow, both observed in practice:

  1. No failure detail — solved generically by the error envelope issue, but publish_plan should add which task index and which step failed and how many issues were already created.
  2. The draft is stuck in executing forever. Every later publish_plan fails with PRECONDITION_FAILED: Plan is already published or busy, update_plan refuses it, and there is no supported way out. That is why "two plans failed to publish several times".

Requirements

  1. Validate the plan before claiming the draft; an invalid plan fails with PLAN_INVALID (stage validation) and details.incomplete = [{ index, title, missing: ['body'|'implementation'|...] }]. Nothing is claimed.
  2. Remember the status the draft had before the claim (draft/review/approved).
  3. Wrap each issue creation and each plan_issues insert. On failure:
    • If zero issues were created: restore the previous status (conditional on status = 'executing' and unchanged mcp_revision) and throw PUBLISH_FAILED with stage from the classified cause, retryable from the cause (e.g. rate limit → true), and details: { failedIndex, failedTitle, step: 'create_issue' | 'record_issue' | 'authorize', createdIssues: [] , cause: { code, message } }.
    • If some issues were created: keep executing, persist context_config.publication = { state: 'partial', operationId, created: [{index, number, url}], failedIndex, failedAt, cause }, and throw PUBLISH_PARTIAL (stage github, retryable: false) with the same details and a message telling the caller to call publish_plan again with resume: true.
  4. Add optional resume: boolean (default false) to publish_plan. With resume: true, the tool accepts a draft that is executing and has publication.state === 'partial'; it skips indexes already recorded in plan_issues/publication.created, and before creating each remaining issue checks GitHub for an existing issue carrying the marker <!-- propr-mcp:<originalOperationId>:<index> --> (search the repository issue list filtered by the propr-planned label, newest first, bounded to 100) so an issue created during an uncertain network failure is adopted instead of duplicated. expectedRevision must still match.
  5. On success, clear publication and set executed as today; return { planId, issues, resumed: boolean, adopted: number[] }.
  6. get_plan exposes publication (state, created count, failedIndex, cause) so the caller can see a stuck/partial plan without reading receipts.

Implementation Specification

  • Edit packages/api/mcp/toolsPlanning.ts (publish_plan, get_plan).
  • New small helper in the same file or packages/api/mcp/planPublication.ts: findMarkedIssue(principal, repository, operationId, index).
  • Use McpError options (stage, retryable, details) from the error envelope issue.
  • Tests: extend the planning MCP test (or new packages/api/test/mcpPublishPlan.test.ts) with a fake principal.github.request that fails on the 2nd issue, then succeeds on resume; and one that fails on the 1st issue and proves the draft returned to review.

Acceptance Criteria

  • A GitHub 422 on the first issue returns PUBLISH_FAILED with details.failedIndex === 0 and details.cause.code === 'GITHUB_REJECTED'; the draft is back to its previous status and can be published again.
  • A failure on the second of three issues returns PUBLISH_PARTIAL with one created issue; get_plan shows publication.state === 'partial'.
  • publish_plan({ resume: true }) creates only the remaining issues, adopts a marked issue that already exists on GitHub, and ends with status === 'executed' and three plan_issues rows (no duplicates).
  • resume: true on a draft that is not partially published fails with PRECONDITION_FAILED and a message explaining why.
  • Invalid plans fail with PLAN_INVALID before any claim.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Sep 28, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    We keep publication a single MCP tool but make its failure modes explicit and recoverable. The alternatives were (a) a background publisher job, rejected as a much larger change that still needs the same recovery semantics, and (b) a separate reset_plan_publication tool, rejected because it lets a caller "unstick" a draft that may already have public issues, creating duplicates. A resume that adopts marker-tagged issues is safe precisely because every issue body already carries <!-- propr-mcp:<operationId>:<index> -->.

    We roll back the claim only when we know nothing was created (zero successful POSTs and the failure happened before or on the first POST with a classified, non-transport error). If the very first POST failed with a transport error, it may have been created, so we treat it as partial with created: [] and require resume, which will adopt it via the marker.

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

    Why this file: Keeps the marker search and publication-state helpers out of the already long planning tool file and makes them reusable by the resume path and tests.

    import type { McpPrincipal } from './policy.js';
    
    export interface PublicationState {
      state: 'partial';
      operationId: string;
      created: Array<{ index: number; number: number; url: string }>;
      failedIndex: number;
      failedAt: string;
      cause: { code: string; message: string } | null;
    }
    
    export const issueMarker = (operationId: string, index: number) => `<!-- propr-mcp:${operationId}:${index} -->`;
    
    /**
     * Find an issue a previous (possibly uncertain) attempt already created.
     * Bounded to the newest 100 `propr-planned` issues so a resume never scans a
     * whole repository.
     */
    export async function findMarkedIssue(principal: McpPrincipal, repository: string, operationId: string, index: number)
      : Promise<{ number: number; url: string; title: string } | null> {
      const [owner, repo] = repository.split('/');
      const { data } = await principal.github.request('GET /repos/{owner}/{repo}/issues', {
        owner, repo, labels: 'propr-planned', state: 'all', sort: 'created', direction: 'desc', per_page: 100,
      });
      const marker = issueMarker(operationId, index);
      const found = (data as Array<{ number: number; html_url: string; title: string; body?: string | null; pull_request?: unknown }>)
        .find(issue => !issue.pull_request && issue.body?.includes(marker));
      return found ? { number: found.number, url: found.html_url, title: found.title } : null;
    }
    
    export function readPublication(contextConfig: unknown): PublicationState | null {
      try {
        const parsed = typeof contextConfig === 'string' ? JSON.parse(contextConfig) : contextConfig;
        return parsed?.publication?.state === 'partial' ? parsed.publication : null;
      } catch { return null; }
    }

    File: packages/api/mcp/toolsPlanning.ts

    Why this file: Hosts publish_plan and get_plan. All changes are local to those two tools.

    --- a/packages/api/mcp/toolsPlanning.ts
    +++ b/packages/api/mcp/toolsPlanning.ts
    @@
     import { getPlanRevision, listPlanRevisions, restorePlanRevision } from '../routes/plannerHelpers/planRevisions.js';
    +import { classifyError } from './errorEnvelope.js';
    +import { findMarkedIssue, issueMarker, readPublication, type PublicationState } from './planPublication.js';
    @@ tools.push({ name: 'get_plan', ...
    -      return ok({ ...draft, attachments: ..., plan: ..., plan_json: undefined, issues: await db('plan_issues').where({ draft_id: args.planId }).limit(100) });
    +      const publication = readPublication((await db('task_drafts').where({ draft_id: args.planId }).first('context_config'))?.context_config);
    +      return ok({ ...draft, attachments: ..., plan: ..., plan_json: undefined, issues: await db('plan_issues').where({ draft_id: args.planId }).limit(100),
    +        // Surface a stuck/partial publication directly on the plan.
    +        publication: publication ? { state: publication.state, created: publication.created.length, failedIndex: publication.failedIndex, cause: publication.cause,
    +          next: 'Call publish_plan with resume: true and the current revision to finish publishing.' } : null });
         } });
    @@
    -  tools.push({ name: 'publish_plan', description: 'Publish your approved plan as GitHub issues without starting implementation. Requires the exact revision.', scope: 'publish', target,
    -    schema: z.object({ ...mutationShape, ...planShape, expectedRevision: z.number().int().min(0) }).strict(), run: async ({ principal, args, operationId }) => {
    -      const draft = await db('task_drafts').where({ draft_id: args.planId, mcp_revision: args.expectedRevision }).first();
    -      if (!draft) throw new McpError('STALE_REVISION', 'Plan revision changed.', 409);
    -      const tasks = plan.parse(JSON.parse(draft.plan_json || '[]'));
    -      const claimed = ...
    +  tools.push({ name: 'publish_plan', description: 'Publish your approved plan as GitHub issues without starting implementation. Requires the exact revision. If a previous attempt stopped part-way (get_plan shows publication.state = partial), call again with resume: true to finish without duplicating issues.', scope: 'publish', target,
    +    schema: z.object({ ...mutationShape, ...planShape, expectedRevision: z.number().int().min(0), resume: z.boolean().default(false) }).strict(), run: async ({ principal, args, operationId }) => {
    +      const draft = await db('task_drafts').where({ draft_id: args.planId, mcp_revision: args.expectedRevision }).first();
    +      if (!draft) throw new McpError('STALE_REVISION', 'Plan revision changed.', 409, { stage: 'precondition' });
    +      // Validate before claiming so a malformed plan never locks the draft.
    +      const parsed = plan.safeParse(JSON.parse(draft.plan_json || '[]'));
    +      if (!parsed.success) {
    +        const incomplete = parsed.error.issues.map(issue => ({ index: Number(issue.path[0]), field: String(issue.path[1] ?? ''), message: issue.message }));
    +        throw new McpError('PLAN_INVALID', 'The plan has tasks missing a title, body or implementation. Fix them with update_plan before publishing.', 400,
    +          { stage: 'validation', details: { incomplete: incomplete.slice(0, 20) } });
    +      }
    +      const tasks = parsed.data;
    +      const previous = readPublication(draft.context_config);
    +      if (args.resume && !(draft.status === 'executing' && previous)) {
    +        throw new McpError('PRECONDITION_FAILED', 'resume: true only applies to a plan whose publication stopped part-way (get_plan shows publication.state = partial).', 409, { stage: 'precondition' });
    +      }
    +      const previousStatus = draft.status;
    +      if (!args.resume) {
    +        const claimed = await db('task_drafts').where({ draft_id: args.planId, mcp_revision: args.expectedRevision }).whereIn('status', ['draft', 'review', 'approved'])
    +          .update({ status: 'executing', updated_at: db.fn.now() });
    +        if (!claimed) throw new McpError('PRECONDITION_FAILED', `Plan is ${draft.status === 'executed' ? 'already published' : `busy (status ${draft.status})`}.`, 409,
    +          { stage: 'precondition', details: { status: draft.status } });
    +      }
    +      // Markers of the first attempt are reused on resume so adoption finds them.
    +      const markerOperationId = previous?.operationId ?? operationId!;
    +      const recorded = new Map((await db('plan_issues').where({ draft_id: args.planId }).select('issue_number')).map((row, index) => [index, row.issue_number]));
    +      const created: PublicationState['created'] = [...(previous?.created ?? [])];
    +      const adopted: number[] = [];
    +      const [owner, repo] = args.repository.split('/');
    +      for (const [index, task] of tasks.entries()) {
    +        if (created.some(entry => entry.index === index)) continue;
    +        let step: 'authorize' | 'create_issue' | 'record_issue' = 'authorize';
    +        try {
    +          await policy.repository(principal, args.repository, true);
    +          step = 'create_issue';
    +          // Adopt an issue an uncertain earlier attempt may already have created.
    +          let issue = args.resume ? await findMarkedIssue(principal, args.repository, markerOperationId, index) : null;
    +          if (issue) adopted.push(issue.number);
    +          else {
    +            const response = await principal.github.request('POST /repos/{owner}/{repo}/issues', { owner, repo, title: task.title,
    +              body: `${task.body}\n\n## Implementation\n${task.implementation}${task.notes ? `\n\n## Notes\n${task.notes}` : ''}\n\n${issueMarker(markerOperationId, index)}`, labels: ['propr-planned'] });
    +            issue = { number: response.data.number, url: response.data.html_url, title: response.data.title };
    +          }
    +          step = 'record_issue';
    +          if (![...recorded.values()].includes(issue.number)) {
    +            await db('plan_issues').insert({ draft_id: args.planId, repository: args.repository, issue_number: issue.number });
    +          }
    +          created.push({ index, number: issue.number, url: issue.url });
    +        } catch (error) {
    +          await failPublication({ error, index, title: task.title, step, created, previousStatus, markerOperationId });
    +        }
    +      }
    +      const ordered = [...created].sort((a, b) => a.index - b.index);
    +      await db('task_drafts').where({ draft_id: args.planId }).update({ status: 'executed', updated_at: db.fn.now(),
    +        plan_json: JSON.stringify(tasks.map((item, i) => { const issue = ordered.find(entry => entry.index === i); return issue ? { ...item, issue_number: issue.number, issue_url: issue.url } : item; })),
    +        context_config: JSON.stringify(withoutPublication(draft.context_config)) });
    +      return ok({ planId: args.planId, issues: ordered.map(({ number, url }, i) => ({ number, url, title: tasks[i]?.title })), resumed: args.resume, adopted });
    +
    +      /** Persist or roll back, then throw a structured error. Always throws. */
    +      async function failPublication(failure: { error: unknown; index: number; title: string; step: string; created: PublicationState['created'];
    +        previousStatus: string; markerOperationId: string }): Promise<never> {
    +        const cause = classifyError(failure.error);
    +        // Transport failures on a POST may have created the issue; only a
    +        // classified rejection with nothing created lets us release the claim.
    +        const certainNothingCreated = failure.created.length === 0 && (failure.step === 'authorize' || (cause.stage !== 'transport' && cause.code !== 'INTERNAL_ERROR'));
    +        const details = { failedIndex: failure.index, failedTitle: failure.title, step: failure.step,
    +          createdIssues: failure.created.map(entry => entry.number), cause: { code: cause.code, message: cause.message } };
    +        if (certainNothingCreated && !args.resume) {
    +          await db('task_drafts').where({ draft_id: args.planId, status: 'executing', mcp_revision: args.expectedRevision })
    +            .update({ status: failure.previousStatus, updated_at: db.fn.now() });
    +          throw new McpError('PUBLISH_FAILED', `Publishing stopped at task ${failure.index + 1} (${failure.step}): ${cause.message}. No issues were created; the plan was released and can be published again.`,
    +            cause.status >= 500 ? 502 : 409, { stage: cause.stage ?? 'github', retryable: cause.retryable, details });
    +        }
    +        const publication: PublicationState = { state: 'partial', operationId: failure.markerOperationId, created: failure.created,
    +          failedIndex: failure.index, failedAt: new Date().toISOString(), cause: { code: cause.code, message: cause.message } };
    +        await db('task_drafts').where({ draft_id: args.planId }).update({ context_config: JSON.stringify({ ...parseConfig(draft.context_config), publication }) });
    +        throw new McpError('PUBLISH_PARTIAL', `Publishing stopped at task ${failure.index + 1} (${failure.step}) after ${failure.created.length} issue(s): ${cause.message}. Call publish_plan with resume: true to finish without duplicates.`,
    +          409, { stage: cause.stage ?? 'github', retryable: false, details });
    +      }
         } });

    Add small local helpers near the top of the file:

    function parseConfig(value: unknown): Record<string, unknown> {
      try { return (typeof value === 'string' ? JSON.parse(value) : value) ?? {}; } catch { return {}; }
    }
    function withoutPublication(value: unknown): Record<string, unknown> {
      // Successful publication clears the recovery record so get_plan no longer reports it.
      const { publication: _publication, ...rest } = parseConfig(value) as Record<string, unknown> & { publication?: unknown };
      return rest;
    }

    McpOperations.run already treats McpError with status < 500 as a deliberate failure, so PUBLISH_FAILED/PUBLISH_PARTIAL are stored as failed receipts with the full envelope (not OUTCOME_UNKNOWN). For a 502 PUBLISH_FAILED (upstream unavailable) the envelope keeps retryable: true but the receipt state becomes unknown; that is acceptable because the draft has been released and nothing was created.

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

    Why this file: Publication recovery is the scenario that previously failed in production; it needs a regression test with a controllable GitHub fake.

    // Sketch - reuse the fixture pattern from mcpTaskSubmissions.test.ts (in-memory SQLite,
    // McpPolicy with repository() stubbed, executeTool from tools.js).
    // 1. Seed a draft in 'review' with three valid tasks.
    // 2. github.request: POST /issues succeeds for task 0, throws { status: 422, response: { data: { message: 'Validation Failed' } } } for task 1.
    // 3. publish_plan -> receipt.state === 'failed', result.error.code === 'PUBLISH_PARTIAL', details.createdIssues.length === 1.
    // 4. get_plan -> publication.state === 'partial'.
    // 5. Make POST succeed; GET /issues returns the already-created task-0 issue with its marker.
    // 6. publish_plan({ resume: true, idempotencyKey: new }) -> issues.length === 3, draft status 'executed',
    //    plan_issues has exactly 3 rows, and the POST count for task 0 is still 1.
    // 7. Separate case: 422 on task 0 -> PUBLISH_FAILED, draft status back to 'review'.
  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: 2596/gpt-5.6-sol-mcp-publish_plan-record-p-20260929-1217-j5w
    • Base Branch: 2593-epic-mcp-observability-cf6
    • Worktree: issue-2596-20260929-1217-gpt-5.6-sol-j5w

    🔍 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