Repository navigation
Description
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
- New core function
normalizeRefinedPlan(currentPlan, refined)inpackages/core/src/services/taskPlanning/refinementOutput.tsreturning either{ ok: true, plan, merged: boolean, operations?: summary }or{ ok: false, code, message, details }:- Full plan: every item has non-empty
title,body,implementationstrings → accepted as-is. - Edit list: every item carries an operation discriminator (
actionorop) inretain | keep | extend | update | replace | add | remove | deleteand a target (index(0-based),id, ortitlematching an existing task) → merged deterministically againstcurrentPlan:retain/keep: keep the target task unchanged,extend: append the providedbody/implementationtext to the target's fields (separated by a blank line);noteslikewise,update/replace: overwrite only the provided fields,add: append a new task (must itself be complete) — or insert afterafterIndexwhen 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 }.
- Full plan: every item has non-empty
refinePlan(core) callsnormalizeRefinedPlanas 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 throwsRefinementOutputError(new, exported) carryingcodeanddetails.runBackgroundRefinementcatchesRefinementOutputErrorand persistsrefinement_result = { runId, status: 'failed', code, error, details, model, timestamp }without touchingplan_json(status back toreview). The UI already surfacesrefinement_result.error.- MCP: the
refine_planreceipt (tracked viaget_operation→targetState) reportsfailedwith the envelope{ code: 'REFINEMENT_OUTPUT_INVALID', stage: 'workflow', retryable: true, message, details }read fromrefinement_resultwhenstatus === 'failed'(extend the plan branch inupdateReceiptState/trackExecution). createRefineHandler(legacy path) applies the same normalisation before writing.- When a merge happened,
refinement_result.merged = trueandsummarynotes "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, extendpackages/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 withunknown_target. - A full plan missing
implementationin one item is rejected withincomplete_tasksand the index. - After a rejected refinement,
plan_jsonis byte-identical to before andrefinement_result.code === 'REFINEMENT_OUTPUT_INVALID'. -
get_operationfor therefine_planreceipt returnsfailedwith that envelope.
Created by ProPR AI Planner
Activity
propr-dev commentedon Sep 28, 2026
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.
File:
packages/core/src/services/taskPlanning/refinement.tsWhy this file:
refinePlanreturns the plan that callers persist; validating here protects every caller.Export
RefinementOutputErrorandnormalizeRefinedPlanfrom the taskPlanning index so@propr/coreconsumers can import them.File:
packages/api/routes/plannerHelpers/refineBackground.tsWhy this file: Background persistence path; a rejected refinement must leave
plan_jsonuntouched and explain why.(The failure branch already never writes
plan_json— keep it that way.) On success, also storemerged: result.mergedinrefinementMeta.File:
packages/api/routes/plannerHelpers/handlers/generationHandlers.tsFile:
packages/api/mcp/tools.tsWhy this file:
refine_planreceipts should report the structured rejection instead of silently becomingcompletedwhen the draft returns toreview.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/Detailswhenget_operationloads the plan target state: selectrefinement_resultin thetask_draftsread, parse it, and only use it when itsrunIdequals the receipt'sresult.runId(a newer refinement must not satisfy an older receipt).File:
packages/core/test/refinementOutput.test.ts(new file)propr-dev commentedon Sep 29, 2026
🤖 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:
codexgpt-5.6-sol2606/gpt-5.6-sol-validate-plan-refinement--20260929-2333-bph2593-epic-mcp-observability-cf6issue-2606-20260929-2333-gpt-5.6-sol-bph🔍 Track Task Execution
fix(ai): Resolve issue #2606 - Validate plan refinement output before…
fix(ai): Resolve issue #2606 - Validate plan refinement output before…