You are already running inside the megaplan harness for this step. Do the requested planning/review/execution work directly. Do NOT invoke the megaplan CLI, do NOT read or activate the megaplan skill, do NOT start nested megaplan plans, and do NOT recurse into another planning harness. Treat mentions of megaplan in the repository or environment as implementation context only.
WRITE ACCESS CONTRACT: You are running with auto-approved writes inside a writable workspace. Treat the working directory as fully writable. Do NOT preemptively skip or block tasks on permission, sandbox, or read-only grounds. Attempt every required edit; only report failure AFTER a real OS-level rejection from a specific shell command. Do not infer 'read-only' from absence of activity; absence is not denial. If a single shell command unexpectedly fails, retry with a different invocation before concluding the environment is restricted.
You are creating an implementation plan for the following idea.
code
Idea:
Clean up the Reigh video editor Sequence Creator implementation after the recent animation-sequence changes. Focus on making the code excellent without broad churn: multi-selected replacement should delete all selected visual clips and insert one sequence, Allowed Assets should use the timeline chat attachment strip with removable X controls, edit-vs-generate workflow should be coherent, image-jump modes should be visibly distinct and schema/prompt aligned, tests should cover the behavior, TypeScript should pass. Avoid touching unrelated .megaplan schema files.
code
Assistant
{"plan":"I’ll inspect the Sequence Creator/editor touch points and nearby tests, avoiding .megaplan and unrelated docs, then turn that into a concrete implementation plan with assumptions and validation gates.","questions":[],"success_criteria":[],"assumptions":[]}
Assistant
{"plan":"I found the Sequence Creator surface, the client draft/materialization utilities, sequence metadata/validation, and the matching Supabase AI generation prompt/tests. I’m narrowing on the actual insertion/replacement and attachment-strip wiring so the plan can name concrete files rather than broad areas.","questions":[],"success_criteria":[],"assumptions":[]}
Assistant
User
Assistant
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.
- Stay focused on the requested idea. If repo exploration surfaces unrelated issues or docs, ignore them and return to the task.
- Prefer source code, tests, and directly relevant config files. Avoid `.megaplan/`, prior plan artifacts, and unrelated `docs/` or ops/deployment material unless the task explicitly depends on them.
- Stop exploring once you have enough evidence to name the concrete touch points and validation path. Do not keep browsing after you can write the plan.
- 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").
- Each success criterion should include a `requires` field listing the capabilities needed for verification. Valid capability strings: `run_shell`, `read_files`, `run_tests`, `parse_diff`, `read_build_output`, `run_linter` (container), `drive_browser`, `inspect_runtime_ui`, `observe_runtime_logs`, `subjective_judgment`, `verify_physical_device` (human). `must` criteria MUST have non-empty `requires`. Example: `{"criterion": "All tests pass", "priority": "must", "requires": ["run_tests"]}`.
- 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: Sequence Creator Cleanup\n\n## Overview\nThe relevant implementation is already concentrated in the video editor Sequence Creator path, not broad editor infrastructure. The main touch points are src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.tsx, src/tools/video-editor/lib/sequence-drafts.ts, sequence schema/metadata under src/tools/video-editor/sequences/, the local Image Jump Remotion component, and the supabase/functions/ai-generate-sequence/ prompt/validation tests. Existing dirty .megaplan/schemas/* changes must be ignored.\n\nThe safest path is to keep this as a focused cleanup: make replacement semantics explicit in the sequence-draft mutation helper, reuse the existing chat attachment strip for Allowed Assets, tighten generate/edit state transitions, align image-jump schema/prompt/component modes, and prove each behavior with targeted tests before running typecheck/build-level validation.\n\n## Main Phase\n\n### Step 1: Lock Down Replacement Semantics (src/tools/video-editor/lib/sequence-drafts.ts)\nScope: Medium\n1. Update BuildReplaceSequenceDraftOptions to accept selectedClipIds in addition to selectedClipId.\n2. Normalize the selected IDs into a deduped ordered set that includes the primary selection.\n3. Validate that every selected target exists and belongs to a visual track before mutating anything.\n4. Delete all selected visual clips from rows/meta/clip order and insert one sequence clip.\n5. Place the new sequence at the earliest selected start time and on the primary selected clip’s visual track, unless later review decides the earliest clip’s track is more intuitive.\n6. Preserve existing overlap resolution and returned selection behavior.\n\n### Step 2: Wire Multi-Selection Replacement Through the Panel (src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.tsx)\nScope: Small\n1. Read selectedClipIds from useTimelineEditorData().\n2. Pass both selectedClipId and selectedClipIds into the replace probe and handleReplace mutation path.\n3. Keep the existing replace button disabled for missing selections, invalid drafts, and any selected non-visual target.\n4. Update the button copy or title only if needed to make multi-replacement clear without adding clutter.\n\n### Step 3: Use the Timeline Chat Attachment Strip for Allowed Assets (SequenceCreatorPanel.tsx, AgentChatMessage.tsx if needed)\nScope: Medium\n1. Render Allowed Assets with AgentChatAttachmentStrip using the same preview/grouping shape as timeline chat attachments.\n2. Add removable X controls for individual assets and full-shot groups via onRemoveAttachment and onRemoveShot.\n3. Ensure removal updates the actual attachment/selection source that backs the strip. If the existing composer removal API only affects chat attachments, add the smallest appropriate deselect/removal path for selected timeline clips instead of making the X visually remove nothing.\n4. Keep asset filtering registry-backed: no placeholders, missing registry entries, raw/stale URLs, or duplicate asset keys.\n\n### Step 4: Make Generate vs Edit Coherent (SequenceCreatorPanel.tsx, SequenceCreatorPanel.test.tsx)\nScope: Medium\n1. Treat Generate as creating a new draft group from the current prompt and clearing stale selected-draft UI state.\n2. Treat Edit as modifying the selected draft group using mode: 'edit' plus edit_context containing the original prompt, selected draft index, source draft, and validated source draft.\n3. After a successful generation, select the new group and move into Edit mode so follow-up edits are obvious.\n4. On failed edit regeneration, avoid silently deleting the prior valid draft unless the current implementation intentionally replaces the group only after valid drafts return.\n5. Keep prompt validation and generation notes specific enough to distinguish “no drafts returned” from “schema rejected drafts.”\n\n### Step 5: Align Image-Jump Modes Across Metadata, Validation, Prompt, and Component\nScope: Medium\n1. Confirm image-jump metadata exposes imageAssetKeys and a mode field whose allowed values are exactly jump, snap, gallery, pulse, and shuffle.\n2. Add validation for enum-like string params where metadata declares a finite option set, or add a minimal image-jump-specific mode validator if that is the existing style.\n3. Update supabase/functions/ai-generate-sequence/templates.ts so the model is explicitly told when each mode should be used and to vary modes based on user language.\n4. Make ImageJumpSequence.tsx render visibly distinct motion/layout for each mode, not just small transform differences.\n5. Ensure schema-facing params remain asset keys while Remotion-facing params receive materialized image URLs through materialize.ts.\n\n### Step 6: Add Focused Tests\nScope: Medium\n1. Extend src/tools/video-editor/lib/sequence-drafts.test.ts for replacing multiple selected visual clips with one sequence, including cross-track selections and a non-visual rejection case.\n2. Extend SequenceCreatorPanel.test.tsx for passing selectedClipIds into replacement, rendering Allowed Assets through removable chat attachment previews, and edit-vs-generate request bodies/state transitions.\n3. Extend src/tools/video-editor/sequences/validation.test.ts, metadata.test.ts, and/or materialize.test.ts for image-jump mode validity and asset-key-to-URL materialization.\n4. Extend supabase/functions/ai-generate-sequence/index.test.ts or template tests for mode guidance and text-free image-jump drafts.\n\n### Step 7: Validate Cheap-to-Broad\nScope: Small\n1. Run targeted tests first:\n bash\n npx vitest run --config config/testing/vitest.config.ts src/tools/video-editor/lib/sequence-drafts.test.ts src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.test.tsx src/tools/video-editor/sequences/validation.test.ts src/tools/video-editor/sequences/materialize.test.ts\n \n2. Run the edge sequence tests:\n bash\n npx vitest run --config config/testing/vitest.edge.config.ts supabase/functions/ai-generate-sequence/index.test.ts\n \n3. Run TypeScript/build validation:\n bash\n npm run build\n \n4. If build is too slow for iteration, use tsc --noEmit first, then finish with npm run build.\n\n## Execution Order\n1. Start with sequence-drafts.ts and its tests because replacement semantics are pure and cheap to verify.\n2. Wire the panel to the helper once the helper contract is proven.\n3. Fix Allowed Assets removal next because it is UI-facing but localized.\n4. Align image-jump metadata/validation/prompt/component together so schema and generation behavior cannot drift.\n5. Finish with targeted tests, edge tests, and TypeScript/build.\n\n## Validation Order\n1. Run focused client tests after each client behavior group.\n2. Run the edge AI sequence tests after prompt/schema updates.\n3. Run npm run build as the final hard gate for TypeScript and production bundling.\n4. Inspect the final diff to confirm no unrelated .megaplan/ schema files were touched by the implementation.","questions":["When an Allowed Assets item came from the current timeline selection rather than the chat attachment set, should clicking X deselect/remove that timeline selection, or should only attached chat chips be removable while selected clips remain controlled by timeline selection?","For multi-selected replacement across tracks, should the inserted sequence be placed on the primary selected clip’s track or on the track containing the earliest selected clip? I assume primary selected track for continuity with single-clip replacement."],"success_criteria":[{"criterion":"Replacing with multiple selected visual clips deletes every selected visual clip and inserts exactly one trusted sequence clip.","priority":"must","requires":["run_tests","read_files"]},{"criterion":"Replacement rejects missing selections and any selection containing an audio/non-visual clip before applying a mutation.","priority":"must","requires":["run_tests","read_files"]},{"criterion":"SequenceCreatorPanel passes the full selected clip set into replace probing and replacement execution.","priority":"must","requires":["run_tests","parse_diff"]},{"criterion":"Allowed Assets render through the timeline chat attachment strip and visible X controls remove the backed asset source rather than only changing local display.","priority":"must","requires":["run_tests","parse_diff","subjective_judgment"]},{"criterion":"Generate creates a new draft group, Edit updates the selected group with edit_context, and stale drafts do not remain visible after a successful new generation.","priority":"must","requires":["run_tests","read_files"]},{"criterion":"Image-jump mode values are aligned across metadata, validation, AI prompt guidance, and the Remotion component.","priority":"must","requires":["run_tests","read_files","parse_diff"]},{"criterion":"Focused Sequence Creator, sequence helper, sequence validation/materialization, and ai-generate-sequence tests pass.","priority":"must","requires":["run_tests"]},{"criterion":"TypeScript production validation passes via npm run build or an equivalent tsc plus build check.","priority":"must","requires":["run_shell","read_build_output"]},{"criterion":"Implementation does not modify unrelated .megaplan/ schema files.","priority":"must","requires":["parse_diff"]},{"criterion":"Changes stay localized to Sequence Creator, sequence draft helpers, image-jump sequence metadata/component, ai-generate-sequence prompt/schema, and directly related tests.","priority":"should","requires":["parse_diff","subjective_judgment"]},{"criterion":"The UI copy remains concise and does not add explanatory in-app text beyond necessary labels, titles, and errors.","priority":"should","requires":["read_files","subjective_judgment"]},{"criterion":"Manual smoke test: open Sequence Creator, generate image-jump from selected/attached images, remove an allowed asset, edit the draft, and replace a multi-selection in the timeline.","priority":"info","requires":["inspect_runtime_ui"]}],"assumptions":["The existing working-tree changes in src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.tsx, src/tools/video-editor/lib/sequence-drafts.ts, and related tests are in-scope partial work and should be reviewed/refined rather than reverted.","Dirty .megaplan/schemas/* files are unrelated to this task and must be left untouched.","The Sequence Creator should continue using trusted structured sequence drafts, not arbitrary generated JSX/code.","Selected/attached asset keys should remain the schema boundary; raw URLs should only appear after client-side materialization for preview/rendering.","The final replacement sequence should use the primary selected clip’s visual track and the earliest selected start time unless clarified otherwise."]}
You are already running inside the megaplan harness for this step. Do the requested planning/review/execution work directly. Do NOT invoke the megaplan CLI, do NOT read or activate the megaplan skill, do NOT start nested megaplan plans, and do NOT recurse into another planning harness. Treat mentions of megaplan in the repository or environment as implementation context only.
WRITE ACCESS CONTRACT: You are running with auto-approved writes inside a writable workspace. Treat the working directory as fully writable. Do NOT preemptively skip or block tasks on permission, sandbox, or read-only grounds. Attempt every required edit; only report failure AFTER a real OS-level rejection from a specific shell command. Do not infer 'read-only' from absence of activity; absence is not denial. If a single shell command unexpectedly fails, retry with a different invocation before concluding the environment is restricted.
You are revising an implementation plan after critique and gate feedback.
Clean up the Reigh video editor Sequence Creator implementation after the recent animation-sequence changes. Focus on making the code excellent without broad churn: multi-selected replacement should delete all selected visual clips and insert one sequence, Allowed Assets should use the timeline chat attachment strip with removable X controls, edit-vs-generate workflow should be coherent, image-jump modes should be visibly distinct and schema/prompt aligned, tests should cover the behavior, TypeScript should pass. Avoid touching unrelated .megaplan schema files.
code
Current plan (markdown):
# Implementation Plan: Sequence Creator Cleanup
Overview
The relevant implementation is already concentrated in the video editor Sequence Creator path, not broad editor infrastructure. The main touch points are src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.tsx, src/tools/video-editor/lib/sequence-drafts.ts, sequence schema/metadata under src/tools/video-editor/sequences/, the local Image Jump Remotion component, and the supabase/functions/ai-generate-sequence/ prompt/validation tests. Existing dirty .megaplan/schemas/* changes must be ignored.
The safest path is to keep this as a focused cleanup: make replacement semantics explicit in the sequence-draft mutation helper, reuse the existing chat attachment strip for Allowed Assets, tighten generate/edit state transitions, align image-jump schema/prompt/component modes, and prove each behavior with targeted tests before running typecheck/build-level validation.
Main Phase
Step 1: Lock Down Replacement Semantics (src/tools/video-editor/lib/sequence-drafts.ts)
Scope: Medium
Update BuildReplaceSequenceDraftOptions to accept selectedClipIds in addition to selectedClipId.
Normalize the selected IDs into a deduped ordered set that includes the primary selection.
Validate that every selected target exists and belongs to a visual track before mutating anything.
Delete all selected visual clips from rows/meta/clip order and insert one sequence clip.
Place the new sequence at the earliest selected start time and on the primary selected clip’s visual track, unless later review decides the earliest clip’s track is more intuitive.
Preserve existing overlap resolution and returned selection behavior.
Step 2: Wire Multi-Selection Replacement Through the Panel (src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.tsx)
Scope: Small
Read selectedClipIds from useTimelineEditorData().
Pass both selectedClipId and selectedClipIds into the replace probe and handleReplace mutation path.
Keep the existing replace button disabled for missing selections, invalid drafts, and any selected non-visual target.
Update the button copy or title only if needed to make multi-replacement clear without adding clutter.
Step 3: Use the Timeline Chat Attachment Strip for Allowed Assets (SequenceCreatorPanel.tsx, AgentChatMessage.tsx if needed)
Scope: Medium
Render Allowed Assets with AgentChatAttachmentStrip using the same preview/grouping shape as timeline chat attachments.
Add removable X controls for individual assets and full-shot groups via onRemoveAttachment and onRemoveShot.
Ensure removal updates the actual attachment/selection source that backs the strip. If the existing composer removal API only affects chat attachments, add the smallest appropriate deselect/removal path for selected timeline clips instead of making the X visually remove nothing.
Keep asset filtering registry-backed: no placeholders, missing registry entries, raw/stale URLs, or duplicate asset keys.
Step 4: Make Generate vs Edit Coherent (SequenceCreatorPanel.tsx, SequenceCreatorPanel.test.tsx)
Scope: Medium
Treat Generate as creating a new draft group from the current prompt and clearing stale selected-draft UI state.
Treat Edit as modifying the selected draft group using mode: 'edit' plus edit_context containing the original prompt, selected draft index, source draft, and validated source draft.
After a successful generation, select the new group and move into Edit mode so follow-up edits are obvious.
On failed edit regeneration, avoid silently deleting the prior valid draft unless the current implementation intentionally replaces the group only after valid drafts return.
Keep prompt validation and generation notes specific enough to distinguish “no drafts returned” from “schema rejected drafts.”
Step 5: Align Image-Jump Modes Across Metadata, Validation, Prompt, and Component
Scope: Medium
Confirm image-jump metadata exposes imageAssetKeys and a mode field whose allowed values are exactly jump, snap, gallery, pulse, and shuffle.
Add validation for enum-like string params where metadata declares a finite option set, or add a minimal image-jump-specific mode validator if that is the existing style.
Update supabase/functions/ai-generate-sequence/templates.ts so the model is explicitly told when each mode should be used and to vary modes based on user language.
Make ImageJumpSequence.tsx render visibly distinct motion/layout for each mode, not just small transform differences.
Ensure schema-facing params remain asset keys while Remotion-facing params receive materialized image URLs through materialize.ts.
Step 6: Add Focused Tests
Scope: Medium
Extend src/tools/video-editor/lib/sequence-drafts.test.ts for replacing multiple selected visual clips with one sequence, including cross-track selections and a non-visual rejection case.
Extend SequenceCreatorPanel.test.tsx for passing selectedClipIds into replacement, rendering Allowed Assets through removable chat attachment previews, and edit-vs-generate request bodies/state transitions.
Extend src/tools/video-editor/sequences/validation.test.ts, metadata.test.ts, and/or materialize.test.ts for image-jump mode validity and asset-key-to-URL materialization.
Extend supabase/functions/ai-generate-sequence/index.test.ts or template tests for mode guidance and text-free image-jump drafts.
Step 7: Validate Cheap-to-Broad
Scope: Small
Run targeted tests first:
bash
npx vitest run --config config/testing/vitest.config.ts src/tools/video-editor/lib/sequence-drafts.test.ts src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.test.tsx src/tools/video-editor/sequences/validation.test.ts src/tools/video-editor/sequences/materialize.test.ts
Run the edge sequence tests:
bash
npx vitest run --config config/testing/vitest.edge.config.ts supabase/functions/ai-generate-sequence/index.test.ts
Run TypeScript/build validation:
bash
npm run build
If build is too slow for iteration, use tsc --noEmit first, then finish with npm run build.
Execution Order
Start with sequence-drafts.ts and its tests because replacement semantics are pure and cheap to verify.
Wire the panel to the helper once the helper contract is proven.
Fix Allowed Assets removal next because it is UI-facing but localized.
Align image-jump metadata/validation/prompt/component together so schema and generation behavior cannot drift.
Finish with targeted tests, edge tests, and TypeScript/build.
Validation Order
Run focused client tests after each client behavior group.
Run the edge AI sequence tests after prompt/schema updates.
Run npm run build as the final hard gate for TypeScript and production bundling.
Inspect the final diff to confirm no unrelated .megaplan/ schema files were touched by the implementation.
code
Current plan metadata:
{
"version": 1,
"timestamp": "2026-05-01T21:03:15Z",
"hash": "sha256:ea0c262d840336ad5a3aa299eff336535593d8cb3fcd66c7bed1b5cc4d8cfab7",
"questions": [
"When an Allowed Assets item came from the current timeline selection rather than the chat attachment set, should clicking X deselect/remove that timeline selection, or should only attached chat chips be removable while selected clips remain controlled by timeline selection?",
"For multi-selected replacement across tracks, should the inserted sequence be placed on the primary selected clip\u2019s track or on the track containing the earliest selected clip? I assume primary selected track for continuity with single-clip replacement."
],
"success_criteria": [
{
"criterion": "Replacing with multiple selected visual clips deletes every selected visual clip and inserts exactly one trusted sequence clip.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "Replacement rejects missing selections and any selection containing an audio/non-visual clip before applying a mutation.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "SequenceCreatorPanel passes the full selected clip set into replace probing and replacement execution.",
"priority": "must",
"requires": [
"run_tests",
"parse_diff"
]
},
{
"criterion": "Allowed Assets render through the timeline chat attachment strip and visible X controls remove the backed asset source rather than only changing local display.",
"priority": "must",
"requires": [
"run_tests",
"parse_diff",
"subjective_judgment"
]
},
{
"criterion": "Generate creates a new draft group, Edit updates the selected group with edit_context, and stale drafts do not remain visible after a successful new generation.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "Image-jump mode values are aligned across metadata, validation, AI prompt guidance, and the Remotion component.",
"priority": "must",
"requires": [
"run_tests",
"read_files",
"parse_diff"
]
},
{
"criterion": "Focused Sequence Creator, sequence helper, sequence validation/materialization, and ai-generate-sequence tests pass.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "TypeScript production validation passes via npm run build or an equivalent tsc plus build check.",
"priority": "must",
"requires": [
"run_shell",
"read_build_output"
]
},
{
"criterion": "Implementation does not modify unrelated .megaplan/ schema files.",
"priority": "must",
"requires": [
"parse_diff"
]
},
{
"criterion": "Changes stay localized to Sequence Creator, sequence draft helpers, image-jump sequence metadata/component, ai-generate-sequence prompt/schema, and directly related tests.",
"priority": "should",
"requires": [
"parse_diff",
"subjective_judgment"
]
},
{
"criterion": "The UI copy remains concise and does not add explanatory in-app text beyond necessary labels, titles, and errors.",
"priority": "should",
"requires": [
"read_files",
"subjective_judgment"
]
},
{
"criterion": "Manual smoke test: open Sequence Creator, generate image-jump from selected/attached images, remove an allowed asset, edit the draft, and replace a multi-selection in the timeline.",
"priority": "info",
"requires": [
"inspect_runtime_ui"
]
}
],
"assumptions": [
"The existing working-tree changes in , , and related tests are in-scope partial work and should be reviewed/refined rather than reverted.",
"Dirty files are unrelated to this task and must be left untouched.",
"The Sequence Creator should continue using trusted structured sequence drafts, not arbitrary generated JSX/code.",
"Selected/attached asset keys should remain the schema boundary; raw URLs should only appear after client-side materialization for preview/rendering.",
"The final replacement sequence should use the primary selected clip\u2019s visual track and the earliest selected start time unless clarified otherwise."
],
"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": "Sequence replacement selection: rows mutations currently drop selectedClipId/selectedTrackId, so the plan's returned-selection behavior will not actually select the inserted sequence unless useTimelineCommit is included.",
"evidence": "SequenceCreatorPanel.tsx calls applyEdit(result.mutation, { selectedClipId: result.selectedClipId, selectedTrackId: result.selectedTrackId }) for insert/replace, but src/tools/video-editor/hooks/useTimelineCommit.ts handles mutation.type === 'rows' by calling commitData(nextData, { save, transactionId, semantic }) and omits both selection fields. commitData is the place that calls editorSelectTimelineClip, so replacing deleted selected clips can clear selection instead of selecting the new sequence."
}
]
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.
- Include `changes_summary` as a short plain-English summary of what changed in the revision. If there were no concrete flags, say that explicitly (for example: `No critique flags were raised; refined wording and kept the plan aligned for execution.`).
- 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.
- CRITICAL: Your entire revised plan markdown (all sections) must be output as the `plan` field in the structured output. The prose response must not contain the plan text.
- CRITICAL: Return only the structured JSON object for the schema fields `plan`, `changes_summary`, `flags_addressed`, `assumptions`, `success_criteria`, and `questions`. Do not add commentary before or after the JSON object.
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: Sequence Creator Cleanup\n\n## Overview\nThe relevant implementation is concentrated in the video editor Sequence Creator path, not broad editor infrastructure. The main touch points are src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.tsx, src/tools/video-editor/lib/sequence-drafts.ts, src/tools/video-editor/hooks/useTimelineCommit.ts, sequence schema/metadata under src/tools/video-editor/sequences/, the local Image Jump Remotion component, and the supabase/functions/ai-generate-sequence/ prompt/validation tests. Existing dirty .megaplan/schemas/* changes must be ignored.\n\nThe critique does not indicate the plan targeted the wrong root cause. It identifies a downstream commit-path gap: Sequence Creator already passes desired selection options into applyEdit, but useTimelineCommit.ts currently drops selectedClipId and selectedTrackId for rows mutations before calling commitData. The plan should therefore keep the Sequence Creator replacement work and add a narrow commit-layer fix so the inserted sequence remains selected after replacing deleted clips.\n\nThe safest path is to keep this as a focused cleanup: make replacement semantics explicit in the sequence-draft mutation helper, preserve selection through row commits, reuse the existing chat attachment strip for Allowed Assets, tighten generate/edit state transitions, align image-jump schema/prompt/component modes, and prove each behavior with targeted tests before running typecheck/build-level validation.\n\n## Main Phase\n\n### Step 1: Lock Down Replacement Semantics (src/tools/video-editor/lib/sequence-drafts.ts)\nScope: Medium\n1. Update BuildReplaceSequenceDraftOptions to accept selectedClipIds in addition to selectedClipId.\n2. Normalize the selected IDs into a deduped ordered set that includes the primary selection.\n3. Validate that every selected target exists and belongs to a visual track before mutating anything.\n4. Delete all selected visual clips from rows/meta/clip order and insert one sequence clip.\n5. Place the new sequence at the earliest selected start time and on the primary selected clip’s visual track, unless later review decides the earliest clip’s track is more intuitive.\n6. Preserve existing overlap resolution and return the inserted clip/track IDs for downstream selection.\n\n### Step 2: Preserve Selection for Row Mutations (src/tools/video-editor/hooks/useTimelineCommit.ts)\nScope: Small\n1. Update the mutation.type === 'rows' branch in applyEdit to pass options.selectedClipId and options.selectedTrackId through to commitData, matching the config and pinnedShotGroups branches.\n2. Keep this generic: do not add Sequence Creator-specific logic to the commit hook.\n3. Add or extend src/tools/video-editor/hooks/useTimelineCommit.test.tsx to prove a rows mutation with selectedClipId/selectedTrackId selects the supplied clip and track instead of clearing selection when the old selected clip was deleted.\n\n### Step 3: Wire Multi-Selection Replacement Through the Panel (src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.tsx)\nScope: Small\n1. Read selectedClipIds from useTimelineEditorData().\n2. Pass both selectedClipId and selectedClipIds into the replace probe and handleReplace mutation path.\n3. Keep the existing replace button disabled for missing selections, invalid drafts, and any selected non-visual target.\n4. Update the button copy or title only if needed to make multi-replacement clear without adding clutter.\n\n### Step 4: Use the Timeline Chat Attachment Strip for Allowed Assets (SequenceCreatorPanel.tsx, AgentChatMessage.tsx if needed)\nScope: Medium\n1. Render Allowed Assets with AgentChatAttachmentStrip using the same preview/grouping shape as timeline chat attachments.\n2. Add removable X controls for individual assets and full-shot groups via onRemoveAttachment and onRemoveShot.\n3. Ensure removal updates the actual attachment/selection source that backs the strip. If the existing composer removal API only affects chat attachments, add the smallest appropriate deselect/removal path for selected timeline clips instead of making the X visually remove nothing.\n4. Keep asset filtering registry-backed: no placeholders, missing registry entries, raw/stale URLs, or duplicate asset keys.\n\n### Step 5: Make Generate vs Edit Coherent (SequenceCreatorPanel.tsx, SequenceCreatorPanel.test.tsx)\nScope: Medium\n1. Treat Generate as creating a new draft group from the current prompt and clearing stale selected-draft UI state.\n2. Treat Edit as modifying the selected draft group using mode: 'edit' plus edit_context containing the original prompt, selected draft index, source draft, and validated source draft.\n3. After a successful generation, select the new group and move into Edit mode so follow-up edits are obvious.\n4. On failed edit regeneration, preserve the prior valid draft group unless a valid replacement draft group is ready.\n5. Keep prompt validation and generation notes specific enough to distinguish “no drafts returned” from “schema rejected drafts.”\n\n### Step 6: Align Image-Jump Modes Across Metadata, Validation, Prompt, and Component\nScope: Medium\n1. Confirm image-jump metadata exposes imageAssetKeys and a mode field whose allowed values are exactly jump, snap, gallery, pulse, and shuffle.\n2. Add validation for enum-like string params where metadata declares a finite option set, or add a minimal image-jump-specific mode validator if that is the existing style.\n3. Update supabase/functions/ai-generate-sequence/templates.ts so the model is explicitly told when each mode should be used and to vary modes based on user language.\n4. Make ImageJumpSequence.tsx render visibly distinct motion/layout for each mode, not just small transform differences.\n5. Ensure schema-facing params remain asset keys while Remotion-facing params receive materialized image URLs through materialize.ts.\n\n### Step 7: Add Focused Tests\nScope: Medium\n1. Extend src/tools/video-editor/lib/sequence-drafts.test.ts for replacing multiple selected visual clips with one sequence, including cross-track selections and a non-visual rejection case.\n2. Extend src/tools/video-editor/hooks/useTimelineCommit.test.tsx for rows mutation selection preservation.\n3. Extend SequenceCreatorPanel.test.tsx for passing selectedClipIds into replacement, rendering Allowed Assets through removable chat attachment previews, and edit-vs-generate request bodies/state transitions.\n4. Extend src/tools/video-editor/sequences/validation.test.ts, metadata.test.ts, and/or materialize.test.ts for image-jump mode validity and asset-key-to-URL materialization.\n5. Extend supabase/functions/ai-generate-sequence/index.test.ts or template tests for mode guidance and text-free image-jump drafts.\n\n### Step 8: Validate Cheap-to-Broad\nScope: Small\n1. Run targeted tests first:\n bash\n npx vitest run --config config/testing/vitest.config.ts src/tools/video-editor/lib/sequence-drafts.test.ts src/tools/video-editor/hooks/useTimelineCommit.test.tsx src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.test.tsx src/tools/video-editor/sequences/validation.test.ts src/tools/video-editor/sequences/materialize.test.ts\n \n2. Run the edge sequence tests:\n bash\n npx vitest run --config config/testing/vitest.edge.config.ts supabase/functions/ai-generate-sequence/index.test.ts\n \n3. Run TypeScript/build validation:\n bash\n npm run build\n \n4. If build is too slow for iteration, use tsc --noEmit first, then finish with npm run build.\n\n## Execution Order\n1. Start with sequence-drafts.ts and its tests because replacement semantics are pure and cheap to verify.\n2. Fix useTimelineCommit.ts rows-mutation option forwarding before relying on returned selection behavior in the panel.\n3. Wire the panel to the helper once the helper and commit contracts are proven.\n4. Fix Allowed Assets removal next because it is UI-facing but localized.\n5. Align image-jump metadata/validation/prompt/component together so schema and generation behavior cannot drift.\n6. Finish with targeted tests, edge tests, and TypeScript/build.\n\n## Validation Order\n1. Run focused client tests after each client behavior group.\n2. Include useTimelineCommit.test.tsx in the focused run so rows mutations prove selected clip/track forwarding.\n3. Run the edge AI sequence tests after prompt/schema updates.\n4. Run npm run build as the final hard gate for TypeScript and production bundling.\n5. Inspect the final diff to confirm no unrelated .megaplan/ schema files were touched by the implementation.","changes_summary":"Addressed FLAG-001 by adding useTimelineCommit.ts to the plan, making rows mutations forward selected clip/track options into commitData, and adding a targeted commit-hook test so replacement can actually select the inserted sequence after deleting selected clips.","flags_addressed":["FLAG-001"],"assumptions":["The existing working-tree changes in src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.tsx, src/tools/video-editor/lib/sequence-drafts.ts, and related tests are in-scope partial work and should be reviewed/refined rather than reverted.","Dirty .megaplan/schemas/* files are unrelated to this task and must be left untouched.","The Sequence Creator should continue using trusted structured sequence drafts, not arbitrary generated JSX/code.","Selected/attached asset keys should remain the schema boundary; raw URLs should only appear after client-side materialization for preview/rendering.","The final replacement sequence should use the primary selected clip’s visual track and the earliest selected start time unless clarified otherwise.","Rows mutation selection forwarding in useTimelineCommit.ts is a generic commit-layer fix required by Sequence Creator replacement and should not contain Sequence Creator-specific branching."],"success_criteria":[{"criterion":"Replacing with multiple selected visual clips deletes every selected visual clip and inserts exactly one trusted sequence clip.","priority":"must","requires":["run_tests","read_files"]},{"criterion":"Replacement rejects missing selections and any selection containing an audio/non-visual clip before applying a mutation.","priority":"must","requires":["run_tests","read_files"]},{"criterion":"Rows mutations in useTimelineCommit.ts forward selectedClipId and selectedTrackId options into commitData, so replacing deleted selected clips selects the inserted sequence.","priority":"must","requires":["run_tests","read_files","parse_diff"]},{"criterion":"SequenceCreatorPanel passes the full selected clip set into replace probing and replacement execution.","priority":"must","requires":["run_tests","parse_diff"]},{"criterion":"Allowed Assets render through the timeline chat attachment strip and visible X controls remove the backed asset source rather than only changing local display.","priority":"must","requires":["run_tests","parse_diff","subjective_judgment"]},{"criterion":"Generate creates a new draft group, Edit updates the selected group with edit_context, and stale drafts do not remain visible after a successful new generation.","priority":"must","requires":["run_tests","read_files"]},{"criterion":"Image-jump mode values are aligned across metadata, validation, AI prompt guidance, and the Remotion component.","priority":"must","requires":["run_tests","read_files","parse_diff"]},{"criterion":"Focused Sequence Creator, timeline commit, sequence helper, sequence validation/materialization, and ai-generate-sequence tests pass.","priority":"must","requires":["run_tests"]},{"criterion":"TypeScript production validation passes via npm run build or an equivalent tsc plus build check.","priority":"must","requires":["run_shell","read_build_output"]},{"criterion":"Implementation does not modify unrelated .megaplan/ schema files.","priority":"must","requires":["parse_diff"]},{"criterion":"Changes stay localized to Sequence Creator, timeline commit option forwarding, sequence draft helpers, image-jump sequence metadata/component, ai-generate-sequence prompt/schema, and directly related tests.","priority":"should","requires":["parse_diff","subjective_judgment"]},{"criterion":"The UI copy remains concise and does not add explanatory in-app text beyond necessary labels, titles, and errors.","priority":"should","requires":["read_files","subjective_judgment"]},{"criterion":"Manual smoke test: open Sequence Creator, generate image-jump from selected/attached images, remove an allowed asset, edit the draft, and replace a multi-selection in the timeline.","priority":"info","requires":["inspect_runtime_ui"]}],"questions":["When an Allowed Assets item came from the current timeline selection rather than the chat attachment set, should clicking X deselect/remove that timeline selection, or should only attached chat chips be removable while selected clips remain controlled by timeline selection?","For multi-selected replacement across tracks, should the inserted sequence be placed on the primary selected clip’s track or on the track containing the earliest selected clip? I assume primary selected track for continuity with single-clip replacement."]}