Implement undo/redo/history system for tools/video-editor
Context
The video editor uses React Context + custom hooks. All mutations flow through applyTimelineEdit() in useTimelineSave.ts. There is no existing undo/redo.
Requirements
Two-tier history system:
Tier 1: Undo Stack (fine-grained, in-memory)
Push snapshot of { rows, meta, clipOrder, tracks, output } before every applyTimelineEdit() call
Cap at ~50-100 entries
Cmd+Z / Cmd+Shift+Z
Drag operations and rapid edits should collapse into single undo entries (batch by user gesture using transaction ID or debounce window)
Tier 2: Checkpoints (coarse-grained, persisted to Supabase)
Named snapshots of full TimelineConfig stored in Supabase DB
Keep checkpoints for past 24 hours
Browsable - jump to any checkpoint
Activity-aware checkpoint triggers:
Session boundary: When edit arrives after >5min idle gap, checkpoint pre-edit state
Edit-distance cap: After ~30 edits since last checkpoint, auto-checkpoint
Semantic triggers: Before destructive ops (delete track, bulk delete, clear timeline) + manual Save checkpoint
Manages idle timer via ref tracking lastEditTimestamp
Checkpoints cap at ~20-30, undo stack at ~50-100
code
Plan:
# Implementation Plan: Undo/Redo/History System for Video Editor
Assistant
User
Assistant
Overview
The video editor currently has no undo/redo capability. All mutations flow through applyTimelineEdit() and applyResolvedConfigEdit() in useTimelineSave.ts, which immediately update state and schedule a debounced save to Supabase. The commitData() function is the single chokepoint where all state changes are applied — it updates dataRef, calls setData(), and triggers scheduleSave().
Architecture insight: The TimelineData object (defined in timeline-data.ts:60-73) contains the full serializable state: config, rows, meta, clipOrder, tracks, output. This is exactly the snapshot we need for undo entries.
Key constraint: There are two mutation paths — applyTimelineEdit (row/meta level, ~85 call sites across 10 hooks) and applyResolvedConfigEdit (resolved config level, used by track management and agent chat). Both funnel through commitData. The history system must intercept at the commitData level to catch all mutations.
No existing checkpoint infrastructure: The timelines table stores only current config + config_version. A new table is needed for checkpoints.
Phase 1: Foundation — Types, DB Migration, DataProvider
Step 1: Define history types (src/tools/video-editor/types/history.ts)
Step 2: Create Supabase migration for timeline_checkpoints table (supabase/migrations/)
Scope: Small
Create migration file with:
sql
CREATE TABLE timeline_checkpoints (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
timeline_id UUID NOT NULL REFERENCES timelines(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES auth.users(id),
config JSONB NOT NULL,
trigger_type TEXT NOT NULL CHECK (trigger_type IN ('session_boundary', 'edit_distance', 'semantic', 'manual')),
label TEXT NOT NULL,
edits_since_last_checkpoint INT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX idx_timeline_checkpoints_timeline ON timeline_checkpoints(timeline_id, created_at DESC);
Add RLS policy: users can only read/write their own checkpoints.
Add a scheduled cleanup: checkpoints older than 24 hours are deleted (can use a DB trigger on insert, or a periodic Edge Function — decision point below in questions).
Maintain undoStack and redoStack as useRef<UndoEntry[]> (in-memory only, not React state — avoid re-renders on every edit).
canUndo/canRedo as derived state (these DO need to be React state for UI updates, but update them only when stack empties/fills).
Cap undo stack at 100 entries; drop oldest when exceeded.
On push: clear redo stack.
Snapshot capture — intercept commitData:
The hook receives dataRef (current state before edit) and wraps the save flow.
Key approach: Instead of wrapping applyTimelineEdit, create a beforeCommit callback that commitData calls before applying the new data. This avoids touching 12+ consumer files.
Modify useTimelineSave.ts to accept an optional onBeforeCommit?: (currentData: TimelineData) => void callback. Inside commitData (useTimelineSave.ts:176), call onBeforeCommit(dataRef.current) before updating state — but only when save !== false (skip for server reloads/polling).
useTimelineHistory provides this callback and pushes a snapshot of the current state onto the undo stack.
Transaction collapsing for drags/rapid edits:
Add optional transactionId to the commitData options: { save?: boolean; transactionId?: string }.
In useClipDrag.ts, the drag session already has a clear start/end lifecycle. Pass a stable transaction ID (e.g., drag-${session.id}) for all applyTimelineEdit calls during a drag.
In the onBeforeCommit callback: if the new entry's transactionId matches the top of the undo stack, skip pushing (the pre-drag snapshot is already captured).
For rapid property edits (e.g., slider changes in PropertiesPanel), use a debounce approach: if two edits arrive within 300ms and have no transaction ID, collapse them (keep the older snapshot, discard the intermediate one).
Undo/redo execution:
undo(): Pop from undo stack, push current state onto redo stack, call commitData with { save: true } to apply the snapshot and trigger a save. Use a flag (isUndoRedo.current = true) to skip pushing onto undo stack during the commit.
redo(): Mirror of undo — pop from redo, push current to undo, apply.
Restoring state from snapshot: Build a full TimelineData from the snapshot using buildDataFromCurrentRegistry() (from timeline-save-utils.ts), keeping the current registry and resolvedConfig URLs intact. The config is the source of truth; rows/meta are derivable but stored for speed.
Checkpoint triggers (activity-aware):
Track lastEditTimestamp (ref) and editsSinceCheckpoint (ref).
Session boundary: In onBeforeCommit, check if Date.now() - lastEditTimestamp > 5 * 60 * 1000. If so, save a checkpoint of the current state (pre-edit) with trigger 'session_boundary'.
Edit-distance cap: Increment editsSinceCheckpoint on each commit. At 30, auto-checkpoint with trigger 'edit_distance'.
Semantic triggers: Add a semantic option to commitData options. Pass semantic: true from handleDeleteClips, handleRemoveTrack, and any "clear timeline" action. The history hook creates a checkpoint before these ops.
Only show if checkpoints.length > 0 or always show with "No checkpoints yet" empty state.
Tooltip on undo/redo buttons showing the action being undone (e.g., the label from the top of the stack).
Step 8: Pass transactionId for drag operations (src/tools/video-editor/hooks/useClipDrag.ts)
Scope: Small
In the drag handler (useClipDrag.ts:402), the drag session already exists as session. Generate a transactionId at drag start (e.g., crypto.randomUUID() or a counter) and pass it through to applyTimelineEdit calls during the drag.
For resize operations in useClipResize.ts, same pattern — generate transaction ID at resize start.
Step 9: Mark destructive operations as semantic (src/tools/video-editor/hooks/useClipEditing.ts, useTimelineTrackManagement.ts)
Scope: Small
In handleDeleteClips (useClipEditing.ts): pass { semantic: true } in the options to applyTimelineEdit.
In handleRemoveTrack (useTimelineTrackManagement.ts): pass { semantic: true }.
Any other bulk-destructive operations that are identifiable.
Phase 4: Validation
Step 10: Manual testing protocol
Scope: Medium
Undo/redo basic flow: Make 3 edits → Cmd+Z three times → verify each state restores → Cmd+Shift+Z → verify redo works.
Drag collapsing: Drag a clip → undo → verify it returns to pre-drag position in one step (not intermediate positions).
Redo invalidation: Make edit A → B → C → undo to B → make edit D → verify redo stack is cleared (can't redo to C).
Checkpoint creation: Leave editor idle >5 min → make edit → verify session boundary checkpoint appears in history dropdown. Make 30+ rapid edits → verify edit-distance checkpoint.
Checkpoint restore: Jump to a previous checkpoint → verify timeline fully restores. Verify undo stack is cleared after checkpoint jump.
Save status: After undo, verify save status goes to 'dirty' → 'saving' → 'saved'. Undo should trigger a real save to Supabase.
Edge cases: Undo when stack is empty (button should be disabled). Undo after page reload (stack is empty, checkpoints persist). Selection state after undo.
Execution Order
Phase 1 first: types + DB migration + provider methods are dependencies for everything.
Phase 2 next: the core hook + wiring. This is the bulk of the work.
Phase 3 after: UI and keyboard shortcuts consume the hook.
Phase 4: manual validation throughout, focused testing after Phase 3.
Validation Order
After Step 4: Verify undo/redo works with console.log before any UI (call undo/redo from devtools).
After Step 6: Verify Cmd+Z/Cmd+Shift+Z work end-to-end.
After Step 7: Full visual verification of toolbar + history panel.
After Step 8-9: Verify drag collapsing and semantic checkpoint triggers.
Risk Notes
Snapshot size: A TimelineConfig with 50 clips is ~10-20KB JSON. 100 undo entries ≈ 1-2MB. Acceptable for in-memory.
Registry/resolved URLs: Undo snapshots store config but NOT registry or resolved URLs. On undo, we rebuild TimelineData from the snapshot config + current registry. This avoids stale signed URLs.
Concurrent edits: If another tab edits the timeline during undo, the existing conflict detection dialog still applies. Undo writes through the normal save path with version checking.
code
Plan metadata:
{
"version": 1,
"timestamp": "2026-03-26T21:45:01Z",
"hash": "sha256:2c99962dc0657d3266e2b6bb5594e8e33698cee232c1710bce961486b03e235d",
"questions": [
"Checkpoint cleanup: Should old checkpoints (>24h) be pruned client-side on load, via a Supabase DB trigger on INSERT, or via a scheduled Edge Function? Client-side prune is simplest (DELETE WHERE created_at < now()-24h on each loadCheckpoints call). DB trigger adds server-side guarantee but is less flexible.",
"jumpToCheckpoint behavior: When jumping to a checkpoint, should the undo stack be (a) cleared entirely, (b) preserved so you can undo back, or (c) should the jump itself be a single undo entry? Option (a) is simplest and most predictable. Option (c) is most flexible but adds complexity.",
"Should applyResolvedConfigEdit (used by agent chat / AI edits) also participate in undo, or should AI-driven edits be excluded from the undo stack? Currently the agent chat can make large config changes via this path."
],
"success_criteria": [
"Cmd+Z undoes the most recent edit and restores the full previous timeline state (clips, tracks, positions, metadata)",
"Cmd+Shift+Z redoes after an undo, and redo stack is cleared when a new edit is made after undo",
"Dragging a clip collapses into a single undo entry (undo restores to pre-drag state, not intermediate positions)",
"Rapid slider/property edits within 300ms collapse into a single undo entry",
"Undo/redo buttons appear next to save badge, are disabled when stack is empty, and visually indicate availability",
"History dropdown shows checkpoint list with labels, trigger types, and timestamps",
"Checkpoints auto-create on session boundary (>5min idle gap), edit-distance cap (~30 edits), and before destructive operations",
"Manual 'Save checkpoint' creates a named checkpoint visible in the history panel",
"Jumping to a checkpoint fully restores the timeline to that saved state",
"Checkpoints persist across page reloads (stored in Supabase), limited to past 24 hours",
"Undo triggers a normal save to Supabase (the restored state is persisted)",
"No performance regression: undo stack snapshots stay under 2MB total, checkpoint saves are async"
],
"assumptions": [
"Undo snapshots will store the serializable config (TimelineConfig) rather than the full TimelineData, and rebuild rows/meta/resolved on restore using existing buildDataFromCurrentRegistry(). This avoids stale URLs and keeps snapshots lean.",
"The onBeforeCommit hook approach (modifying commitData in useTimelineSave.ts) is preferred over wrapping applyTimelineEdit, because it captures ALL mutation paths (applyTimelineEdit, applyResolvedConfigEdit) with a single interception point.",
"Checkpoint cleanup will be done client-side (DELETE on load) unless you specify otherwise. No Edge Function or DB trigger needed for the initial implementation.",
"canUndo/canRedo will be React state (boolean) updated only when the stack transitions between empty and non-empty, to avoid re-rendering the entire editor tree on every edit.",
"The undo stack cap is 100 entries and checkpoint cap is 30 per timeline \u2014 both are generous defaults that can be tuned later.",
"jumpToCheckpoint will clear the undo/redo stacks (option a from the questions), as this is most predictable for users.",
"Agent chat edits via applyResolvedConfigEdit WILL participate in undo (they flow through commitData like everything else), unless you say otherwise."
],
"structure_warnings": [
"Each step section should reference at least one file in backticks."
]
}
code
Plan structure warnings from validator:
[
"Each step section should reference at least one file in backticks."
]
code
Existing flags:
[]
Known accepted debt grouped by subsystem:
{
"agent-chat-rendering": [
{
"id": "DEBT-007",
"concern": "removing the duplicate assistant turn may hide message_user text if the frontend only renders assistant-role turns as chat bubbles.",
"occurrence_count": 1,
"plan_ids": [
"refactor-ai-timeline-agent-20260326-0157"
]
}
],
"bulk-panel-tabs": [
{
"id": "DEBT-010",
"concern": "text clip multi-selections would miss the position tab under the plan's stated rule.",
"occurrence_count": 1,
"plan_ids": [
"multi-select-feature-parity-20260326-0548"
]
}
],
"clip-drag-scroll-sync": [
{
"id": "DEBT-015",
"concern": "the plan's step 3 ontick callback only shows coordinator.update() but the full clip-drag state path (snap, lateststart, ghost positions) also needs re-running during stationary-pointer scroll.",
"occurrence_count": 1,
"plan_ids": [
"add-auto-scroll-to-the-20260326-2119"
]
}
],
"conflict-resolution": [
{
"id": "DEBT-004",
"concern": "silently reloading agent-originated timeline updates would discard dirty local edits.",
"occurrence_count": 1,
"plan_ids": [
"build-a-turn-based-timeline-20260326-0005"
]
}
],
"context-menu-scope": [
{
"id": "DEBT-012",
"concern": "multi-clip copy is not included despite being mentioned in the original idea.",
"occurrence_count": 1,
"plan_ids": [
"multi-select-feature-parity-20260326-0548"
]
}
],
"issue-detection": [
{
"id": "DEBT-006",
"concern": "mid-sentence-cut detection is not implementable without transcript/profile data that the current provider doesn't expose.",
"occurrence_count": 1,
"plan_ids": [
"build-a-turn-based-timeline-20260326-0005"
]
}
],
"optimistic-locking": [
{
"id": "DEBT-002",
"concern": "plan only specifies version checking at the db write layer; the ui load/state/save path doesn't carry config_version yet.",
"occurrence_count": 1,
"plan_ids": [
"build-a-turn-based-timeline-20260326-0005"
]
}
],
"properties-panel-scope": [
{
"id": "DEBT-011",
"concern": "crop and transition controls are not included in the bulk panel, narrowing the original idea's scope.",
"occurrence_count": 1,
"plan_ids": [
"multi-select-feature-parity-20260326-0548"
]
}
],
"realtime-subscriptions": [
{
"id": "DEBT-003",
"concern": "the shared realtime system doesn't know about timeline_agent_sessions; step 7 hooks need their own channel subscription.",
"occurrence_count": 1,
"plan_ids": [
"build-a-turn-based-timeline-20260326-0005"
]
}
],
"selection-save-bridge": [
{
"id": "DEBT-009",
"concern": "the plan specifies passing pruneselection into usetimelinesave but doesn't detail the hook-layer bridge needed because usetimelinesave is instantiated inside usetimelinedata before usetimelinestate runs.",
"occurrence_count": 1,
"plan_ids": [
"multi-select-timeline-clips-20260326-0415"
]
}
],
"task-deduplication": [
{
"id": "DEBT-001",
"concern": "server-generated idempotency keys would break retry deduplication because retried requests get fresh keys.",
"occurrence_count": 1,
"plan_ids": [
"migrate-all-task-creation-20260325-2354"
]
}
],
"task-system-integration": [
{
"id": "DEBT-005",
"concern": "create_generation_task is underspecified against the actual task family system.",
"occurrence_count": 1,
"plan_ids": [
"build-a-turn-based-timeline-20260326-0005"
]
}
],
"tool-error-propagation": [
{
"id": "DEBT-008",
"concern": "a blanket catch in executetool would silently downgrade db/persistence failures into ordinary tool results, changing the session error/http 500 behavior.",
"occurrence_count": 1,
"plan_ids": [
"refactor-ai-timeline-agent-20260326-0157"
]
}
],
"track-reorder-accessibility": [
{
"id": "DEBT-013",
"concern": "replacing arrow buttons with drag-only handle removes keyboard-accessible reorder; plan only specifies pointersensor.",
"occurrence_count": 1,
"plan_ids": [
"fix-track-reordering-bugs-and-20260326-1856"
]
}
],
"track-reorder-testing": [
{
"id": "DEBT-014",
"concern": "no automated tests specified for same-kind boundary rules or save/load persistence of reordered tracks.",
"occurrence_count": 1,
"plan_ids": [
"fix-track-reordering-bugs-and-20260326-1856"
]
}
]
}
code
Escalated debt subsystems:
[]
Debt guidance:
- These are known accepted limitations. Do not re-flag them unless the current plan makes them worse, broadens them, or fails to contain them.
- Prefix every new concern with a subsystem tag followed by a colon, for example `Timeout recovery: retry backoff remains brittle`.
- When a concern is recurring debt that still needs to be flagged, prefix it with `Recurring debt:` after the subsystem tag, for example `Timeout recovery: Recurring debt: retry backoff remains brittle`.
Requirements:
- Consider whether the plan is at the right level of abstraction.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids` should list previously addressed flags that now appear resolved.
- Focus on concrete issues that would cause real problems.
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Verify that the plan remains aligned with the user's original intent.
- Verify that the plan follows the expected structure: one H1 title, `## Overview`, numbered step sections (`### Step N:` under `## Phase` headers, or flat `## Step N:`) with file references and numbered substeps, plus `## Execution Order` or `## Validation Order`.
- Missing required sections or step coverage (for example: no H1, no `## Overview`, or no step sections at all) should be flagged as category `completeness` with severity_hint `likely-significant`.
- Structural formatting within steps (for example: prose instead of numbered substeps, or a missing file reference inside an otherwise actionable step) should usually be category `completeness` with severity_hint `likely-minor` because the executor can still follow the instructions.
- Ask whether the plan is the simplest approach that solves the stated problem, whether it could use fewer steps or less machinery, and whether it introduces unnecessary complexity.
- Over-engineering concerns should use category `maintainability`, should usually prefix the concern with "Over-engineering:", and should scale severity_hint to the practical impact.
- Flag scope creep explicitly when the plan grows beyond the original idea or recorded user notes. Use the phrase "Scope creep:" in the concern.
- Assign severity_hint carefully. Implementation details the executor will naturally resolve should usually be `likely-minor`.
{"flags":[{"id":"new-undo-snapshots-too-late","concern":"Undo snapshots: commitData interception is too late to capture the true pre-edit state for drop flows that mutate editor state in place before calling applyTimelineEdit.","category":"correctness","severity_hint":"likely-significant","evidence":"handleAssetDrop mutates current.tracks and current.rows before the save hook ever runs, then commits via applyTimelineEdit (/Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useAssetManagement.ts#L156 to /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useAssetManagement.ts#L165, /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useAssetManagement.ts#L237 to /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useAssetManagement.ts#L239). External drops do the same for text drops and file drops (/Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useExternalDrop.ts#L167 to /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useExternalDrop.ts#L174, /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useExternalDrop.ts#L194 to /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useExternalDrop.ts#L202, /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useExternalDrop.ts#L229). A snapshot taken in commitData would already include the newly pushed track/row, so undo would not faithfully restore the pre-drop state."},{"id":"new-checkpoint-semantic-plumbing-gap","concern":"Checkpoints: semantic checkpoint plumbing does not actually reach the destructive track-management paths in this repo.","category":"correctness","severity_hint":"likely-significant","evidence":"The plan says to add semantic to commitData and thread it through applyTimelineEdit, but destructive track operations currently go through applyResolvedConfigEdit, whose public options only carry selection fields (/Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useTimelineData.ts#L53 to /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useTimelineData.ts#L63, /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useTimelineSave.ts#L259 to /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useTimelineSave.ts#L275). handleRemoveTrack and the user-facing handleClearUnusedTracks both use that path (/Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useTimelineTrackManagement.ts#L343 to /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useTimelineTrackManagement.ts#L364, /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useTimelineTrackManagement.ts#L407 to /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useTimelineTrackManagement.ts#L440, surfaced in the UI at /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/components/TimelineEditor/TimelineEditor.tsx#L264 to /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/components/TimelineEditor/TimelineEditor.tsx#L268). As written, the plan cannot mark those destructive operations for pre-checkpointing."},{"id":"new-undo-batching-misses-multi-move","concern":"Undo batching: a single multi-clip track move from the keyboard would still produce one undo/save event per clip.","category":"correctness","severity_hint":"likely-significant","evidence":"Arrow up/down already drive bulk movement through moveSelectedClipsToTrack (/Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useKeyboardShortcuts.ts#L49 to /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useKeyboardShortcuts.ts#L60). That helper loops planned moves and calls moveClipToRow once per clip (/Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useTimelineTrackManagement.ts#L296 to /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useTimelineTrackManagement.ts#L298), and each moveClipToRow commits through applyTimelineEdit (/Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useTimelineTrackManagement.ts#L131 to /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useTimelineTrackManagement.ts#L136). The plan only batches drags and 300ms rapid edits, so one keypress on a 5-clip selection would still create 5 undo entries and 5 edit-distance increments."},{"id":"new-history-plan-needs-tests","concern":"Testing: the plan only schedules manual validation even though this feature rewires the editor's core save path and the repository already uses automated tests for timeline hooks/context composition.","category":"completeness","severity_hint":"likely-significant","evidence":"Phase 4 is manual-only, but the repo already has Vitest coverage patterns for timeline behavior in /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useTimelineTrackManagement.test.ts#L1 to /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useTimelineTrackManagement.test.ts#L122 and provider/context wiring in /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/contexts/VideoEditorProvider.test.tsx#L1 to /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/contexts/VideoEditorProvider.test.tsx#L58. With useTimelineSave as the persistence/conflict chokepoint (/Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useTimelineSave.ts#L176 to /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useTimelineSave.ts#L218), omitting automated coverage leaves redo invalidation, semantic checkpointing, and conflict/save interactions uncontained."}],"verified_flag_ids":[],"disputed_flag_ids":[]}
You are an independent reviewer. Critique the plan against the actual repository.
Implement undo/redo/history system for tools/video-editor
Context
The video editor uses React Context + custom hooks. All mutations flow through applyTimelineEdit() in useTimelineSave.ts. There is no existing undo/redo.
Requirements
Two-tier history system:
Tier 1: Undo Stack (fine-grained, in-memory)
Push snapshot of { rows, meta, clipOrder, tracks, output } before every applyTimelineEdit() call
Cap at ~50-100 entries
Cmd+Z / Cmd+Shift+Z
Drag operations and rapid edits should collapse into single undo entries (batch by user gesture using transaction ID or debounce window)
Tier 2: Checkpoints (coarse-grained, persisted to Supabase)
Named snapshots of full TimelineConfig stored in Supabase DB
Keep checkpoints for past 24 hours
Browsable - jump to any checkpoint
Activity-aware checkpoint triggers:
Session boundary: When edit arrives after >5min idle gap, checkpoint pre-edit state
Edit-distance cap: After ~30 edits since last checkpoint, auto-checkpoint
Semantic triggers: Before destructive ops (delete track, bulk delete, clear timeline) + manual Save checkpoint
Manages idle timer via ref tracking lastEditTimestamp
Checkpoints cap at ~20-30, undo stack at ~50-100
code
Plan:
# Implementation Plan: Undo/Redo/History System for Video Editor
Overview
The video editor currently has no undo/redo capability. All mutations flow through applyTimelineEdit() and applyResolvedConfigEdit() in useTimelineSave.ts, which immediately update state and schedule a debounced save to Supabase. The commitData() function is the single chokepoint where all state changes are applied — it updates dataRef, calls setData(), and triggers scheduleSave().
Architecture insight: The TimelineData object (defined in timeline-data.ts:60-73) contains the full serializable state: config, rows, meta, clipOrder, tracks, output. This is exactly the snapshot we need for undo entries.
Key constraint: There are two mutation paths — applyTimelineEdit (row/meta level, ~85 call sites across 10 hooks) and applyResolvedConfigEdit (resolved config level, used by track management and agent chat). Both funnel through commitData. The history system must intercept at the commitData level to catch all mutations.
Pre-mutation snapshot problem: Some callers (asset drops, external drops, text tool drops) mutate dataRef.current.tracks and dataRef.current.rows in-place before calling applyTimelineEdit (useAssetManagement.ts:164-165, useExternalDrop.ts:171-172, useExternalDrop.ts:197-202). A snapshot taken inside commitData would already reflect these mutations. The fix: snapshot at the applyTimelineEdit/applyResolvedConfigEdit level (before any caller-side mutations are visible), not at commitData.
No existing checkpoint infrastructure: The timelines table stores only current config + config_version. A new table is needed for checkpoints.
Settled decisions (from prior review)
Intercept at commitData level for the onBeforeCommit callback, BUT use config-based snapshots (derived from the last committed config, not dataRef.current) to avoid the pre-mutation problem.
Undo stack is in-memory refs; checkpoints are Supabase-persisted. canUndo/canRedo are React state updated only on empty/non-empty transitions.
jumpToCheckpoint clears the undo/redo stacks entirely.
Agent chat edits via applyResolvedConfigEdit participate in undo.
Client-side checkpoint cleanup (DELETE on load).
Phase 1: Foundation — Types, DB Migration, DataProvider
Step 1: Define history types (src/tools/video-editor/types/history.ts)
Scope: Small
Create a new types file with:
typescript
// The snapshot is config-based (not dataRef), so it's always the last committed state
export interface UndoSnapshot {
config: TimelineConfig; // The full serializable config
signature: string; // For dedup
}
export interface UndoEntry {
snapshot: UndoSnapshot;
timestamp: number;
label?: string;
transactionId?: string; // For collapsing drags/multi-move
}
export type CheckpointTriggerType = 'session_boundary' | 'edit_distance' | 'semantic' | 'manual';
export interface Checkpoint {
id: string;
timelineId: string;
config: TimelineConfig;
createdAt: string;
triggerType: CheckpointTriggerType;
label: string;
editsSinceLastCheckpoint: number;
}
Key design note: Snapshots store config (not rows/meta/clipOrder), because config is the serializable source of truth. On undo, we rebuild full TimelineData from the snapshot config + current registry using buildDataFromCurrentRegistry() from timeline-save-utils.ts. This avoids the pre-mutation snapshot problem entirely — the last saved/committed config is always clean.
Step 2: Create Supabase migration for timeline_checkpoints table (supabase/migrations/)
Scope: Small
Create migration file:
sql
CREATE TABLE timeline_checkpoints (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
timeline_id UUID NOT NULL REFERENCES timelines(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES auth.users(id),
config JSONB NOT NULL,
trigger_type TEXT NOT NULL CHECK (trigger_type IN ('session_boundary', 'edit_distance', 'semantic', 'manual')),
label TEXT NOT NULL,
edits_since_last_checkpoint INT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX idx_timeline_checkpoints_timeline ON timeline_checkpoints(timeline_id, created_at DESC);
Add RLS policy: users can only read/write/delete their own checkpoints.
Cleanup is client-side:loadCheckpoints will DELETE rows older than 24h before selecting.
Add an onBeforeCommit ref to the hook parameters. Call it inside commitData before the state update, but ONLY when options?.save !== false and !options?.skipHistory:
typescript
// At the top of commitData, before dataRef.current = nextData:
if ((options?.save ?? true) && !options?.skipHistory) {
onBeforeCommitRef.current?.(dataRef.current, {
transactionId: options?.transactionId,
semantic: options?.semantic,
});
}
Update applyTimelineEdit signature at useTimelineSave.ts:220-257 — add transactionId?: string and semantic?: boolean to its options parameter and forward them to commitData.
Update applyResolvedConfigEdit signature at useTimelineSave.ts:259-275 — add semantic?: boolean to its options and forward to commitData. This is critical for destructive track operations.
Mark existing non-edit commits as skipHistory: The polling/reload paths already use save: false, but add explicit skipHistory: true to reloadFromServer (useTimelineSave.ts:436) and the polled-data sync effect (useTimelineSave.ts:367) to be safe.
Return the onBeforeCommitRef from useTimelineSave so useTimelineData can wire the history hook.
Snapshot strategy — config-based, not dataRef-based:
The onBeforeCommit callback receives currentData (the value of dataRef.current at the moment commitData is called).
Critical: For the pre-mutation problem (asset drops mutating dataRef.current.tracks/rows before commitData), we snapshot currentData.config — not rows/meta/tracks. The config is only rebuilt from rows inside materializeData() which runs inside applyTimelineEdit, so currentData.config always reflects the last committed state, unaffected by in-place mutations to rows/tracks.
[canUndo, setCanUndo] = useState(false), [canRedo, setCanRedo] = useState(false) — updated only on empty↔non-empty transitions.
Cap undo stack at 100 entries; drop oldest when exceeded.
Step 6: Wire useTimelineHistory into the data layer (src/tools/video-editor/hooks/useTimelineData.ts, src/tools/video-editor/hooks/useTimelineState.types.ts, src/tools/video-editor/hooks/useTimelineState.ts)
Scope: Medium
Instantiate the history hook in useTimelineData.ts:74-129:
typescript
const history = useTimelineHistory({
dataRef: save.dataRef,
commitData: save.commitData,
provider,
timelineId,
userId,
});
// Wire the callback
save.onBeforeCommitRef.current = history.onBeforeCommit;
Update UseTimelineDataResult in useTimelineData.ts:22-72 to include: undo, redo, canUndo, canRedo, checkpoints, jumpToCheckpoint, createManualCheckpoint.
Thread through context — add history fields to TimelineChromeContextValue in useTimelineState.types.ts:87-104:
Wire in useTimelineState.ts — pass these fields from dataHook into the chrome memo (useTimelineState.ts:335-369).
Phase 3: Transaction IDs & Semantic Markers
Step 7: Pass transactionId for drag and resize operations (src/tools/video-editor/hooks/useClipDrag.ts, src/tools/video-editor/hooks/useClipResize.ts)
Scope: Small
In useClipDrag.ts: The drag session object already exists. Generate a stable transactionId (e.g., crypto.randomUUID()) when a new drag session starts, store it on the session. At useClipDrag.ts:402, pass { transactionId: session.transactionId } in the options to applyTimelineEdit.
In useClipResize.ts: Same pattern — generate transaction ID at resize start, pass through all applyTimelineEdit calls during the resize.
Step 8: Pass transactionId for multi-clip keyboard track moves (src/tools/video-editor/hooks/useTimelineTrackManagement.ts)
Scope: Small — addresses the per-clip loop problem
In moveSelectedClipsToTrack (useTimelineTrackManagement.ts:296-298): The loop calls moveClipToRow once per clip, each of which calls applyTimelineEdit. Generate a single transactionId before the loop and pass it through.
Modify moveClipToRow (useTimelineTrackManagement.ts:131-136) to accept an optional transactionId and forward it to applyTimelineEdit:
In moveSelectedClipsToTrack (useTimelineTrackManagement.ts:296):
typescript
const txnId = crypto.randomUUID();
for (const move of plannedMoves) {
moveClipToRow(move.clipId, move.targetRowId, { transactionId: txnId });
}
This ensures a single keyboard press on a 5-clip selection creates exactly 1 undo entry.
Step 9: Mark destructive operations as semantic (src/tools/video-editor/hooks/useClipEditing.ts, src/tools/video-editor/hooks/useTimelineTrackManagement.ts)
Scope: Small
In handleDeleteClips (useClipEditing.ts): pass { semantic: true } in options to applyTimelineEdit.
In handleRemoveTrack (useTimelineTrackManagement.ts:343-364): This uses applyResolvedConfigEdit. Pass { semantic: true } — this is now possible because Step 4 added semantic to applyResolvedConfigEdit's options.
In handleClearUnusedTracks (useTimelineTrackManagement.ts:407-440): Same — pass { semantic: true } to applyResolvedConfigEdit.
Verify all destructive paths are covered. The exhaustive list of destructive operations using applyResolvedConfigEdit:
handleRemoveTrack → applyResolvedConfigEdit at line 363
handleClearUnusedTracks → applyResolvedConfigEdit at line 439
ImportUndo2, Redo2, History from lucide-react (add to existing import at VideoEditorShell.tsx:2).
Phase 5: Automated Tests
Step 12: Unit tests for useTimelineHistory (src/tools/video-editor/hooks/useTimelineHistory.test.ts)
Scope: Medium — follows existing Vitest patterns in the repo (useTimelineTrackManagement.test.ts, VideoEditorProvider.test.tsx)
Test: basic undo/redo cycle — make 3 edits via onBeforeCommit + mock commitData, call undo() 3 times, verify each snapshot is restored, call redo(), verify forward navigation.
Test: redo invalidation — edit A→B→C, undo to B, make edit D, verify canRedo is false.
Test: transaction collapsing — push 5 entries with same transactionId, verify only 1 undo entry is created. Push entries with different transaction IDs, verify separate entries.
Test: 300ms debounce collapsing — push 3 entries within 300ms (no transactionId), verify they collapse. Push entry after 500ms gap, verify new entry.
Test: undo stack cap — push 120 entries, verify stack size is 100 and oldest entries were dropped.
Test: checkpoint triggers —
Session boundary: set lastEditTimestamp to 6 minutes ago, trigger commit, verify saveCheckpoint called with 'session_boundary'.
Edit distance: trigger 30 commits, verify saveCheckpoint called with 'edit_distance'.
Semantic: trigger commit with semantic: true, verify saveCheckpoint called with 'semantic'.
Test: jumpToCheckpoint clears stacks — populate undo/redo, jump to checkpoint, verify both are empty.
Test: skipHistory flag — call onBeforeCommit with skipHistory scenario (simulated), verify no stack push.
Step 13: Run existing tests to verify no regressions (src/tools/video-editor/)
Scope: Small
Runnpx vitest run src/tools/video-editor/ to verify all existing tests pass after the commitData and applyTimelineEdit signature changes.
Fix any type errors in existing tests caused by the new optional parameters.
Phase 6: Manual Validation
Step 14: Manual testing protocol
Scope: Medium
Undo/redo basic flow: Make 3 edits → Cmd+Z three times → verify each state restores → Cmd+Shift+Z → verify redo works.
Drag collapsing: Drag a clip → undo → verify it returns to pre-drag position in one step.
Asset drop undo: Drop an asset onto the timeline (creating a new track) → undo → verify the clip AND the auto-created track are removed.
Multi-clip keyboard move: Select 3 clips, press Arrow Up → undo → verify all 3 clips return to original tracks in one step.
Redo invalidation: Make edit A → B → C → undo to B → make edit D → verify redo stack is cleared.
Semantic checkpoint: Delete a track → verify checkpoint appears in history dropdown before the deletion.
Checkpoint restore: Jump to a previous checkpoint → verify timeline fully restores and undo/redo buttons reset.
Save status: After undo, verify save status goes dirty → saving → saved.
Execution Order
Phase 1 first: types + DB migration + provider methods are dependencies for everything.
Phase 2 next: core hook + wiring into commitData. This is the bulk of the work.
Phase 3: transaction IDs and semantic markers — these are small targeted changes to existing hooks.
Phase 4: UI and keyboard shortcuts consume the hook.
Phase 5: automated tests — write after the core is functional so tests validate real behavior.
Phase 6: manual validation as final pass.
Validation Order
After Step 5: verify undo/redo works via console (call from devtools).
After Step 8: verify multi-clip keyboard move undoes as single entry.
After Step 10: verify Cmd+Z/Cmd+Shift+Z work end-to-end.
After Step 12: run npx vitest run src/tools/video-editor/hooks/useTimelineHistory.test.ts.
After Step 13: run full video editor test suite.
After Step 14: full manual validation.
Risk Notes
Snapshot size: A TimelineConfig with 50 clips is ~10-20KB JSON. 100 undo entries ≈ 1-2MB. Acceptable for in-memory.
Pre-mutation safety: By snapshotting config (rebuilt by materializeData inside applyTimelineEdit) rather than dataRef.current.rows/tracks, we avoid the problem where drop handlers mutate dataRef in-place before calling the edit function. The config from the previous commit is always clean.
Registry/resolved URLs: Undo snapshots store config but NOT registry or resolved URLs. On undo, we rebuild TimelineData from the snapshot config + current registry using buildDataFromCurrentRegistry(). This avoids stale signed URLs.
Concurrent edits: If another tab edits the timeline during undo, the existing conflict detection dialog still applies. Undo writes through the normal save path with version checking.
code
Plan metadata:
{
"version": 2,
"timestamp": "2026-03-26T21:54:18Z",
"hash": "sha256:96805accde08ed4441644daf88f6809620c5d76c0dbf28721a5bebcbe47c651f",
"changes_summary": "Revision 2 changes from v1:\n\n1. Flag: snapshots-too-late \u2014 Redesigned snapshot strategy. Instead of snapshotting dataRef.current (which can be pre-mutated by drop handlers), we snapshot currentData.config \u2014 the config from the last committed state. config is only rebuilt inside materializeData() which runs inside applyTimelineEdit, so it's never affected by in-place mutations to rows/tracks. Added explicit coverage of asset drop undo in manual testing (Step 14.3).\n\n2. Flag: semantic-plumbing-gap \u2014 Extended applyResolvedConfigEdit (not just applyTimelineEdit) to accept semantic?: boolean in its options (Step 4.4). Updated Step 9 to explicitly mark handleRemoveTrack and handleClearUnusedTracks (which both use applyResolvedConfigEdit) with semantic: true. Added an exhaustive list of all applyResolvedConfigEdit callers with destructive/non-destructive classification.\n\n3. Flag: batching-misses-multi-move \u2014 Added Step 8 specifically for multi-clip keyboard track moves. moveSelectedClipsToTrack now generates a single before its per-clip loop and passes it through \u2192 . Added parameter to . Added manual test case for multi-clip move undo (Step 14.4).\n\n4. \u2014 Added Phase 5 with two steps: Step 12 (8 specific unit test cases for covering undo/redo cycles, redo invalidation, transaction collapsing, debounce collapsing, stack cap, all 3 checkpoint triggers, jumpToCheckpoint, and skipHistory) and Step 13 (regression check on existing test suite).\n\n5. \u2014 Reduced from to just since we rebuild everything from config on restore. This is leaner and avoids the pre-mutation problem entirely.\n\n6. \u2014 More explicit than relying on to determine whether to push onto undo stack. Reload and polling paths now explicitly opt out.",
"flags_addressed": [
"new-undo-snapshots-too-late",
"new-checkpoint-semantic-plumbing-gap",
"new-undo-batching-misses-multi-move",
"new-history-plan-needs-tests"
],
"questions": [],
"success_criteria": [
"Cmd+Z undoes the most recent edit and restores the full previous timeline state (clips, tracks, positions, metadata)",
"Cmd+Shift+Z redoes after an undo, and redo stack is cleared when a new edit is made after undo",
"Dragging a clip collapses into a single undo entry (undo restores to pre-drag state, not intermediate positions)",
"Multi-clip keyboard track move (Arrow Up/Down with multiple selected) collapses into a single undo entry",
"Rapid slider/property edits within 300ms collapse into a single undo entry",
"Asset drop undo correctly removes both the clip AND any auto-created track",
"Undo/redo buttons appear next to save badge, are disabled when stack is empty, and visually indicate availability",
"History dropdown shows checkpoint list with labels, trigger types, and timestamps",
"Checkpoints auto-create on session boundary (>5min idle gap), edit-distance cap (~30 edits), and before destructive operations (delete track, clear unused tracks, bulk delete clips)",
"Manual 'Save checkpoint' creates a named checkpoint visible in the history panel",
"Jumping to a checkpoint fully restores the timeline to that saved state and clears undo/redo stacks",
"Checkpoints persist across page reloads (stored in Supabase), limited to past 24 hours",
"Undo triggers a normal save to Supabase (the restored state is persisted)",
"No performance regression: undo stack snapshots stay under 2MB total, checkpoint saves are async",
"Automated Vitest tests cover: undo/redo cycles, redo invalidation, transaction collapsing, debounce collapsing, stack cap, all 3 auto-checkpoint triggers, jumpToCheckpoint stack clearing",
"Existing video editor tests pass without regressions after commitData signature changes"
],
"assumptions": [
"Undo snapshots store only { config: TimelineConfig, signature: string } \u2014 not the full TimelineData. On restore, we rebuild via buildDataFromCurrentRegistry(config, currentData) which keeps current registry and resolved URLs intact. This sidesteps the pre-mutation problem because config is only produced by materializeData() inside applyTimelineEdit, not affected by in-place dataRef mutations.",
"The onBeforeCommit hook fires inside commitData (before state update) and receives the current dataRef.current. Since we only read .config and .signature from it (not .rows/.tracks), pre-mutation of rows/tracks by drop handlers does not affect our snapshot.",
"canUndo/canRedo are React state (boolean) updated only when the stack transitions between empty and non-empty, to avoid re-rendering the entire editor tree on every edit.",
"The undo stack cap is 100 entries and checkpoint cap is 30 per timeline \u2014 both are generous defaults that can be tuned later.",
"jumpToCheckpoint clears the undo/redo stacks entirely (most predictable UX).",
"Agent chat edits via applyResolvedConfigEdit participate in undo (they flow through commitData like everything else).",
"Client-side checkpoint cleanup (DELETE on load) \u2014 no Edge Function or DB trigger needed for initial implementation.",
"Transaction collapsing uses exact transactionId matching for explicit gestures (drag, resize, multi-clip move) and a 300ms time window for rapid untransacted edits (slider changes)."
],
"structure_warnings": [
"Each step section should reference at least one file in backticks."
],
"delta_from_previous_percent": 72.77
}
{"flags":[{"id":"new-agent-chat-undo-path-mismatch","concern":"Agent chat integration: the plan still assumes agent edits arrive through applyResolvedConfigEdit, but in this repo agent output refreshes the timeline via query invalidation/realtime, so those changes will still bypass history when polling/reload commits are marked skipHistory.","category":"correctness","severity_hint":"likely-significant","evidence":"applyResolvedConfigEdit is only used in src/tools/video-editor/hooks/useClipEditing.ts:219,259,272,326 and src/tools/video-editor/hooks/useTimelineTrackManagement.ts:174,315,327,340,363,439; there is no agent-chat callsite. Agent sends invalidate the timeline query in src/tools/video-editor/hooks/useAgentSession.ts:288-295, realtime invalidates the same query in src/tools/video-editor/hooks/useTimelineRealtime.ts:27-47, and useTimelineSave applies polled data through commitData(..., { save: false }) in src/tools/video-editor/hooks/useTimelineSave.ts:340-374. Because the revised plan explicitly marks polling/reload paths as skipHistory, the claimed 'agent chat edits participate in undo' behavior is still not wired to the repository's actual agent-edit path."},{"id":"new-checkpoint-edit-distance-overcounts-transactions","concern":"Checkpoint counting: transaction-collapsed gestures still count once per low-level commit toward the 30-edit auto-checkpoint cap.","category":"correctness","severity_hint":"likely-minor","evidence":"The repository's multi-clip keyboard move still loops moveClipToRow for each selected clip in src/tools/video-editor/hooks/useTimelineTrackManagement.ts:296-298, and each call commits through applyTimelineEdit at src/tools/video-editor/hooks/useTimelineTrackManagement.ts:131-136. The revised plan adds a shared transactionId so undo entries collapse, but its checkpoint logic still says to increment editsSinceCheckpoint on each commit. A single Arrow Up/Down gesture on 5 clips would therefore consume 5 of the 30 edit-distance slots and auto-checkpoint earlier than intended."},{"id":"new-plan-structure-missing-file-ref","concern":"Plan structure: completeness warning remains because at least one numbered step still lacks a repo file reference.","category":"completeness","severity_hint":"likely-minor","evidence":"The validator still reports Each step section should reference at least one file in backticks. In the current draft, ### Step 14: Manual testing protocol is a numbered step with no file reference, so the plan still misses the requested per-step file anchoring."}],"verified_flag_ids":["new-undo-snapshots-too-late","new-checkpoint-semantic-plumbing-gap","new-undo-batching-misses-multi-move","new-history-plan-needs-tests"],"disputed_flag_ids":[]}
In onBeforeCommit: if transactionId is provided and matches the top entry's transactionId, skip pushing (the pre-gesture snapshot is already captured).
For rapid untransacted edits within 300ms: if no transactionId, check if Date.now() - topEntry.timestamp < 300. If so, skip pushing (keep the older snapshot).
This handles: drag (transactionId), resize (transactionId), multi-clip keyboard move (transactionId), and slider edits (300ms debounce).
Undo/redo execution:
undo(): Pop from undo stack, push { config: dataRef.current.config, signature: dataRef.current.signature } onto redo stack. Rebuild full TimelineData from snapshot config using buildDataFromCurrentRegistry(poppedEntry.snapshot.config, dataRef.current). Call commitData(rebuilt, { save: true, skipHistory: true }).
redo(): Mirror of undo.
buildDataFromCurrentRegistry (from timeline-save-utils.ts) takes a config and a current TimelineData, keeping the current registry/resolved URLs intact.
Checkpoint triggers (activity-aware):
Track lastEditTimestamp (ref, init to Date.now()) and editsSinceCheckpoint (ref, init to 0).
All checkpoint logic runs inside onBeforeCommit:
Session boundary: If Date.now() - lastEditTimestamp > 5 * 60 * 1000, save checkpoint of current state with trigger 'session_boundary' and label like "Before edit (5m idle)".
Edit-distance cap: Increment editsSinceCheckpoint. At 30, auto-checkpoint with trigger 'edit_distance' and label like "Auto-save (30 edits)".
Semantic triggers: If opts.semantic, save checkpoint with trigger 'semantic' and label like "Before destructive edit".
After any checkpoint: reset editsSinceCheckpoint to 0, update lastCheckpointTimestamp.
Update lastEditTimestamp = Date.now() on every commit.
Manual:createManualCheckpoint(label?) saves current dataRef.current.config immediately.
"Each step section should reference at least one file in backticks."
]
code
Existing flags:
[
{
"id": "new-undo-snapshots-too-late",
"concern": "Undo snapshots: commitData interception is too late to capture the true pre-edit state for drop flows that mutate editor state in place before calling applyTimelineEdit.",
"status": "addressed",
"severity": "significant"
},
{
"id": "new-checkpoint-semantic-plumbing-gap",
"concern": "Checkpoints: semantic checkpoint plumbing does not actually reach the destructive track-management paths in this repo.",
"status": "addressed",
"severity": "significant"
},
{
"id": "new-undo-batching-misses-multi-move",
"concern": "Undo batching: a single multi-clip track move from the keyboard would still produce one undo/save event per clip.",
"status": "addressed",
"severity": "significant"
},
{
"id": "new-history-plan-needs-tests",
"concern": "Testing: the plan only schedules manual validation even though this feature rewires the editor's core save path and the repository already uses automated tests for timeline hooks/context composition.",
"status": "addressed",
"severity": "significant"
}
]
code
Known accepted debt grouped by subsystem:
{
"agent-chat-rendering": [
{
"id": "DEBT-007",
"concern": "removing the duplicate assistant turn may hide message_user text if the frontend only renders assistant-role turns as chat bubbles.",
"occurrence_count": 1,
"plan_ids": [
"refactor-ai-timeline-agent-20260326-0157"
]
}
],
"bulk-panel-tabs": [
{
"id": "DEBT-010",
"concern": "text clip multi-selections would miss the position tab under the plan's stated rule.",
"occurrence_count": 1,
"plan_ids": [
"multi-select-feature-parity-20260326-0548"
]
}
],
"bulk-properties-panel": [
{
"id": "DEBT-016",
"concern": "bulkclippanel still imports customeffecteditor; removing it without updating bulk mode would break the build.",
"occurrence_count": 1,
"plan_ids": [
"build-an-llm-powered-custom-20260326-2230"
]
}
],
"clip-drag-scroll-sync": [
{
"id": "DEBT-015",
"concern": "the plan's step 3 ontick callback only shows coordinator.update() but the full clip-drag state path (snap, lateststart, ghost positions) also needs re-running during stationary-pointer scroll.",
"occurrence_count": 1,
"plan_ids": [
"add-auto-scroll-to-the-20260326-2119"
]
}
],
"conflict-resolution": [
{
"id": "DEBT-004",
"concern": "silently reloading agent-originated timeline updates would discard dirty local edits.",
"occurrence_count": 1,
"plan_ids": [
"build-a-turn-based-timeline-20260326-0005"
]
}
],
"context-menu-scope": [
{
"id": "DEBT-012",
"concern": "multi-clip copy is not included despite being mentioned in the original idea.",
"occurrence_count": 1,
"plan_ids": [
"multi-select-feature-parity-20260326-0548"
]
}
],
"issue-detection": [
{
"id": "DEBT-006",
"concern": "mid-sentence-cut detection is not implementable without transcript/profile data that the current provider doesn't expose.",
"occurrence_count": 1,
"plan_ids": [
"build-a-turn-based-timeline-20260326-0005"
]
}
],
"legacy-effect-lifecycle": [
{
"id": "DEBT-017",
"concern": "removing customeffecteditor makes effects-table entries read-only \u2014 users can no longer edit legacy custom effects.",
"occurrence_count": 1,
"plan_ids": [
"build-an-llm-powered-custom-20260326-2230"
]
}
],
"optimistic-locking": [
{
"id": "DEBT-002",
"concern": "plan only specifies version checking at the db write layer; the ui load/state/save path doesn't carry config_version yet.",
"occurrence_count": 1,
"plan_ids": [
"build-a-turn-based-timeline-20260326-0005"
]
}
],
"properties-panel-scope": [
{
"id": "DEBT-011",
"concern": "crop and transition controls are not included in the bulk panel, narrowing the original idea's scope.",
"occurrence_count": 1,
"plan_ids": [
"multi-select-feature-parity-20260326-0548"
]
}
],
"realtime-subscriptions": [
{
"id": "DEBT-003",
"concern": "the shared realtime system doesn't know about timeline_agent_sessions; step 7 hooks need their own channel subscription.",
"occurrence_count": 1,
"plan_ids": [
"build-a-turn-based-timeline-20260326-0005"
]
}
],
"selection-save-bridge": [
{
"id": "DEBT-009",
"concern": "the plan specifies passing pruneselection into usetimelinesave but doesn't detail the hook-layer bridge needed because usetimelinesave is instantiated inside usetimelinedata before usetimelinestate runs.",
"occurrence_count": 1,
"plan_ids": [
"multi-select-timeline-clips-20260326-0415"
]
}
],
"task-deduplication": [
{
"id": "DEBT-001",
"concern": "server-generated idempotency keys would break retry deduplication because retried requests get fresh keys.",
"occurrence_count": 1,
"plan_ids": [
"migrate-all-task-creation-20260325-2354"
]
}
],
"task-system-integration": [
{
"id": "DEBT-005",
"concern": "create_generation_task is underspecified against the actual task family system.",
"occurrence_count": 1,
"plan_ids": [
"build-a-turn-based-timeline-20260326-0005"
]
}
],
"tool-error-propagation": [
{
"id": "DEBT-008",
"concern": "a blanket catch in executetool would silently downgrade db/persistence failures into ordinary tool results, changing the session error/http 500 behavior.",
"occurrence_count": 1,
"plan_ids": [
"refactor-ai-timeline-agent-20260326-0157"
]
}
],
"track-reorder-accessibility": [
{
"id": "DEBT-013",
"concern": "replacing arrow buttons with drag-only handle removes keyboard-accessible reorder; plan only specifies pointersensor.",
"occurrence_count": 1,
"plan_ids": [
"fix-track-reordering-bugs-and-20260326-1856"
]
}
],
"track-reorder-testing": [
{
"id": "DEBT-014",
"concern": "no automated tests specified for same-kind boundary rules or save/load persistence of reordered tracks.",
"occurrence_count": 1,
"plan_ids": [
"fix-track-reordering-bugs-and-20260326-1856"
]
}
]
}
code
Escalated debt subsystems:
[]
Debt guidance:
- These are known accepted limitations. Do not re-flag them unless the current plan makes them worse, broadens them, or fails to contain them.
- Prefix every new concern with a subsystem tag followed by a colon, for example `Timeout recovery: retry backoff remains brittle`.
- When a concern is recurring debt that still needs to be flagged, prefix it with `Recurring debt:` after the subsystem tag, for example `Timeout recovery: Recurring debt: retry backoff remains brittle`.
Requirements:
- Consider whether the plan is at the right level of abstraction.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids` should list previously addressed flags that now appear resolved.
- Focus on concrete issues that would cause real problems.
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Verify that the plan remains aligned with the user's original intent.
- Verify that the plan follows the expected structure: one H1 title, `## Overview`, numbered step sections (`### Step N:` under `## Phase` headers, or flat `## Step N:`) with file references and numbered substeps, plus `## Execution Order` or `## Validation Order`.
- Missing required sections or step coverage (for example: no H1, no `## Overview`, or no step sections at all) should be flagged as category `completeness` with severity_hint `likely-significant`.
- Structural formatting within steps (for example: prose instead of numbered substeps, or a missing file reference inside an otherwise actionable step) should usually be category `completeness` with severity_hint `likely-minor` because the executor can still follow the instructions.
- Ask whether the plan is the simplest approach that solves the stated problem, whether it could use fewer steps or less machinery, and whether it introduces unnecessary complexity.
- Over-engineering concerns should use category `maintainability`, should usually prefix the concern with "Over-engineering:", and should scale severity_hint to the practical impact.
- Flag scope creep explicitly when the plan grows beyond the original idea or recorded user notes. Use the phrase "Scope creep:" in the concern.
- Assign severity_hint carefully. Implementation details the executor will naturally resolve should usually be `likely-minor`.