Skip to content

Validate plan refinement output before saving: merge edit-style output into the full plan or reject it with a structured error #2606

Closed

Description

@propr-dev

Context

A plan refinement once produced an edit list (items like { "action": "retain", ... }, { "action": "extend", ... }, { "action": "add", ... }) instead of a full revised plan. ProPR saved it as the new plan: runBackgroundRefinement (packages/api/routes/plannerHelpers/refineBackground.ts) writes plan_json: JSON.stringify(result.plan) with no validation. The previous complete plan was only recoverable through the revision history. The legacy createRefineHandler in handlers/generationHandlers.ts does the same.

Core already has validation primitives: incompletePlanItems and validatePlanText in packages/core/src/services/taskPlanning/planValidation.ts, and refinePlan/parseRefinementResponse in refinement.ts, which already tries to repair malformed JSON and incomplete edits.

Requirements

  1. New core function normalizeRefinedPlan(currentPlan, refined) in packages/core/src/services/taskPlanning/refinementOutput.ts returning either { ok: true, plan, merged: boolean, operations?: summary } or { ok: false, code, message, details }:
    • Full plan: every item has non-empty title, body, implementation strings → accepted as-is.
    • Edit list: every item carries an operation discriminator (action or op) in retain | keep | extend | update | replace | add | remove | delete and a target (index (0-based), id, or title matching an existing task) → merged deterministically against currentPlan:
      • retain/keep: keep the target task unchanged,
      • extend: append the provided body/implementation text to the target's fields (separated by a blank line); notes likewise,
      • update/replace: overwrite only the provided fields,
      • add: append a new task (must itself be complete) — or insert after afterIndex when given,
      • remove/delete: drop the target.
        Tasks not mentioned in an edit list are retained (an edit list describes changes, not the whole plan). The merged result must pass the full-plan check.
    • Mixed or unrecognised shapes, unknown targets, duplicate targets, an empty result, or a merged plan with incomplete items → ok: false, code: 'REFINEMENT_OUTPUT_INVALID', details: { reason: 'incomplete_tasks' | 'unknown_operation' | 'unknown_target' | 'mixed_shape' | 'empty_plan', incomplete?: [{ index, missing: [...] }], operations?: n }.
  2. refinePlan (core) calls normalizeRefinedPlan as its final step. If invalid, it first attempts one repair round using the existing repair path (requestCompletePlan) asking for the full plan; if still invalid, it throws RefinementOutputError (new, exported) carrying code and details.
  3. runBackgroundRefinement catches RefinementOutputError and persists refinement_result = { runId, status: 'failed', code, error, details, model, timestamp } without touching plan_json (status back to review). The UI already surfaces refinement_result.error.
  4. MCP: the refine_plan receipt (tracked via get_operation → targetState) reports failed with the envelope { code: 'REFINEMENT_OUTPUT_INVALID', stage: 'workflow', retryable: true, message, details } read from refinement_result when status === 'failed' (extend the plan branch in updateReceiptState/trackExecution).
  5. createRefineHandler (legacy path) applies the same normalisation before writing.
  6. When a merge happened, refinement_result.merged = true and summary notes "Applied N edits to the existing plan" so users see it was merged, not replaced.

Implementation Specification

  • New packages/core/src/services/taskPlanning/refinementOutput.ts (+ export from the taskPlanning barrel).
  • Edit packages/core/src/services/taskPlanning/refinement.ts (final step).
  • Edit packages/api/routes/plannerHelpers/refineBackground.ts, handlers/generationHandlers.ts.
  • Edit packages/api/mcp/tools.ts (updateReceiptState) to surface the failure envelope for refine receipts.
  • Tests: packages/core/test/refinementOutput.test.ts, extend packages/api/test/plannerBackgroundLifecycle.test.ts.

Acceptance Criteria

  • An edit list [{action:'retain',index:0},{action:'extend',index:1,body:'More'},{action:'add',title,body,implementation}] against a 2-task plan yields 3 complete tasks with task 1's body extended.
  • An edit list with {action:'extend', index: 7} on a 2-task plan is rejected with unknown_target.
  • A full plan missing implementation in one item is rejected with incomplete_tasks and the index.
  • After a rejected refinement, plan_json is byte-identical to before and refinement_result.code === 'REFINEMENT_OUTPUT_INVALID'.
  • get_operation for the refine_plan receipt returns failed with that envelope.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Sep 28, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    Validation sits at the boundary where a plan is about to be persisted, and merging is done deterministically in code rather than by asking the model again. Code merge was chosen over "always ask the LLM for the full plan" because it is cheap, predictable and preserves untouched tasks byte-for-byte; we still use one repair round for shapes code cannot interpret. Rejection never writes plan_json, so the previous complete plan is never overwritten by garbage — the revision history becomes a safety net rather than the primary recovery path.

    Treating unmentioned tasks in an edit list as retained matches how the model uses these lists ("retain", "extend", "add") and is the least destructive interpretation.

    File: packages/core/src/services/taskPlanning/refinementOutput.ts (new file)

    Why this file: Pure, testable normalisation shared by both refinement persistence paths.

    import { incompletePlanItems } from './planValidation.js';
    
    export interface PlanTask { title: string; body: string; implementation: string; notes?: string; [key: string]: unknown }
    export type RefinementRejectReason = 'incomplete_tasks' | 'unknown_operation' | 'unknown_target' | 'mixed_shape' | 'empty_plan';
    export type NormalizedRefinement =
      | { ok: true; plan: PlanTask[]; merged: boolean; operations: number }
      | { ok: false; code: 'REFINEMENT_OUTPUT_INVALID'; message: string; details: { reason: RefinementRejectReason; [key: string]: unknown } };
    
    export class RefinementOutputError extends Error {
      readonly code = 'REFINEMENT_OUTPUT_INVALID';
      constructor(message: string, readonly details: Record<string, unknown>) { super(message); this.name = 'RefinementOutputError'; }
    }
    
    const OPERATIONS: Record<string, 'retain' | 'extend' | 'update' | 'add' | 'remove'> = {
      retain: 'retain', keep: 'retain', extend: 'extend', update: 'update', replace: 'update', add: 'add', remove: 'remove', delete: 'remove',
    };
    
    const opOf = (item: Record<string, unknown>) => String(item.action ?? item.op ?? '').toLowerCase();
    const isComplete = (item: unknown) => !!item && typeof item === 'object'
      && ['title', 'body', 'implementation'].every(key => typeof (item as Record<string, unknown>)[key] === 'string' && ((item as Record<string, string>)[key]).trim());
    
    function reject(reason: RefinementRejectReason, message: string, extra: Record<string, unknown> = {}): NormalizedRefinement {
      return { ok: false, code: 'REFINEMENT_OUTPUT_INVALID', message, details: { reason, ...extra } };
    }
    
    function completeness(plan: PlanTask[]): NormalizedRefinement | null {
      if (!plan.length) return reject('empty_plan', 'The refinement produced an empty plan.');
      const incomplete = incompletePlanItems(plan);
      // incompletePlanItems returns indexes (or items) missing title/body/implementation; map to {index, missing}.
      if (incomplete.length) {
        return reject('incomplete_tasks', 'Every task needs a title, body and implementation.', {
          incomplete: plan.map((task, index) => ({ index, missing: ['title', 'body', 'implementation'].filter(key => !(typeof task[key] === 'string' && (task[key] as string).trim())) }))
            .filter(entry => entry.missing.length).slice(0, 20) });
      }
      return null;
    }
    
    function targetIndex(plan: PlanTask[], item: Record<string, unknown>): number {
      if (Number.isInteger(item.index)) return Number(item.index);
      if (typeof item.id === 'string') return plan.findIndex(task => task.id === item.id);
      if (typeof item.title === 'string' && opOf(item) !== 'add') return plan.findIndex(task => task.title.trim().toLowerCase() === String(item.title).trim().toLowerCase());
      return -1;
    }
    
    export function normalizeRefinedPlan(currentPlan: PlanTask[], refined: unknown): NormalizedRefinement {
      if (!Array.isArray(refined)) return reject('mixed_shape', 'The refinement output was not a list of tasks.');
      const edits = refined.filter(item => item && typeof item === 'object' && opOf(item as Record<string, unknown>));
      if (edits.length === 0) {
        const plan = refined as PlanTask[];
        return completeness(plan) ?? { ok: true, plan, merged: false, operations: 0 };
      }
      // Half full-plan, half edit list is ambiguous: never guess.
      if (edits.length !== refined.length) return reject('mixed_shape', 'The refinement mixed full tasks with edit operations.');
      const result: Array<PlanTask | null> = currentPlan.map(task => ({ ...task }));
      const touched = new Set<number>();
      const additions: Array<{ after: number; task: PlanTask }> = [];
      for (const raw of edits as Array<Record<string, unknown>>) {
        const op = OPERATIONS[opOf(raw)];
        if (!op) return reject('unknown_operation', `Unknown refinement operation "${opOf(raw)}".`, { operation: opOf(raw) });
        if (op === 'add') {
          const { action: _action, op: _op, afterIndex, ...task } = raw;
          if (!isComplete(task)) return reject('incomplete_tasks', 'An added task needs a title, body and implementation.', { incomplete: [{ index: currentPlan.length + additions.length, missing: ['title', 'body', 'implementation'].filter(key => !task[key]) }] });
          additions.push({ after: Number.isInteger(afterIndex) ? Number(afterIndex) : currentPlan.length - 1, task: task as PlanTask });
          continue;
        }
        const index = targetIndex(currentPlan, raw);
        if (index < 0 || index >= currentPlan.length) return reject('unknown_target', `Refinement referenced a task that does not exist (${JSON.stringify(raw.index ?? raw.id ?? raw.title)}).`);
        if (touched.has(index)) return reject('unknown_target', `Refinement changed task ${index + 1} more than once.`);
        touched.add(index);
        const target = result[index]!;
        if (op === 'remove') result[index] = null;
        else if (op === 'extend') {
          for (const key of ['body', 'implementation', 'notes'] as const) {
            if (typeof raw[key] === 'string' && (raw[key] as string).trim()) target[key] = target[key] ? `${target[key]}\n\n${raw[key]}` : String(raw[key]);
          }
        } else if (op === 'update') {
          for (const key of ['title', 'body', 'implementation', 'notes'] as const) if (typeof raw[key] === 'string') target[key] = String(raw[key]);
        }
        // retain: nothing to do.
      }
      const merged: PlanTask[] = [];
      result.forEach((task, index) => {
        if (task) merged.push(task);
        for (const addition of additions.filter(entry => entry.after === index)) merged.push(addition.task);
      });
      for (const addition of additions.filter(entry => entry.after < 0 || entry.after >= currentPlan.length)) merged.push(addition.task);
      return completeness(merged) ?? { ok: true, plan: merged, merged: true, operations: edits.length };
    }

    Adjust the incompletePlanItems usage to its actual return type (indexes or items) — the helper above only relies on "non-empty means some are incomplete".

    File: packages/core/src/services/taskPlanning/refinement.ts

    Why this file: refinePlan returns the plan that callers persist; validating here protects every caller.

    import { normalizeRefinedPlan, RefinementOutputError } from './refinementOutput.js';
    
    // At the end of refinePlan, before `return { plan, action, summary, ... }`:
    let normalized = normalizeRefinedPlan(currentPlan, parsed.plan);
    if (!normalized.ok) {
      // One repair round: ask for the complete plan explicitly (existing helper).
      const repaired = await requestCompletePlan({ ...options, currentPlan, invalidOutput: parsed.plan, reason: normalized.details.reason });
      normalized = normalizeRefinedPlan(currentPlan, repaired.plan);
    }
    if (!normalized.ok) throw new RefinementOutputError(normalized.message, normalized.details);
    return { ...result, plan: normalized.plan, merged: normalized.merged,
      summary: normalized.merged ? `${result.summary ?? ''}\n\nApplied ${normalized.operations} edits to the existing plan.`.trim() : result.summary };

    Export RefinementOutputError and normalizeRefinedPlan from the taskPlanning index so @propr/core consumers can import them.

    File: packages/api/routes/plannerHelpers/refineBackground.ts

    Why this file: Background persistence path; a rejected refinement must leave plan_json untouched and explain why.

    @@
    -import { buildPlannerAbortSignalKey, refinePlan, runWithPlannerAbortContext } from '@propr/core';
    +import { buildPlannerAbortSignalKey, refinePlan, runWithPlannerAbortContext, RefinementOutputError } from '@propr/core';
    @@ catch (error) {
         const failureMeta = {
           runId,
           status: 'failed',
           error: errorMessage,
    +      // Structured code/details let MCP receipts and the UI say *why* nothing was saved.
    +      ...(error instanceof RefinementOutputError ? { code: error.code, details: error.details } : {}),
           model: generationModel,
           timestamp: new Date().toISOString()
         };
         const persisted = await persistActiveRefinement(db, draftId, runId, {
           status: 'review',
           refinement_result: JSON.stringify(failureMeta),
         });

    (The failure branch already never writes plan_json — keep it that way.) On success, also store merged: result.merged in refinementMeta.

    File: packages/api/routes/plannerHelpers/handlers/generationHandlers.ts

    -          await deps.db('task_drafts').where({ draft_id: draftId }).update({
    -            plan_json: JSON.stringify(result.plan),
    +          // Legacy path: same validation as the background runner.
    +          const normalized = normalizeRefinedPlan(currentPlan, result.plan);
    +          if (!normalized.ok) {
    +            await deps.db('task_drafts').where({ draft_id: draftId }).update({ status: 'review', updated_at: deps.db.fn.now(),
    +              refinement_result: JSON.stringify({ status: 'failed', code: normalized.code, error: normalized.message, details: normalized.details, timestamp: new Date().toISOString() }) });
    +            return;
    +          }
    +          await deps.db('task_drafts').where({ draft_id: draftId }).update({
    +            plan_json: JSON.stringify(normalized.plan),

    File: packages/api/mcp/tools.ts

    Why this file: refine_plan receipts should report the structured rejection instead of silently becoming completed when the draft returns to review.

     function updateReceiptState(row: Operation, receipt: Record<string, unknown>): void {
       const target = receipt.targetState as Record<string, unknown> | undefined;
       if (row.state === 'accepted' && target) {
    -    if (['generate_plan', 'refine_plan'].includes(row.tool) && target.status === 'review') receipt.state = 'completed';
    +    if (row.tool === 'refine_plan' && target.status === 'review' && target.refinementStatus === 'failed') {
    +      receipt.state = 'failed';
    +      receipt.result = { ...(receipt.result as object), error: { code: target.refinementCode ?? 'REFINEMENT_FAILED', stage: 'workflow',
    +        retryable: true, status: 422, message: target.refinementError ?? 'The refinement could not be applied.', details: target.refinementDetails } };
    +    } else if (['generate_plan', 'refine_plan'].includes(row.tool) && target.status === 'review') receipt.state = 'completed';

    Populate refinementStatus/Code/Error/Details when get_operation loads the plan target state: select refinement_result in the task_drafts read, parse it, and only use it when its runId equals the receipt's result.runId (a newer refinement must not satisfy an older receipt).

    File: packages/core/test/refinementOutput.test.ts (new file)

    import assert from 'node:assert/strict';
    import { test } from 'node:test';
    import { normalizeRefinedPlan } from '../src/services/taskPlanning/refinementOutput.js';
    
    const plan = [{ title: 'A', body: 'a', implementation: 'ia' }, { title: 'B', body: 'b', implementation: 'ib' }];
    
    test('edit lists are merged, unmentioned tasks retained', () => {
      const result = normalizeRefinedPlan(plan, [{ action: 'extend', index: 1, body: 'More' },
        { action: 'add', title: 'C', body: 'c', implementation: 'ic' }]);
      assert.ok(result.ok);
      assert.deepEqual(result.plan.map(task => task.title), ['A', 'B', 'C']);
      assert.equal(result.plan[1].body, 'b\n\nMore');
      assert.equal(result.merged, true);
    });
    
    test('unknown targets, incomplete tasks and mixed shapes are rejected', () => {
      const unknown = normalizeRefinedPlan(plan, [{ action: 'extend', index: 7, body: 'x' }]);
      assert.ok(!unknown.ok && unknown.details.reason === 'unknown_target');
      const incomplete = normalizeRefinedPlan(plan, [{ title: 'A', body: 'a' }]);
      assert.ok(!incomplete.ok && incomplete.details.reason === 'incomplete_tasks');
      const mixed = normalizeRefinedPlan(plan, [{ action: 'retain', index: 0 }, { title: 'X', body: 'x', implementation: 'y' }]);
      assert.ok(!mixed.ok && mixed.details.reason === 'mixed_shape');
    });
  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: 2606/gpt-5.6-sol-validate-plan-refinement--20260929-2333-bph
    • Base Branch: 2593-epic-mcp-observability-cf6
    • Worktree: issue-2606-20260929-2333-gpt-5.6-sol-bph

    🔍 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 30, 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