Skip to content

Plan revision history: record what caused each revision (generation, refinement, manual edit, rename, restore) and expose it from get_plan #2605

Closed

Description

@propr-dev

Context

The task_drafts_plan_history SQLite trigger (migration 20260928000000_add_task_draft_plan_revisions.js) snapshots the outgoing plan_json into task_draft_plan_revisions on every change, and MCP already has list_plan_revisions, get_plan_revision and restore_plan_revision (packages/api/mcp/toolsPlanning.ts, backed by packages/api/routes/plannerHelpers/planRevisions.ts). What is missing from the request:

  1. What caused each revision — generation, refinement, manual edit, rename, restore. Today a revision only has status_before/status_after; after a refinement replaced a full plan with an edit list, there is no way to see "this version came from refinement at 14:02, the one before from generation".
  2. Renames are not recorded (the trigger only fires on plan_json changes).
  3. get_plan does not expose the history; the caller has to know that the separate revision tools exist.

Requirements

  1. Migration adds task_drafts.plan_cause TEXT NULL (cause of the current plan) and task_draft_plan_revisions.cause TEXT NULL, name_before TEXT NULL, name_after TEXT NULL. Allowed causes: generation, refinement, manual_edit, restore, rename, unknown (legacy rows).
  2. Recreate the task_drafts_plan_history trigger so the snapshot row copies OLD.plan_cause into cause — i.e. each revision row records how that (replaced) version came to be. Keep the existing coalescing and 50-row retention logic from the original migration verbatim; only add the column.
  3. Add trigger task_drafts_name_history (AFTER UPDATE OF name) inserting a revision row with cause = 'rename', plan_json = OLD.plan_json, name_before = OLD.name, name_after = NEW.name, when the name changed and plan_json did not; retention applies.
  4. Every writer sets plan_cause in the same UPDATE that writes plan_json:
    • generation completion (persistGenerationCompletion in packages/core/src/services/...taskPlanningService and runBackgroundGeneration in packages/api/routes/plannerHelpers/utils.ts) → generation,
    • refinement (runBackgroundRefinement in refineBackground.ts, and the legacy createRefineHandler in handlers/generationHandlers.ts) → refinement,
    • MCP update_plan and the UI draft update route (plannerRoutes.ts updateDraft) → manual_edit,
    • restorePlanRevision → restore (and the snapshot row it inserts gets the outgoing plan's cause),
    • create_plan with an initial plan → manual_edit.
  5. listPlanRevisions / getPlanRevision return cause, nameBefore, nameAfter, plus a derived currentCause for the live plan.
  6. get_plan output adds revisionHistory: { count, currentCause, latest: [up to 10 summaries: revisionId, cause, replacedAt, issueCount, titles(first 5)] , tools: ['list_plan_revisions','get_plan_revision','restore_plan_revision'] }.
  7. The UI revision list (propr-ui/src/api/planRevisionsApi.ts types + the component that renders revisions) shows the cause label; optional but the API type must include cause.

Implementation Specification

  • New migration packages/core/src/db/migrations/20261002000000_add_plan_revision_causes.js.
  • Edit writers listed above, planRevisions.ts, toolsPlanning.ts, propr-ui/src/api/planRevisionsApi.ts.
  • Tests: extend the plan revision tests (search planRevisions in packages/api/test) with each cause, rename recording, and get_plan.revisionHistory.

Acceptance Criteria

  • Generate → refine → manual edit → rename → restore produces revision rows whose causes (newest first) are restore-replaced manual_edit… exactly as specified: each row's cause equals the cause of the version it snapshots.
  • A rename without plan change produces exactly one rename row with nameBefore/nameAfter.
  • get_plan shows revisionHistory.currentCause === 'refinement' right after a refinement.
  • Legacy rows (created before the migration) report cause: 'unknown'.
  • Migration down restores the original trigger.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Sep 28, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    The trigger already captures every plan change, so we attach the cause at the source rather than inferring it. Each writer stamps task_drafts.plan_cause in the same UPDATE that writes plan_json; the trigger copies OLD.plan_cause into the snapshot. This keeps capture atomic and complete (no writer can forget to insert a history row — the trigger still does that) and costs one extra column per writer. Inferring cause from status transitions (generating → review = generation) was rejected: manual edits and refinements both go review → review.

    Renames get their own tiny trigger because the existing trigger is keyed on plan_json and must not start snapshotting on unrelated column writes.

    File: packages/core/src/db/migrations/20261002000000_add_plan_revision_causes.js (new file)

    Why this file: Schema + trigger changes must be versioned and reversible.

    /**
     * Records what produced each plan version. Each writer stamps
     * task_drafts.plan_cause together with plan_json; the history trigger copies
     * OLD.plan_cause so a revision row says how the replaced version came to be.
     */
    export async function up(knex) {
      await knex.schema.alterTable('task_drafts', table => { table.string('plan_cause', 16).nullable(); });
      await knex.schema.alterTable('task_draft_plan_revisions', table => {
        table.string('cause', 16).nullable();
        table.text('name_before').nullable();
        table.text('name_after').nullable();
      });
      await knex.raw('DROP TRIGGER IF EXISTS task_drafts_plan_history');
      // IMPORTANT: copy the CREATE TRIGGER statement from
      // 20260928000000_add_task_draft_plan_revisions.js verbatim (coalescing window,
      // restore skip and 50-row retention), and only add `cause` to the INSERT:
      //   INSERT INTO task_draft_plan_revisions (draft_id, plan_json, draft_revision, status_before, status_after, replaced_at, cause)
      //   VALUES (OLD.draft_id, OLD.plan_json, OLD.mcp_revision, OLD.status, NEW.status, CURRENT_TIMESTAMP, COALESCE(OLD.plan_cause, 'unknown'));
      await knex.raw(PLAN_HISTORY_TRIGGER_WITH_CAUSE);
      await knex.raw(`
        CREATE TRIGGER task_drafts_name_history
        AFTER UPDATE OF name ON task_drafts
        WHEN OLD.name IS NOT NEW.name AND OLD.plan_json IS NEW.plan_json AND OLD.plan_json IS NOT NULL
        BEGIN
          INSERT INTO task_draft_plan_revisions (draft_id, plan_json, draft_revision, status_before, status_after, replaced_at, cause, name_before, name_after)
          VALUES (OLD.draft_id, OLD.plan_json, OLD.mcp_revision, OLD.status, NEW.status, CURRENT_TIMESTAMP, 'rename', OLD.name, NEW.name);
          -- Same retention as the plan trigger: keep the newest 50 rows per draft.
          DELETE FROM task_draft_plan_revisions WHERE draft_id = NEW.draft_id AND revision_id NOT IN (
            SELECT revision_id FROM task_draft_plan_revisions WHERE draft_id = NEW.draft_id ORDER BY revision_id DESC LIMIT 50);
        END`);
    }
    
    export async function down(knex) {
      await knex.raw('DROP TRIGGER IF EXISTS task_drafts_name_history');
      await knex.raw('DROP TRIGGER IF EXISTS task_drafts_plan_history');
      await knex.raw(ORIGINAL_PLAN_HISTORY_TRIGGER); // verbatim copy from 20260928000000
      await knex.schema.alterTable('task_draft_plan_revisions', table => { table.dropColumn('cause'); table.dropColumn('name_before'); table.dropColumn('name_after'); });
      await knex.schema.alterTable('task_drafts', table => { table.dropColumn('plan_cause'); });
    }
    
    // Define both SQL constants at the top of this file (copied from the original migration).

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

    Why this file: Read/restore helpers used by both REST and MCP; they must surface and set the cause.

    --- a/packages/api/routes/plannerHelpers/planRevisions.ts
    +++ b/packages/api/routes/plannerHelpers/planRevisions.ts
    @@
    +export type PlanRevisionCause = 'generation' | 'refinement' | 'manual_edit' | 'restore' | 'rename' | 'unknown';
    +
     interface PlanRevisionRow {
       revision_id: number;
       ...
       replaced_at: string;
    +  cause: string | null;
    +  name_before: string | null;
    +  name_after: string | null;
     }
     
     export interface PlanRevisionSummary {
       ...
       titles: string[];
    +  /** How this snapshot's plan was produced. */
    +  cause: PlanRevisionCause;
    +  nameBefore: string | null;
    +  nameAfter: string | null;
     }
    @@ function summarize(row: PlanRevisionRow): PlanRevisionSummary {
       return {
         ...
    +    cause: (row.cause as PlanRevisionCause | null) ?? 'unknown',
    +    nameBefore: row.name_before, nameAfter: row.name_after,
       };
     }
    @@ restorePlanRevision
    -        await tx('task_draft_plan_revisions').insert({
    -          draft_id: draftId, plan_json: draft.plan_json, draft_revision: draft.mcp_revision,
    -          status_before: draft.status, status_after: 'review', replaced_at: tx.fn.now(),
    -        });
    +        await tx('task_draft_plan_revisions').insert({
    +          draft_id: draftId, plan_json: draft.plan_json, draft_revision: draft.mcp_revision,
    +          status_before: draft.status, status_after: 'review', replaced_at: tx.fn.now(),
    +          // The replaced plan keeps its own origin, like trigger-written rows.
    +          cause: draft.plan_cause ?? 'unknown',
    +        });
    @@
    -    await restorable().update({ plan_json: row.plan_json, status: 'review', updated_at: tx.fn.now() });
    +    await restorable().update({ plan_json: row.plan_json, status: 'review', plan_cause: 'restore', updated_at: tx.fn.now() });

    (Select plan_cause in the draft read: .first('plan_json', 'status', 'mcp_revision', 'plan_cause').)

    Add a helper used by get_plan:

    export async function planRevisionHistory(db: Knex, draftId: string) {
      const [latest, count, current] = await Promise.all([
        db('task_draft_plan_revisions').where({ draft_id: draftId }).orderBy('revision_id', 'desc').limit(10) as Promise<PlanRevisionRow[]>,
        db('task_draft_plan_revisions').where({ draft_id: draftId }).count({ count: '*' }).first(),
        db('task_drafts').where({ draft_id: draftId }).first('plan_cause'),
      ]);
      return {
        count: Number(count?.count ?? 0),
        currentCause: (current?.plan_cause as PlanRevisionCause | null) ?? 'unknown',
        latest: latest.map(summarize).map(({ revision_id, cause, replaced_at, issue_count, titles, nameBefore, nameAfter }) =>
          ({ revisionId: revision_id, cause, replacedAt: replaced_at, issueCount: issue_count, titles: titles.slice(0, 5), nameBefore, nameAfter })),
        tools: ['list_plan_revisions', 'get_plan_revision', 'restore_plan_revision'],
      };
    }

    File: packages/api/mcp/toolsPlanning.ts

    Why this file: update_plan/create_plan stamp manual_edit; get_plan exposes history.

    @@ create_plan
    -        await tx('task_drafts').insert({ draft_id: id, ..., plan_json: args.plan ? JSON.stringify(args.plan) : null, status: 'draft' });
    +        await tx('task_drafts').insert({ draft_id: id, ..., plan_json: args.plan ? JSON.stringify(args.plan) : null,
    +          plan_cause: args.plan ? 'manual_edit' : null, status: 'draft' });
    @@ update_plan
    -          ...(args.plan !== undefined ? { plan_json: JSON.stringify(args.plan) } : {}), updated_at: ...
    +          // Stamped in the same UPDATE so the history trigger attributes the next snapshot correctly.
    +          ...(args.plan !== undefined ? { plan_json: JSON.stringify(args.plan), plan_cause: 'manual_edit' } : {}), updated_at: ...
    @@ get_plan
    -      return ok({ ..., issues: ... });
    +      return ok({ ..., issues: ..., revisionHistory: await planRevisionHistory(db, args.planId) });

    Writers in API and core

    Why: The cause must be written by the component that produced the plan.

    • packages/api/routes/plannerHelpers/refineBackground.ts → in the successful persistActiveRefinement call add plan_cause: 'refinement' next to plan_json.
    • packages/api/routes/plannerHelpers/handlers/generationHandlers.ts (createRefineHandler) → add plan_cause: 'refinement' to the update that writes plan_json.
    • Generation persistence (persistGenerationCompletion in core, search for the update that writes plan_json with status: 'review' after generation) → add plan_cause: 'generation'.
    • UI draft update (updateDraft handler in packages/api/routes/plannerRoutes.ts) → when the body includes plan_json, add plan_cause: 'manual_edit'. A body that only changes name must not touch plan_cause (the rename trigger records it).

    File: propr-ui/src/api/planRevisionsApi.ts

     export interface PlanRevisionSummary {
       ...
    +  cause: 'generation' | 'refinement' | 'manual_edit' | 'restore' | 'rename' | 'unknown';
    +  nameBefore: string | null;
    +  nameAfter: string | null;
     }

    In the revision list component, render the cause as a small label (Generated, Refined, Edited, Restored, Renamed: old → new, — for unknown).

    Tests

    // packages/api/test/planRevisionCauses.test.ts (migrated in-memory SQLite)
    // 1. insert draft; update plan_json + plan_cause 'generation'   (row count 0 -> first version has no snapshot yet)
    // 2. update plan_json + 'refinement'  -> latest row cause 'generation'
    // 3. update plan_json + 'manual_edit' -> latest row cause 'refinement'
    // 4. update name only                  -> latest row cause 'rename', name_before/after set
    // 5. restorePlanRevision(first)        -> latest row cause 'manual_edit', draft.plan_cause 'restore'
    // 6. planRevisionHistory().currentCause === 'restore'
  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: 2605/gpt-5.6-sol-plan-revision-history-rec-20260929-2230-uuu
    • Base Branch: 2593-epic-mcp-observability-cf6
    • Worktree: issue-2605-20260929-2230-gpt-5.6-sol-uuu

    🔍 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