You are creating an implementation plan for the following idea.
code
Idea:
Clean up the structural smells in the video-editor resize/preview architecture that have caused recurring bugs all session. The most recent symptom: when a user drags an interior boundary inside a pinned shot group, the live preview position is subtly wrong during the drag (boundary lags or jitters), but the committed position on release is correct. The root cause is structural — the live preview math and the commit math live in two different code paths that recompute the same answer in different files, the dual state (resizePreviewRef vs resizeOverrides) lets the rendered position drift one frame behind the synchronous source of truth, and the cursor-to-handle offset isnt captured anywhere so the boundary always trails the cursor by some pixels. None of these are bugs — theyre places where the architecture relies on parallel implementations agreeing, with no shared function or test enforcing it.
This is a focused structural cleanup, not a re-architecture. Five items, in priority order by leverage. Each item is testable in isolation.
State of completion BEFORE this megaplan: Coming out of the previous finish projection rollback megaplan, the data shape is fully soft-tag, the resize session model is unified (clip | group-child-boundary | group-edge), useClipDrag/useClipResize/usePinnedGroupSync/useSwitchToFinalVideo/useExternalDrop/useTimelineTrackManagement are all rewritten for the soft-tag model, the deprecated shims are gone, and 210/210 video-editor tests pass. The user has confirmed dragging an interior boundary ends up perfect on release — so the commit path is correct. The bug is purely in the live preview being subtly off from the committed result.
The 5 cleanups:
Extract computeResizeBoundary as a shared pure function (highest leverage). Currently TimelineCanvas.updateResize (the live preview) and useClipResize.onActionResizeEnd (the commit) both compute the new boundary position given a cursor delta — but in different files, with different intermediate variable names, and no shared function. Create src/tools/video-editor/lib/resize-math.ts with computeGroupChildBoundaryResize and computeGroupEdgeResize pure functions. Both live preview and commit call these. Add unit tests for clamping, direction, min-duration.
Capture the cursor-to-handle offset at session start. The resize handle is 8px wide. deltaSeconds = (clientX - initialClientX) / pixelsPerSecond assumes the cursor STARTED ON the boundary. Fix: at pointer-down, compute boundaryPixel = startLeft + (dir === left ? action.start : action.end) * pixelsPerSecond and cursorOffsetPx = clientX - boundaryPixel. Store on session. In updateResize: cursorBoundaryPixel = clientX - cursorOffsetPx; cursorBoundaryTime = (cursorBoundaryPixel - startLeft) / pixelsPerSecond. Apply for all three resize kinds.
Assistant
User
Assistant
Eliminate the dual resizePreviewRef / resizeOverrides state. Use useSyncExternalStore to subscribe to the ref, or a version counter. Eliminate the React state lag. SortableRow renders from the same source the commit reads.
Centralize pixel ↔ time conversion. Extract useTimelineScale({ scale, scaleWidth, startLeft }) returning pixelsPerSecond, pixelsPerSecondRef, timeToPixel, pixelToTime. All consumers use it.
Add an end-to-end resize integration test using @testing-library/react + fireEvent. Render real TimelineCanvas with shot group of 3 clips. Fire pointerdown on middle clip right handle, pointermove, assert DOM boundary position matches expected. Fire pointerup, assert no jump. Variant for group-edge.
Hard requirements: User symptom fixed. No regressions in: drag clip body in pinned group, drag right edge of last clip, drag left edge of first clip, drag interior boundary, cross-track drag grouped clip, switch shot to/from final video, drag shot from gallery, auto-save defers, poll-sync defers, migration loads projection-shape. tsc -p tsconfig.app.json --noEmit clean for src/tools/video-editor/. All video-editor tests pass (210 currently). Shared computeGroupChildBoundaryResize/computeGroupEdgeResize exist with unit tests and both live preview AND commit call them. Cursor offset captured for all 3 resize kinds. Dual state collapsed to one source. useTimelineScale exists and used by all consumers. At least one end-to-end resize test.
Constraints: video-editor tool only, no DB schema changes, follow CLAUDE.md, prefer Edit over Write, dont bundle unrelated cleanups, leave pre-existing non-video-editor failures alone, no new state management libraries, new resize-math functions PURE (no hooks/refs/side effects), e2e test uses @testing-library/react + fireEvent.
Success: boundary tracks cursor pixel-perfectly during drag, tsc clean, all tests pass, new pure functions referenced by both live preview and commit (grep-verifiable), dual state collapsed (grep verifiable), at least one e2e pointer test passes, resize subsystem line count decreases net.
code
Project directory:
/Users/user_c042661f/Documents/reigh-workspace/reigh-app
No prior clarification artifact exists. Identify ambiguities, ask clarifying questions, and state your assumptions inside the plan output.
Requirements:
- If the engineering brief suggests an approach, use it as your starting hypothesis — but before committing, consider if there's a simpler or more fundamental fix. The brief is well-researched input, not a final answer.
- If the brief is absent, incomplete, or says "skip", inspect the repository yourself before planning.
- Produce a concrete implementation plan in markdown.
- Define observable success criteria as objects with `criterion` (string) and `priority` (`must`, `should`, or `info`):
- `must` — hard gate. The reviewer will block on failure. Use for correctness, functional requirements, and verifiable outcomes (e.g., "all existing tests pass", "API returns 200 for valid input"). Every `must` criterion must have a clear yes/no answer.
- `should` — quality target. The reviewer flags but does not block. Use for subjective goals, numeric guidelines, and best-effort improvements (e.g., "file under ~300 lines", "no deeply nested conditionals", "each function has a single responsibility").
- `info` — documented for humans, reviewer skips. Use for criteria that cannot be verified in this pipeline (e.g., "13 manual smoke tests pass", "stakeholder sign-off obtained").
- Use the `questions` field for ambiguities that would materially change implementation.
- Use the `assumptions` field for defaults you are making so planning can proceed now.
- Prefer cheap validation steps early.
- Keep the plan proportional to the task. A 1-line fix needs a 2-step plan (apply fix + run tests), not a 5-step investigation.
- If user notes answer earlier questions, incorporate them into the draft plan instead of re-asking them.
- Fix the problem fully. Do not limit scope just to avoid breaking existing tests — update the tests too if needed.
- Prefer the simplest, most direct fix. No fallbacks, type conversions, or defensive wrappers without concrete evidence they are needed.
- If the task or issue hints suggest a specific approach, follow it. Only deviate with concrete counter-evidence.
Plan template — simple format (adapt to the actual repo and scope):
md
# Implementation Plan: [Title]
## Overview
Summarize the goal, current repository shape, and the constraints that matter.
## Main Phase
### Step 1: Audit the current behavior (`megaplan/prompts.py`)
**Scope:** Small
1. **Inspect** the current implementation and call out the exact insertion points (`megaplan/prompts.py:29`).
### Step 2: Add the first change (`megaplan/evaluation.py`)
**Scope:** Medium
1. **Implement** the smallest viable change with exact file references (`megaplan/evaluation.py:1`).
2. **Capture** any tricky behavior with a short example.
```python
issues = validate_plan_structure(plan_text)
```
### Step 3: Wire downstream behavior (`megaplan/handlers.py`, `megaplan/workers.py`)
**Scope:** Medium
1. **Update** the runtime flow in the touched files (`megaplan/handlers.py:400`, `megaplan/workers.py:199`).
### Step 4: Prove the change (`tests/test_evaluation.py`, `tests/test_megaplan.py`)
**Scope:** Small
1. **Run** the cheapest targeted checks first (`tests/test_evaluation.py:1`).
2. **Finish** with broader verification once the wiring is in place (`tests/test_megaplan.py:1`).
## Execution Order
1. Update prompts and mocks before enforcing stricter validation.
2. Land higher-risk wiring after the validator and tests are ready.
## Validation Order
1. Start with focused unit tests.
2. Run the broader suite after the flow changes are in place.
For complex plans, use multiple phases:
md
## Phase 1: Foundation — Dependencies, DB, Types
### Step 1: Install dependencies (`package.json`)
...
### Step 2: Create database migration (`supabase/migrations/`)
...
## Phase 2: Core Integration
### Step 3: Port the main component (`src/components/`)
...
Template guidance:
Simple plans: use ## Main Phase with ### Step N: sections underneath.
Complex plans: use multiple ## Phase N: sections, each containing ### Step N: steps. Step numbers are global (not per-phase).
The flat ## Step N: format (without phases) also works for backwards compatibility.
Key invariants: one H1 title, one ## Overview, numbered step sections (### Step N: or ## Step N:), and at least one ordering section.
{"plan":"# Implementation Plan: Video-Editor Resize Preview Convergence Cleanup\n\n## Overview\nThe current bug is localized to live resize preview, but the repo state confirms the structural cause described in the brief: preview math is duplicated in TimelineCanvas.tsx, commit math is duplicated in useClipResize.ts and useClipResize.ts, preview reads from both resizePreviewRef and resizeOverrides in TimelineCanvas.tsx, and resize start currently stores initialClientX but no cursor-to-handle offset in TimelineCanvas.tsx.\n\nThe simpler symptom-only fix would be to patch TimelineCanvas with cursor offset and force-sync rendering. That would probably stop the visible lag, but it would keep the same duplicated boundary math that already caused this class of bug. The smallest durable fix is still the brief’s direction: extract the resize math first, then make preview and commit consume the same result, then remove the second preview source of truth.\n\n## Main Phase\n\n### Step 1: Extract the shared resize math contract (src/tools/video-editor/lib/resize-math.ts)\nScope: Small\n1. Create resize-math.ts with pure computeGroupChildBoundaryResize and computeGroupEdgeResize helpers. Keep them data-only: inputs should be initial bounds, direction, proposed boundary or delta, and clamp/min-duration constraints; outputs should be explicit next bounds plus any wasClamped flag the caller needs.\n2. Move the interior-boundary math out of TimelineCanvas.tsx and the mirrored commit math out of useClipResize.ts into those helpers without changing behavior first.\n3. Do the same for group-edge bound calculation now split between TimelineCanvas.tsx and useClipResize.ts. Keep child-preview projection in TimelineCanvas unless the helper API clearly wants to return it too.\n4. Add focused unit coverage in resize-math.test.ts for clamping, left/right direction symmetry, and minimum-duration enforcement before touching the preview store.\n\n### Step 2: Make resize preview track the cursor from the correct anchor (TimelineCanvas.tsx)\nScope: Medium\n1. Extend the resize session types in TimelineCanvas.tsx with a captured cursorOffsetPx and any boundary/group anchor fields needed so pointer movement can be expressed as pixel -> boundary -> time, not clientX - initialClientX.\n2. At pointer-down in TimelineCanvas.tsx, compute the handle’s actual boundary pixel for all three session kinds (clip, group-child-boundary, group-edge) using the row’s current rendered position plus the dragged boundary time, then store cursorOffsetPx = clientX - boundaryPixel.\n3. Rewrite updateResize in TimelineCanvas.tsx so it derives cursorBoundaryPixel = clientX - cursorOffsetPx, converts that through the shared scale helpers, and feeds the result into computeGroupChildBoundaryResize / computeGroupEdgeResize or the clip-resize path.\n4. Preserve existing audio clamping, snap behavior, and onActionResizing semantics while ensuring the previewed boundary is the exact synchronous value later committed.\n\n### Step 3: Collapse preview state to one authoritative source (TimelineCanvas.tsx)\nScope: Medium\n1. Replace the parallel resizePreviewRef + resizeOverrides setup in TimelineCanvas.tsx with a single preview store. The cleanest fit in this repo is a tiny ref-backed store plus useSyncExternalStore, similar to existing usage in useEffectRegistry.ts and lightboxOpenState.ts.\n2. Update SortableRow, positionedShotGroups, getResizeContext, endResize, and override clearing in TimelineCanvas.tsx, TimelineCanvas.tsx, TimelineCanvas.tsx, and TimelineCanvas.tsx to read the same snapshot the pointer handlers write.\n3. Keep the API surface local to TimelineCanvas; this is a structural cleanup, not a broader state-management change.\n4. Grep-verify the cleanup by eliminating resizeOverrides as a second mutable authority and making resizePreviewRef either disappear or become an internal implementation detail behind the single store.\n\n### Step 4: Centralize pixel/time conversion (useTimelineScale + pure scale helper)\nScope: Medium\n1. Introduce useTimelineScale.ts and, if needed for non-React callers, a paired pure helper in src/tools/video-editor/lib so both hooks/components and pure utilities share the same pixelsPerSecond, timeToPixel, and pixelToTime logic.\n2. Replace duplicated conversion code in TimelineCanvas.tsx, TimelineEditor.tsx, TimelineEditor.tsx, TimeRuler.tsx, drop-position.ts, and the drag path in useClipDrag.ts.\n3. Do this after Step 3 so the resize fix lands against one preview model, then fan the shared conversion helper through the rest of the timeline math without mixing concerns.\n\n### Step 5: Add pointer-level regression coverage and run the full video-editor validation stack\nScope: Medium\n1. Extend TimelineCanvas.test.tsx with a stateful harness that mounts the real TimelineCanvas, wires onActionResizeEnd and onShotGroupEdgeResize to real resize commit logic, and re-renders rows after commit.\n2. Add an interior-boundary pointer test on a 3-clip pinned group that asserts the live DOM boundary position follows the expected pixel exactly during pointermove, then pointerup causes no visible jump.\n3. Add the group-edge pointer variant requested in the brief, plus any small helper assertions needed in useClipResize.test.tsx if the extracted math changes commit call sites.\n4. Validation order:\n 1. vitest run --config config/testing/vitest.config.ts src/tools/video-editor/lib/resize-math.test.ts src/tools/video-editor/hooks/useClipResize.test.tsx src/tools/video-editor/components/TimelineEditor/TimelineCanvas.test.tsx\n 2. vitest run --config config/testing/vitest.config.ts src/tools/video-editor/**\n 3. tsc -p tsconfig.app.json --noEmit\n5. Use the existing regression suites for the non-preview flows named in the brief as the guardrail against scope creep: clip drag, grouped drag, track management, external drop, pinned-group sync, final-video switching, persistence, and migration tests should all still pass after the resize cleanup.\n\n## Execution Order\n1. Lock the resize formulas into pure helpers and unit tests before touching pointer behavior.\n2. Fix cursor anchoring and single-source preview inside TimelineCanvas next; that is the user-visible bug.\n3. Centralize scale conversion after preview correctness is restored so the refactor is mechanical, not diagnostic.\n4. Finish with pointer integration coverage and then the full video-editor suite plus typecheck.\n\n## Validation Order\n1. Start with the new resize-math unit tests because they are the cheapest proof that preview and commit are using the same formulas.\n2. Run TimelineCanvas and useClipResize targeted tests after the store/offset changes.\n3. Only then run the broader src/tools/video-editor/** suite and tsc -p tsconfig.app.json --noEmit.","questions":["For item 4, should non-React utilities such as src/tools/video-editor/lib/drop-position.ts share the conversion logic through a pure factory plus useTimelineScale wrapper, or do you only want the hook used in React consumers?", "For computeGroupEdgeResize, should the shared helper own only the outer boundary calculation, with TimelineCanvas continuing to project child preview overrides separately, or should it return the full projected child result too?"],"success_criteria":[{"criterion":"src/tools/video-editor/lib/resize-math.ts exports pure computeGroupChildBoundaryResize and computeGroupEdgeResize helpers, both have direct unit tests, and both are referenced from TimelineCanvas.tsx and useClipResize.ts.", "priority":"must"},{"criterion":"Resize sessions capture cursor-to-handle offset for clip, group-child-boundary, and group-edge, and the new pointer integration test shows the live boundary position matches the expected pixel during drag with no jump on release.", "priority":"must"},{"criterion":"TimelineCanvas no longer maintains resizePreviewRef and resizeOverrides as two separate authoritative resize-preview states; rendered preview and commit read from one source of truth.", "priority":"must"},{"criterion":"A shared timeline-scale abstraction exists and is used across the resize/timeline conversion sites touched by this cleanup, eliminating the duplicated scaleWidth / scale math in the current resize flow.", "priority":"must"},{"criterion":"tsc -p tsconfig.app.json --noEmit completes without video-editor type errors after the cleanup.", "priority":"must"},{"criterion":"The video-editor test suite passes, including the new resize-math unit tests and at least one end-to-end pointer resize test for interior boundary plus the group-edge variant.", "priority":"must"},{"criterion":"The resize subsystem ends up smaller or flatter than before, with less duplicated math and fewer parallel state paths.", "priority":"should"},{"criterion":"The extracted math helpers stay hook-free and side-effect-free, with inputs and outputs expressed only as plain data.", "priority":"should"},{"criterion":"Manual drag verification shows the boundary feels pixel-perfect under the cursor in the original repro path.", "priority":"info"}],"assumptions":["useSyncExternalStore is the preferred way to collapse preview state here because the repo already uses it and it satisfies the single-source requirement without introducing a new library.", "If useTimelineScale cannot be used directly from pure utility files, the implementation will add a small pure scale helper under src/tools/video-editor/lib and keep useTimelineScale as the React wrapper over that shared logic.", "The new pointer integration coverage can live in src/tools/video-editor/components/TimelineEditor/TimelineCanvas.test.tsx with a local stateful harness rather than requiring a broader TimelineEditor mount.", "The listed non-preview regression paths are already covered by existing video-editor suites closely enough that rerunning the full src/tools/video-editor/** tests is the right verification strategy, not adding unrelated new scenario tests."]}
You are revising an implementation plan after critique and gate feedback.
Clean up the structural smells in the video-editor resize/preview architecture that have caused recurring bugs all session. The most recent symptom: when a user drags an interior boundary inside a pinned shot group, the live preview position is subtly wrong during the drag (boundary lags or jitters), but the committed position on release is correct. The root cause is structural — the live preview math and the commit math live in two different code paths that recompute the same answer in different files, the dual state (resizePreviewRef vs resizeOverrides) lets the rendered position drift one frame behind the synchronous source of truth, and the cursor-to-handle offset isnt captured anywhere so the boundary always trails the cursor by some pixels. None of these are bugs — theyre places where the architecture relies on parallel implementations agreeing, with no shared function or test enforcing it.
This is a focused structural cleanup, not a re-architecture. Five items, in priority order by leverage. Each item is testable in isolation.
State of completion BEFORE this megaplan: Coming out of the previous finish projection rollback megaplan, the data shape is fully soft-tag, the resize session model is unified (clip | group-child-boundary | group-edge), useClipDrag/useClipResize/usePinnedGroupSync/useSwitchToFinalVideo/useExternalDrop/useTimelineTrackManagement are all rewritten for the soft-tag model, the deprecated shims are gone, and 210/210 video-editor tests pass. The user has confirmed dragging an interior boundary ends up perfect on release — so the commit path is correct. The bug is purely in the live preview being subtly off from the committed result.
The 5 cleanups:
Extract computeResizeBoundary as a shared pure function (highest leverage). Currently TimelineCanvas.updateResize (the live preview) and useClipResize.onActionResizeEnd (the commit) both compute the new boundary position given a cursor delta — but in different files, with different intermediate variable names, and no shared function. Create src/tools/video-editor/lib/resize-math.ts with computeGroupChildBoundaryResize and computeGroupEdgeResize pure functions. Both live preview and commit call these. Add unit tests for clamping, direction, min-duration.
Capture the cursor-to-handle offset at session start. The resize handle is 8px wide. deltaSeconds = (clientX - initialClientX) / pixelsPerSecond assumes the cursor STARTED ON the boundary. Fix: at pointer-down, compute boundaryPixel = startLeft + (dir === left ? action.start : action.end) * pixelsPerSecond and cursorOffsetPx = clientX - boundaryPixel. Store on session. In updateResize: cursorBoundaryPixel = clientX - cursorOffsetPx; cursorBoundaryTime = (cursorBoundaryPixel - startLeft) / pixelsPerSecond. Apply for all three resize kinds.
Eliminate the dual resizePreviewRef / resizeOverrides state. Use useSyncExternalStore to subscribe to the ref, or a version counter. Eliminate the React state lag. SortableRow renders from the same source the commit reads.
Centralize pixel ↔ time conversion. Extract useTimelineScale({ scale, scaleWidth, startLeft }) returning pixelsPerSecond, pixelsPerSecondRef, timeToPixel, pixelToTime. All consumers use it.
Add an end-to-end resize integration test using @testing-library/react + fireEvent. Render real TimelineCanvas with shot group of 3 clips. Fire pointerdown on middle clip right handle, pointermove, assert DOM boundary position matches expected. Fire pointerup, assert no jump. Variant for group-edge.
Hard requirements: User symptom fixed. No regressions in: drag clip body in pinned group, drag right edge of last clip, drag left edge of first clip, drag interior boundary, cross-track drag grouped clip, switch shot to/from final video, drag shot from gallery, auto-save defers, poll-sync defers, migration loads projection-shape. tsc -p tsconfig.app.json --noEmit clean for src/tools/video-editor/. All video-editor tests pass (210 currently). Shared computeGroupChildBoundaryResize/computeGroupEdgeResize exist with unit tests and both live preview AND commit call them. Cursor offset captured for all 3 resize kinds. Dual state collapsed to one source. useTimelineScale exists and used by all consumers. At least one end-to-end resize test.
Constraints: video-editor tool only, no DB schema changes, follow CLAUDE.md, prefer Edit over Write, dont bundle unrelated cleanups, leave pre-existing non-video-editor failures alone, no new state management libraries, new resize-math functions PURE (no hooks/refs/side effects), e2e test uses @testing-library/react + fireEvent.
Success: boundary tracks cursor pixel-perfectly during drag, tsc clean, all tests pass, new pure functions referenced by both live preview and commit (grep-verifiable), dual state collapsed (grep verifiable), at least one e2e pointer test passes, resize subsystem line count decreases net.
code
Current plan (markdown):
# Implementation Plan: Video-Editor Resize Preview Convergence Cleanup
Overview
The current bug is localized to live resize preview, but the repo state confirms the structural cause described in the brief: preview math is duplicated in TimelineCanvas.tsx, commit math is duplicated in useClipResize.ts and useClipResize.ts, preview reads from both resizePreviewRef and resizeOverrides in TimelineCanvas.tsx, and resize start currently stores initialClientX but no cursor-to-handle offset in TimelineCanvas.tsx.
The simpler symptom-only fix would be to patch TimelineCanvas with cursor offset and force-sync rendering. That would probably stop the visible lag, but it would keep the same duplicated boundary math that already caused this class of bug. The smallest durable fix is still the brief’s direction: extract the resize math first, then make preview and commit consume the same result, then remove the second preview source of truth.
Main Phase
Step 1: Extract the shared resize math contract (src/tools/video-editor/lib/resize-math.ts)
Scope: Small
Create resize-math.ts with pure computeGroupChildBoundaryResize and computeGroupEdgeResize helpers. Keep them data-only: inputs should be initial bounds, direction, proposed boundary or delta, and clamp/min-duration constraints; outputs should be explicit next bounds plus any wasClamped flag the caller needs.
Move the interior-boundary math out of TimelineCanvas.tsx and the mirrored commit math out of useClipResize.ts into those helpers without changing behavior first.
Do the same for group-edge bound calculation now split between TimelineCanvas.tsx and useClipResize.ts. Keep child-preview projection in TimelineCanvas unless the helper API clearly wants to return it too.
Add focused unit coverage in resize-math.test.ts for clamping, left/right direction symmetry, and minimum-duration enforcement before touching the preview store.
Step 2: Make resize preview track the cursor from the correct anchor (TimelineCanvas.tsx)
Scope: Medium
Extend the resize session types in TimelineCanvas.tsx with a captured cursorOffsetPx and any boundary/group anchor fields needed so pointer movement can be expressed as pixel -> boundary -> time, not clientX - initialClientX.
At pointer-down in TimelineCanvas.tsx, compute the handle’s actual boundary pixel for all three session kinds (clip, group-child-boundary, group-edge) using the row’s current rendered position plus the dragged boundary time, then store cursorOffsetPx = clientX - boundaryPixel.
Rewrite updateResize in TimelineCanvas.tsx so it derives cursorBoundaryPixel = clientX - cursorOffsetPx, converts that through the shared scale helpers, and feeds the result into computeGroupChildBoundaryResize / computeGroupEdgeResize or the clip-resize path.
Preserve existing audio clamping, snap behavior, and onActionResizing semantics while ensuring the previewed boundary is the exact synchronous value later committed.
Step 3: Collapse preview state to one authoritative source (TimelineCanvas.tsx)
Scope: Medium
Replace the parallel resizePreviewRef + resizeOverrides setup in TimelineCanvas.tsx with a single preview store. The cleanest fit in this repo is a tiny ref-backed store plus useSyncExternalStore, similar to existing usage in useEffectRegistry.ts and lightboxOpenState.ts.
Update SortableRow, positionedShotGroups, getResizeContext, endResize, and override clearing in TimelineCanvas.tsx, TimelineCanvas.tsx, TimelineCanvas.tsx, and TimelineCanvas.tsx to read the same snapshot the pointer handlers write.
Keep the API surface local to TimelineCanvas; this is a structural cleanup, not a broader state-management change.
Grep-verify the cleanup by eliminating resizeOverrides as a second mutable authority and making resizePreviewRef either disappear or become an internal implementation detail behind the single store.
Step 4: Centralize pixel/time conversion (useTimelineScale + pure scale helper)
Scope: Medium
Introduce useTimelineScale.ts and, if needed for non-React callers, a paired pure helper in src/tools/video-editor/lib so both hooks/components and pure utilities share the same pixelsPerSecond, timeToPixel, and pixelToTime logic.
Replace duplicated conversion code in TimelineCanvas.tsx, TimelineEditor.tsx, TimelineEditor.tsx, TimeRuler.tsx, drop-position.ts, and the drag path in useClipDrag.ts.
Do this after Step 3 so the resize fix lands against one preview model, then fan the shared conversion helper through the rest of the timeline math without mixing concerns.
Step 5: Add pointer-level regression coverage and run the full video-editor validation stack
Scope: Medium
Extend TimelineCanvas.test.tsx with a stateful harness that mounts the real TimelineCanvas, wires onActionResizeEnd and onShotGroupEdgeResize to real resize commit logic, and re-renders rows after commit.
Add an interior-boundary pointer test on a 3-clip pinned group that asserts the live DOM boundary position follows the expected pixel exactly during pointermove, then pointerup causes no visible jump.
Add the group-edge pointer variant requested in the brief, plus any small helper assertions needed in useClipResize.test.tsx if the extracted math changes commit call sites.
Validation order:
vitest run --config config/testing/vitest.config.ts src/tools/video-editor/lib/resize-math.test.ts src/tools/video-editor/hooks/useClipResize.test.tsx src/tools/video-editor/components/TimelineEditor/TimelineCanvas.test.tsx
vitest run --config config/testing/vitest.config.ts src/tools/video-editor/**
tsc -p tsconfig.app.json --noEmit
Use the existing regression suites for the non-preview flows named in the brief as the guardrail against scope creep: clip drag, grouped drag, track management, external drop, pinned-group sync, final-video switching, persistence, and migration tests should all still pass after the resize cleanup.
Execution Order
Lock the resize formulas into pure helpers and unit tests before touching pointer behavior.
Fix cursor anchoring and single-source preview inside TimelineCanvas next; that is the user-visible bug.
Centralize scale conversion after preview correctness is restored so the refactor is mechanical, not diagnostic.
Finish with pointer integration coverage and then the full video-editor suite plus typecheck.
Validation Order
Start with the new resize-math unit tests because they are the cheapest proof that preview and commit are using the same formulas.
Run TimelineCanvas and useClipResize targeted tests after the store/offset changes.
Only then run the broader src/tools/video-editor/** suite and tsc -p tsconfig.app.json --noEmit.
code
Current plan metadata:
{
"version": 1,
"timestamp": "2026-04-08T16:17:58Z",
"hash": "sha256:1f511e302a8ae0a8bdf1c2149ca8c5adccb45fda7caa1d108f41e1ca6f2f89ec",
"questions": [
"For item 4, should non-React utilities such as src/tools/video-editor/lib/drop-position.ts share the conversion logic through a pure factory plus useTimelineScale wrapper, or do you only want the hook used in React consumers?",
"For computeGroupEdgeResize, should the shared helper own only the outer boundary calculation, with TimelineCanvas continuing to project child preview overrides separately, or should it return the full projected child result too?"
],
"success_criteria": [
{
"criterion": "src/tools/video-editor/lib/resize-math.ts exports pure computeGroupChildBoundaryResize and computeGroupEdgeResize helpers, both have direct unit tests, and both are referenced from TimelineCanvas.tsx and useClipResize.ts.",
"priority": "must"
},
{
"criterion": "Resize sessions capture cursor-to-handle offset for clip, group-child-boundary, and group-edge, and the new pointer integration test shows the live boundary position matches the expected pixel during drag with no jump on release.",
"priority": "must"
},
{
"criterion": "TimelineCanvas no longer maintains resizePreviewRef and resizeOverrides as two separate authoritative resize-preview states; rendered preview and commit read from one source of truth.",
"priority": "must"
},
{
"criterion": "A shared timeline-scale abstraction exists and is used across the resize/timeline conversion sites touched by this cleanup, eliminating the duplicated scaleWidth / scale math in the current resize flow.",
"priority": "must"
},
{
"criterion": "tsc -p tsconfig.app.json --noEmit completes without video-editor type errors after the cleanup.",
"priority": "must"
},
{
"criterion": "The video-editor test suite passes, including the new resize-math unit tests and at least one end-to-end pointer resize test for interior boundary plus the group-edge variant.",
"priority": "must"
},
{
"criterion": "The resize subsystem ends up smaller or flatter than before, with less duplicated math and fewer parallel state paths.",
"priority": "should"
},
{
"criterion": "The extracted math helpers stay hook-free and side-effect-free, with inputs and outputs expressed only as plain data.",
"priority": "should"
},
{
"criterion": "Manual drag verification shows the boundary feels pixel-perfect under the cursor in the original repro path.",
"priority": "info"
}
],
"assumptions": [
"useSyncExternalStore is the preferred way to collapse preview state here because the repo already uses it and it satisfies the single-source requirement without introducing a new library.",
"If useTimelineScale cannot be used directly from pure utility files, the implementation will add a small pure scale helper under and keep as the React wrapper over that shared logic.",
"The new pointer integration coverage can live in with a local stateful harness rather than requiring a broader mount.",
"The listed non-preview regression paths are already covered by existing video-editor suites closely enough that rerunning the full tests is the right verification strategy, not adding unrelated new scenario tests."
],
"structure_warnings": []
}
code
Gate summary:
{
"recommendation": "ITERATE",
"rationale": "Light robustness: single revision pass to incorporate critique feedback.",
"signals_assessment": "",
"warnings": [],
"settled_decisions": []
}
code
Open significant flags:
[
{
"id": "FLAG-001",
"severity": "significant",
"status": "open",
"concern": "Resize preview parity: computeGroupEdgeResize is not a straight shared extraction today. The live preview path in TimelineCanvas rescales every child in the pinned group, while the commit path in useClipResize.startGroupEdgeResize() only mutates the first or last clip. The plan says to share group-edge math but also says to keep child preview projection in TimelineCanvas, which would leave preview and commit on different semantics and makes the new helper contract ambiguous.",
"evidence": "src/tools/video-editor/components/TimelineEditor/TimelineCanvas.tsx:681-735 computes group-edge preview by scaling every child override across the whole group; src/tools/video-editor/hooks/useClipResize.ts:420-479 commits group-edge resize by updating only targetClipId; current tests lock that behavior in src/tools/video-editor/hooks/useClipResize.test.tsx:334-387 ('mutates last clip only' / 'mutates first clip only')."
}
]
code
Requirements:
- Before addressing individual flags, check: does any flag suggest the plan is targeting the wrong code or the wrong root cause? If so, consider whether the plan needs a new approach rather than adjustments. Explain your reasoning.
- Update the plan to address the significant issues.
- Keep the plan readable and executable.
- Return flags_addressed with the exact flag IDs you addressed.
- Preserve or improve success criteria quality. Each criterion must have a `priority` of `must`, `should`, or `info`. Promote or demote priorities if critique feedback reveals a criterion was over- or under-weighted.
- Verify that the plan remains aligned with the user's original intent, not just internal plan quality.
- Remove unjustified scope growth. If critique raised scope creep, narrow the plan back to the original idea unless the broader work is strictly required.
- Maintain the structural template: H1 title, ## Overview, phase sections with numbered step sections, ## Execution Order or ## Validation Order.
Plan template — simple format (adapt to the actual repo and scope):
md
# Implementation Plan: [Title]
## Overview
Summarize the goal, current repository shape, and the constraints that matter.
## Main Phase
### Step 1: Audit the current behavior (`megaplan/prompts.py`)
**Scope:** Small
1. **Inspect** the current implementation and call out the exact insertion points (`megaplan/prompts.py:29`).
### Step 2: Add the first change (`megaplan/evaluation.py`)
**Scope:** Medium
1. **Implement** the smallest viable change with exact file references (`megaplan/evaluation.py:1`).
2. **Capture** any tricky behavior with a short example.
```python
issues = validate_plan_structure(plan_text)
```
### Step 3: Wire downstream behavior (`megaplan/handlers.py`, `megaplan/workers.py`)
**Scope:** Medium
1. **Update** the runtime flow in the touched files (`megaplan/handlers.py:400`, `megaplan/workers.py:199`).
### Step 4: Prove the change (`tests/test_evaluation.py`, `tests/test_megaplan.py`)
**Scope:** Small
1. **Run** the cheapest targeted checks first (`tests/test_evaluation.py:1`).
2. **Finish** with broader verification once the wiring is in place (`tests/test_megaplan.py:1`).
## Execution Order
1. Update prompts and mocks before enforcing stricter validation.
2. Land higher-risk wiring after the validator and tests are ready.
## Validation Order
1. Start with focused unit tests.
2. Run the broader suite after the flow changes are in place.
For complex plans, use multiple phases:
md
## Phase 1: Foundation — Dependencies, DB, Types
### Step 1: Install dependencies (`package.json`)
...
### Step 2: Create database migration (`supabase/migrations/`)
...
## Phase 2: Core Integration
### Step 3: Port the main component (`src/components/`)
...
Template guidance:
Simple plans: use ## Main Phase with ### Step N: sections underneath.
Complex plans: use multiple ## Phase N: sections, each containing ### Step N: steps. Step numbers are global (not per-phase).
The flat ## Step N: format (without phases) also works for backwards compatibility.
Key invariants: one H1 title, one ## Overview, numbered step sections (### Step N: or ## Step N:), and at least one ordering section.
{"plan":"# Implementation Plan: Video-Editor Resize Preview Convergence Cleanup\n\n## Overview\nFLAG-001 does not suggest the plan is aimed at the wrong subsystem or the wrong root cause. It confirms the same root cause more sharply: preview and commit semantics are still split, and group-edge preview is currently another parallel implementation that disagrees with the committed behavior. The plan should not broaden into a re-architecture, but it does need one concrete correction: treat the existing group-edge commit semantics as the source of truth and align preview to that behavior instead of leaving the helper contract ambiguous.\n\nRepo inspection still points to the same three structural problems in the resize flow: duplicate boundary math in TimelineCanvas.tsx and useClipResize.ts, dual preview authority in TimelineCanvas.tsx, and missing cursor-offset capture in TimelineCanvas.tsx. The only material revision is that computeGroupEdgeResize must model the already-tested commit behavior from useClipResize.ts and useClipResize.test.tsx: resizing a group edge mutates only the outer clip, not every child.\n\n## Main Phase\n\n### Step 1: Extract shared resize math with explicit commit-parity contracts (src/tools/video-editor/lib/resize-math.ts)\nScope: Small\n1. Create resize-math.ts with pure computeGroupChildBoundaryResize and computeGroupEdgeResize helpers. Define computeGroupChildBoundaryResize around a proposed shared boundary time and computeGroupEdgeResize around the outer clip’s initial bounds plus direction, delta, and minimum-duration/clamp inputs.\n2. Make the group-edge contract explicit in the helper and tests: it returns the dragged outer clip’s next { start, end } and clamp metadata only. It does not return proportional child projections, because that is not what commit currently does.\n3. Replace duplicated interior-boundary math in TimelineCanvas.tsx and useClipResize.ts with computeGroupChildBoundaryResize.\n4. Replace duplicated group-edge bound math in TimelineCanvas.tsx and useClipResize.ts with computeGroupEdgeResize, preserving the existing "mutates outer clip only" semantics already locked by tests.\n5. Add focused unit coverage in resize-math.test.ts for clamping, direction symmetry, minimum duration, and explicit group-edge parity with current commit behavior.\n\n### Step 2: Fix pointer anchoring and remove semantic drift in live preview (TimelineCanvas.tsx)\nScope: Medium\n1. Extend the resize session types in TimelineCanvas.tsx with cursorOffsetPx and the exact boundary/clip anchor fields needed for each resize kind.\n2. Capture cursorOffsetPx at pointer-down in TimelineCanvas.tsx for all three session kinds using the real boundary pixel: startLeft + boundaryTime * pixelsPerSecond.\n3. Rewrite updateResize in TimelineCanvas.tsx so it computes cursorBoundaryPixel = clientX - cursorOffsetPx, converts that through shared scale helpers, and feeds the result into the extracted resize math.\n4. Remove the current group-edge proportional child scaling in TimelineCanvas.tsx. During a group-edge drag, preview only the first or last child’s override exactly as commit will, leaving interior children unchanged unless they are the dragged edge clip.\n5. Keep snapping and audio clamp behavior intact, but ensure previewed group-edge bounds now match commit semantics instead of inventing a separate proportional-preview model.\n\n### Step 3: Collapse preview state to one source and derive group overlays from previewed clips (TimelineCanvas.tsx)\nScope: Medium\n1. Replace the parallel resizePreviewRef + resizeOverrides pattern in TimelineCanvas.tsx with one preview store, using useSyncExternalStore and a tiny local ref-backed publisher.\n2. Update SortableRow, getResizeContext, endResize, and override clearing in TimelineCanvas.tsx, TimelineCanvas.tsx, and TimelineCanvas.tsx so render and commit read the same snapshot.\n3. Stop storing a synthetic group-edge preview override keyed by shotId:rowId in TimelineCanvas.tsx. Instead, compute positionedShotGroups in TimelineCanvas.tsx from the previewed child actions, so the overlay reflects the same clip overrides the row renders.\n4. This keeps group-edge preview and commit aligned while also making the dual-state cleanup smaller: one preview store, no separate group-level preview semantics.\n\n### Step 4: Centralize pixel/time conversion without widening scope (useTimelineScale)\nScope: Medium\n1. Add useTimelineScale.ts plus a tiny pure scale helper under src/tools/video-editor/lib if needed so non-React code can share the same conversion logic.\n2. Replace the duplicated conversion code in TimelineCanvas.tsx, TimelineEditor.tsx, TimelineEditor.tsx, TimeRuler.tsx, drop-position.ts, and the drag path in useClipDrag.ts.\n3. Keep this step mechanical. It should not introduce new resize semantics; it exists to remove duplicated conversions now that the resize path has one math contract and one preview store.\n\n### Step 5: Add regression coverage that proves semantic parity (TimelineCanvas.test.tsx, useClipResize.test.tsx)\nScope: Medium\n1. Add resize-math unit tests first, then extend TimelineCanvas.test.tsx with a stateful harness that mounts the real TimelineCanvas, commits through real resize logic, and re-renders rows after pointer-up.\n2. Add the required interior-boundary pointer test on a 3-clip pinned group: pointerdown on the middle clip’s right handle, pointermove, assert the live DOM boundary matches the expected pixel exactly, then pointerup and assert no jump.\n3. Add the group-edge variant, but make the assertion match actual commit semantics: the dragged outer clip boundary moves, the committed position does not jump, and non-edge children do not get proportionally rescaled during preview.\n4. Keep the existing useClipResize group-edge tests in useClipResize.test.tsx and useClipResize.test.tsx as regression proof that commit still mutates only the outer clip.\n5. Validation order:\n 1. vitest run --config config/testing/vitest.config.ts src/tools/video-editor/lib/resize-math.test.ts src/tools/video-editor/hooks/useClipResize.test.tsx src/tools/video-editor/components/TimelineEditor/TimelineCanvas.test.tsx\n 2. vitest run --config config/testing/vitest.config.ts src/tools/video-editor/**\n 3. tsc -p tsconfig.app.json --noEmit\n\n## Execution Order\n1. Lock the helper contracts and unit tests first, especially the explicit group-edge parity decision.\n2. Fix pointer anchoring and remove proportional group-edge preview next, because that is the remaining preview/commit semantic split.\n3. Collapse preview state after the preview math is correct so render and commit read one source.\n4. Fan out the shared scale helper only after the resize behavior is stable.\n5. Finish with pointer integration coverage, then the full video-editor suite and typecheck.\n\n## Validation Order\n1. Start with resize-math unit tests to prove the extracted contracts match current commit behavior.\n2. Run targeted TimelineCanvas and useClipResize tests after preview/store changes.\n3. Run the broader src/tools/video-editor/** suite.\n4. Finish with tsc -p tsconfig.app.json --noEmit.","questions":[],"success_criteria":[{"criterion":"src/tools/video-editor/lib/resize-math.ts exports pure computeGroupChildBoundaryResize and computeGroupEdgeResize helpers, both have direct unit tests, and both are referenced from TimelineCanvas.tsx and useClipResize.ts.", "priority":"must"},{"criterion":"Resize sessions capture cursor-to-handle offset for clip, group-child-boundary, and group-edge, and the interior-boundary pointer integration test shows the live boundary position matches the expected pixel during drag with no jump on release.", "priority":"must"},{"criterion":"Group-edge preview semantics match existing commit semantics: dragging a pinned group edge previews and commits only the outer clip boundary change, and non-edge children are not proportionally rescaled during preview.", "priority":"must"},{"criterion":"TimelineCanvas no longer maintains resizePreviewRef and resizeOverrides as two separate authoritative resize-preview states; rendered preview and commit read from one source of truth.", "priority":"must"},{"criterion":"A shared timeline-scale abstraction exists and is used across the resize/timeline conversion sites touched by this cleanup, eliminating duplicated scaleWidth / scale math in the current resize flow.", "priority":"must"},{"criterion":"tsc -p tsconfig.app.json --noEmit completes without video-editor type errors after the cleanup.", "priority":"must"},{"criterion":"The video-editor test suite passes, including the new resize-math unit tests, the interior-boundary pointer test, and the group-edge pointer variant.", "priority":"must"},{"criterion":"The resize subsystem ends up smaller or flatter than before, with less duplicated math and fewer parallel state paths.", "priority":"should"},{"criterion":"The extracted math helpers stay hook-free and side-effect-free, with inputs and outputs expressed only as plain data.", "priority":"should"},{"criterion":"Manual drag verification shows the original interior-boundary repro now tracks the cursor pixel-perfectly.", "priority":"info"}],"assumptions":["The existing useClipResize group-edge tests are the correct behavioral source of truth, so preview must be aligned to the current "outer clip only" commit semantics rather than changing commit behavior.", "useSyncExternalStore is the preferred way to collapse preview state here because the repo already uses it and it satisfies the single-source requirement without introducing a new library.", "If useTimelineScale cannot be used directly from pure utility files, the implementation will add a small pure scale helper under src/tools/video-editor/lib and keep useTimelineScale as the React wrapper over that shared logic.", "The new pointer integration coverage can live in src/tools/video-editor/components/TimelineEditor/TimelineCanvas.test.tsx with a local stateful harness rather than requiring a broader TimelineEditor mount.", "The listed non-preview regression paths are already covered by existing video-editor suites closely enough that rerunning the full src/tools/video-editor/** tests is the right verification strategy, not adding unrelated new scenario tests."],"flags_addressed":["FLAG-001"]}