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 generated animation sequence implementation without changing user-facing behavior. Focus on making the Sequence Creator structure excellent: extract generation request orchestration and draft/provenance helpers out of SequenceCreatorPanel where appropriate, move animation intent/provenance types to a shared sequence generation module, keep the single prompt UX, preserve trusted_v1 behavior and generated lane safety, update focused tests, and avoid broad ArtAgents/schema/package work in this pass.
code
Assistant
{"plan":"I’ll inspect the Sequence Creator implementation and focused tests directly, then turn that into a scoped implementation plan with assumptions and success criteria.","questions":[],"success_criteria":[],"assumptions":[]}
Assistant
{"plan":"I found the relevant Sequence Creator files and focused tests. I’ll read the component, sequence draft helpers, metadata/materialization code, and the edge function touch points just enough to identify concrete extraction boundaries.","questions":[],"success_criteria":[],"assumptions":[]}
Assistant
{"plan":"I have enough of the structure now: SequenceCreatorPanel.tsx is carrying UI state plus request assembly, response validation, draft grouping, preview config, and provenance metadata. I’m doing one more narrow pass over test scripts and exports so the plan can name the validation path precisely.","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 Structure Cleanup\n\n## Overview\nClean up SequenceCreatorPanel without changing behavior. The current component owns UI rendering plus request construction, draft validation, grouping, preview helpers, and provenance metadata in one file. The focused refactor should extract sequence generation request/draft/provenance logic into shared modules while preserving the trusted trusted_v1 lane, generated lane safety, current validation rules, and the single prompt-driven UX.\n\nRelevant touch points:\n- src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.tsx:54\n- src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.tsx:120\n- src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.tsx:364\n- src/tools/video-editor/lib/sequence-drafts.ts:106\n- src/tools/video-editor/sequences/validation.ts:158\n- supabase/functions/ai-generate-sequence/index.ts:204\n- supabase/functions/ai-generate-sequence/templates.ts:113\n\n## Main Phase\n\n### Step 1: Capture Current Behavior And Boundaries (SequenceCreatorPanel.tsx, focused tests)\nScope: Small\n1. Run the focused baseline tests before changing code:\n bash\n npx vitest run --config config/testing/vitest.config.ts src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.test.tsx src/tools/video-editor/lib/sequence-drafts.test.ts src/tools/video-editor/sequences/validation.test.ts src/tools/video-editor/sequences/materialize.test.ts\n \n2. Treat current tests as behavior documentation for request payloads, client-side draft filtering, preview materialization, insert/replace safety, and provenance metadata.\n3. Do not include broad ArtAgents, schema package, generated registry, or edge prompt behavior changes in this pass.\n\n### Step 2: Add A Shared Sequence Generation Module (src/tools/video-editor/sequences/generation.ts)\nScope: Medium\n1. Move shared generation types out of SequenceCreatorPanel.tsx, including:\n - AllowedSequenceAsset\n - EditableSequenceDraft\n - SequenceDraftGroup\n - GenerateSequenceResponse\n - SequenceGenerationClipPayload\n - SequenceAnimationIntent\n2. Move pure helpers into the same module:\n - buildAllowedSequenceAssets\n - buildGenerationClipPayloads\n - buildAnimationIntentPayload\n - createEditableDraft\n - nameDraftGroupFromPrompt\n - sanitizeAnimationIntentForProvenance\n - buildSequenceGenerationMetadata\n3. Keep the module focused on sequence generation data and provenance. Avoid coupling it to React rendering or component state.\n4. Update imports in SequenceCreatorPanel.test.tsx so helper tests import from sequences/generation.ts, not from the panel component.\n\n### Step 3: Extract Request Orchestration (src/tools/video-editor/components/SequenceCreator/useSequenceGeneration.ts)\nScope: Medium\n1. Move runSequenceGeneration request construction and response normalization out of SequenceCreatorPanel.tsx:364 into a small hook or service local to the Sequence Creator folder.\n2. Keep component-owned UI state in the panel where it remains presentation-specific: mode, text field values, selected group/index, and rendered panels.\n3. Have the extracted function return normalized outcomes such as valid editable drafts, invalid count, generated group metadata, and error/no-draft notes rather than directly rendering UI.\n4. Preserve the existing request body shape:\n - prompt\n - mode\n - edit_context\n - animation_intent derived from the same prompt text\n - timeline\n - selected_clips\n - attached_clips\n - allowed_clip_types\n - allowed_assets\n - theme\n - theme_overrides\n5. Preserve abort handling and the 150 second timeout.\n\n### Step 4: Extract Draft/Provenance Mutation Helpers (src/tools/video-editor/lib/sequence-drafts.ts or src/tools/video-editor/sequences/generation.ts)\nScope: Small\n1. Move attachSequenceGenerationMetadata out of the panel so insert/replace paths can call a reusable helper.\n2. Keep insertion/replacement row mutation behavior in sequence-drafts.ts; do not alter placement, overlap resolution, replacement target validation, clip order, or meta delete behavior.\n3. Ensure generated sequence clips still receive:\n ts\n generation: {\n sequence_lane: 'trusted_v1',\n sequence_creator: {\n name,\n prompt,\n draft_index,\n intent,\n },\n }\n \n4. Preserve URL redaction in provenance intent while leaving the original prompt stored as it is today.\n\n### Step 5: Slim The Panel Without Changing UX (SequenceCreatorPanel.tsx)\nScope: Medium\n1. Rewire SequenceCreatorPanel to import extracted helpers and orchestration.\n2. Keep the current prompt-driven UI and do not add a separate animation intent input.\n3. Preserve generate/edit mode behavior, including clearing selected draft UI only for new generation and preserving the prior valid group when edit regeneration returns no valid replacement.\n4. Keep buildSequencePreviewConfig either in the panel only if it is truly presentation-specific, or move it to the generation module if tests need it directly. Do not change preview materialization behavior.\n\n### Step 6: Update Focused Tests (SequenceCreatorPanel.test.tsx, sequence-drafts.test.ts, optional new generation tests)\nScope: Medium\n1. Move pure helper assertions for allowed assets, clip payloads, animation intent, and provenance into tests for src/tools/video-editor/sequences/generation.ts if that keeps panel tests focused on UI behavior.\n2. Keep panel tests covering:\n - prompt-derived animation_intent\n - stale draft clearing on new generate\n - edit regeneration request body\n - invalid draft notes\n - insert/replace calls and metadata application\n3. Keep sequence-drafts.test.ts focused on row mutation safety.\n4. Add or update a direct provenance test confirming raw URLs are redacted from intent.freeform and sequence_lane remains trusted_v1.\n\n### Step 7: Validate Narrowly, Then Broadly Enough\nScope: Small\n1. Run focused tests first:\n bash\n npx vitest run --config config/testing/vitest.config.ts src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.test.tsx src/tools/video-editor/lib/sequence-drafts.test.ts src/tools/video-editor/sequences/validation.test.ts src/tools/video-editor/sequences/materialize.test.ts\n \n2. Run typecheck/build-level validation if focused tests pass:\n bash\n npm run build\n \n3. Run lint if the refactor adds new files or import paths with risk:\n bash\n npm run lint\n \n\n## Execution Order\n1. Establish focused baseline behavior.\n2. Create sequences/generation.ts and move pure types/helpers first.\n3. Extract request orchestration only after imports are stable.\n4. Rewire SequenceCreatorPanel with minimal UI changes.\n5. Update tests alongside moved exports.\n6. Run focused tests before broader build/lint checks.\n\n## Validation Order\n1. Run the Sequence Creator and sequence helper tests first because they directly guard behavior.\n2. Run npm run build to catch cross-file TypeScript/import mistakes.\n3. Run npm run lint if time allows or if new helper files introduce lint-sensitive imports.","questions":["Does “single prompt UX” mean preserving the existing Generate/Edit prompt areas exactly as-is, or should edit mode also be collapsed into the same visible prompt control? This plan assumes no new intent field and no UX restructuring beyond preserving the current prompt-driven flow.","Should provenance helpers remain frontend-only for this pass, or should their types be mirrored into supabase/functions/ai-generate-sequence? This plan keeps edge function behavior unchanged to avoid broad schema/package work."],"success_criteria":[{"criterion":"SequenceCreatorPanel.tsx no longer defines shared generation/provenance types or pure request payload helpers; those live in a sequence generation module and are imported by the panel/tests.","priority":"must","requires":["read_files","parse_diff"]},{"criterion":"Generated sequence insert and replace still persist generation.sequence_lane as trusted_v1 and preserve sequence_creator provenance with URL-redacted intent.freeform.","priority":"must","requires":["run_tests","parse_diff"]},{"criterion":"The AI generation request body remains behaviorally compatible: prompt, mode, edit_context, animation_intent, timeline, selected_clips, attached_clips, allowed_clip_types, allowed_assets, theme, and theme_overrides are still sent as before.","priority":"must","requires":["run_tests","parse_diff"]},{"criterion":"Client-side validation still rejects invalid drafts, raw URLs, generated code fields, animation refs, untrusted clip types, and disallowed asset keys.","priority":"must","requires":["run_tests","read_files"]},{"criterion":"Insert/replace generated lane safety is preserved: sequence drafts only insert on visual tracks, audio replacements are rejected, selected visual replacement behavior and clip order/meta deletes remain unchanged.","priority":"must","requires":["run_tests"]},{"criterion":"Focused Sequence Creator and sequence helper tests pass.","priority":"must","requires":["run_tests"]},{"criterion":"The project builds successfully after the refactor.","priority":"must","requires":["run_shell","read_build_output"]},{"criterion":"SequenceCreatorPanel.tsx is materially slimmer and reads primarily as UI composition plus event wiring rather than request/provenance orchestration.","priority":"should","requires":["read_files","subjective_judgment"]},{"criterion":"New helper boundaries avoid React dependencies unless implemented as an explicit hook under the SequenceCreator component folder.","priority":"should","requires":["read_files","parse_diff"]},{"criterion":"No ArtAgents, timeline schema package, generated registry, or broad edge function prompt/schema work is included in this pass.","priority":"should","requires":["parse_diff","read_files"]}],"assumptions":["Existing dirty working tree changes are implementation context and should not be reverted unless they directly conflict with this refactor.","The refactor should preserve current user-facing labels, buttons, toasts, notes, validation messages, preview behavior, and generated/edit mode behavior.","The frontend shared module can live at src/tools/video-editor/sequences/generation.ts; edge function duplication in supabase/functions/ai-generate-sequence/sequence-validation.ts is intentionally left alone in this pass.","trusted_v1 is the required generated lane marker for provenance, not a broader schema migration target.","Focused Vitest coverage is sufficient for this structural cleanup, with npm run build used as the broader TypeScript/import check."]}
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 generated animation sequence implementation without changing user-facing behavior. Focus on making the Sequence Creator structure excellent: extract generation request orchestration and draft/provenance helpers out of SequenceCreatorPanel where appropriate, move animation intent/provenance types to a shared sequence generation module, keep the single prompt UX, preserve trusted_v1 behavior and generated lane safety, update focused tests, and avoid broad ArtAgents/schema/package work in this pass.
code
Current plan (markdown):
# Implementation Plan: Sequence Creator Structure Cleanup
Overview
Clean up SequenceCreatorPanel without changing behavior. The current component owns UI rendering plus request construction, draft validation, grouping, preview helpers, and provenance metadata in one file. The focused refactor should extract sequence generation request/draft/provenance logic into shared modules while preserving the trusted trusted_v1 lane, generated lane safety, current validation rules, and the single prompt-driven UX.
Step 1: Capture Current Behavior And Boundaries (SequenceCreatorPanel.tsx, focused tests)
Scope: Small
Run the focused baseline tests before changing code:
bash
npx vitest run --config config/testing/vitest.config.ts src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.test.tsx src/tools/video-editor/lib/sequence-drafts.test.ts src/tools/video-editor/sequences/validation.test.ts src/tools/video-editor/sequences/materialize.test.ts
Treat current tests as behavior documentation for request payloads, client-side draft filtering, preview materialization, insert/replace safety, and provenance metadata.
Do not include broad ArtAgents, schema package, generated registry, or edge prompt behavior changes in this pass.
Step 2: Add A Shared Sequence Generation Module (src/tools/video-editor/sequences/generation.ts)
Scope: Medium
Move shared generation types out of SequenceCreatorPanel.tsx, including:
AllowedSequenceAsset
EditableSequenceDraft
SequenceDraftGroup
GenerateSequenceResponse
SequenceGenerationClipPayload
SequenceAnimationIntent
Move pure helpers into the same module:
buildAllowedSequenceAssets
buildGenerationClipPayloads
buildAnimationIntentPayload
createEditableDraft
nameDraftGroupFromPrompt
sanitizeAnimationIntentForProvenance
buildSequenceGenerationMetadata
Keep the module focused on sequence generation data and provenance. Avoid coupling it to React rendering or component state.
Update imports in SequenceCreatorPanel.test.tsx so helper tests import from sequences/generation.ts, not from the panel component.
Move runSequenceGeneration request construction and response normalization out of SequenceCreatorPanel.tsx:364 into a small hook or service local to the Sequence Creator folder.
Keep component-owned UI state in the panel where it remains presentation-specific: mode, text field values, selected group/index, and rendered panels.
Have the extracted function return normalized outcomes such as valid editable drafts, invalid count, generated group metadata, and error/no-draft notes rather than directly rendering UI.
Preserve the existing request body shape:
prompt
mode
edit_context
animation_intent derived from the same prompt text
timeline
selected_clips
attached_clips
allowed_clip_types
allowed_assets
theme
theme_overrides
Preserve abort handling and the 150 second timeout.
Step 4: Extract Draft/Provenance Mutation Helpers (src/tools/video-editor/lib/sequence-drafts.ts or src/tools/video-editor/sequences/generation.ts)
Scope: Small
Move attachSequenceGenerationMetadata out of the panel so insert/replace paths can call a reusable helper.
Keep insertion/replacement row mutation behavior in sequence-drafts.ts; do not alter placement, overlap resolution, replacement target validation, clip order, or meta delete behavior.
Preserve URL redaction in provenance intent while leaving the original prompt stored as it is today.
Step 5: Slim The Panel Without Changing UX (SequenceCreatorPanel.tsx)
Scope: Medium
Rewire SequenceCreatorPanel to import extracted helpers and orchestration.
Keep the current prompt-driven UI and do not add a separate animation intent input.
Preserve generate/edit mode behavior, including clearing selected draft UI only for new generation and preserving the prior valid group when edit regeneration returns no valid replacement.
Keep buildSequencePreviewConfig either in the panel only if it is truly presentation-specific, or move it to the generation module if tests need it directly. Do not change preview materialization behavior.
Move pure helper assertions for allowed assets, clip payloads, animation intent, and provenance into tests for src/tools/video-editor/sequences/generation.ts if that keeps panel tests focused on UI behavior.
Keep panel tests covering:
prompt-derived animation_intent
stale draft clearing on new generate
edit regeneration request body
invalid draft notes
insert/replace calls and metadata application
Keep sequence-drafts.test.ts focused on row mutation safety.
Add or update a direct provenance test confirming raw URLs are redacted from intent.freeform and sequence_lane remains trusted_v1.
Step 7: Validate Narrowly, Then Broadly Enough
Scope: Small
Run focused tests first:
bash
npx vitest run --config config/testing/vitest.config.ts src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.test.tsx src/tools/video-editor/lib/sequence-drafts.test.ts src/tools/video-editor/sequences/validation.test.ts src/tools/video-editor/sequences/materialize.test.ts
Run typecheck/build-level validation if focused tests pass:
bash
npm run build
Run lint if the refactor adds new files or import paths with risk:
bash
npm run lint
Execution Order
Establish focused baseline behavior.
Create sequences/generation.ts and move pure types/helpers first.
Extract request orchestration only after imports are stable.
Rewire SequenceCreatorPanel with minimal UI changes.
Update tests alongside moved exports.
Run focused tests before broader build/lint checks.
Validation Order
Run the Sequence Creator and sequence helper tests first because they directly guard behavior.
Run npm run build to catch cross-file TypeScript/import mistakes.
Run npm run lint if time allows or if new helper files introduce lint-sensitive imports.
code
Current plan metadata:
{
"version": 1,
"timestamp": "2026-05-01T23:53:02Z",
"hash": "sha256:b54989f2ac1c69d7d21e27a29be5fa1e4d7cc7744c09de4a9de2b8ee76af82e7",
"questions": [
"Does \u201csingle prompt UX\u201d mean preserving the existing Generate/Edit prompt areas exactly as-is, or should edit mode also be collapsed into the same visible prompt control? This plan assumes no new intent field and no UX restructuring beyond preserving the current prompt-driven flow.",
"Should provenance helpers remain frontend-only for this pass, or should their types be mirrored into supabase/functions/ai-generate-sequence? This plan keeps edge function behavior unchanged to avoid broad schema/package work."
],
"success_criteria": [
{
"criterion": "SequenceCreatorPanel.tsx no longer defines shared generation/provenance types or pure request payload helpers; those live in a sequence generation module and are imported by the panel/tests.",
"priority": "must",
"requires": [
"read_files",
"parse_diff"
]
},
{
"criterion": "Generated sequence insert and replace still persist generation.sequence_lane as trusted_v1 and preserve sequence_creator provenance with URL-redacted intent.freeform.",
"priority": "must",
"requires": [
"run_tests",
"parse_diff"
]
},
{
"criterion": "The AI generation request body remains behaviorally compatible: prompt, mode, edit_context, animation_intent, timeline, selected_clips, attached_clips, allowed_clip_types, allowed_assets, theme, and theme_overrides are still sent as before.",
"priority": "must",
"requires": [
"run_tests",
"parse_diff"
]
},
{
"criterion": "Client-side validation still rejects invalid drafts, raw URLs, generated code fields, animation refs, untrusted clip types, and disallowed asset keys.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "Insert/replace generated lane safety is preserved: sequence drafts only insert on visual tracks, audio replacements are rejected, selected visual replacement behavior and clip order/meta deletes remain unchanged.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Focused Sequence Creator and sequence helper tests pass.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "The project builds successfully after the refactor.",
"priority": "must",
"requires": [
"run_shell",
"read_build_output"
]
},
{
"criterion": "SequenceCreatorPanel.tsx is materially slimmer and reads primarily as UI composition plus event wiring rather than request/provenance orchestration.",
"priority": "should",
"requires": [
"read_files",
"subjective_judgment"
]
},
{
"criterion": "New helper boundaries avoid React dependencies unless implemented as an explicit hook under the SequenceCreator component folder.",
"priority": "should",
"requires": [
"read_files",
"parse_diff"
]
},
{
"criterion": "No ArtAgents, timeline schema package, generated registry, or broad edge function prompt/schema work is included in this pass.",
"priority": "should",
"requires": [
"parse_diff",
"read_files"
]
}
],
"assumptions": [
"Existing dirty working tree changes are implementation context and should not be reverted unless they directly conflict with this refactor.",
"The refactor should preserve current user-facing labels, buttons, toasts, notes, validation messages, preview behavior, and generated/edit mode behavior.",
"The frontend shared module can live at ; edge function duplication in is intentionally left alone in this pass.",
" is the required generated lane marker for provenance, not a broader schema migration target.",
"Focused Vitest coverage is sufficient for this structural cleanup, with used as the broader TypeScript/import check."
],
"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 generation module boundary: moving EditableSequenceDraft into sequences/generation.ts can introduce a real dependency cycle unless the plan explicitly accounts for sequence-drafts.ts already importing sequence validation and likely needing the draft type/helper. If generation.ts imports sequence-drafts.ts for row mutation helpers while sequence-drafts.ts imports generation.ts for EditableSequenceDraft or provenance helpers, Vitest/build can fail or runtime initialization can become order-sensitive.",
"evidence": "Plan step 2 moves EditableSequenceDraft and createEditableDraft to src/tools/video-editor/sequences/generation.ts; step 4 allows attachSequenceGenerationMetadata in either sequence-drafts.ts or generation.ts, while keeping insertion/replacement mutation behavior in sequence-drafts.ts. Current SequenceCreatorPanel.tsx defines both draft/provenance helpers and imports mutation helpers from ../../lib/sequence-drafts, so the refactor needs a one-way dependency that the plan does not pin down."
}
]
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 Structure Cleanup\n\n## Overview\nClean up SequenceCreatorPanel without changing user-facing behavior. The current component owns UI rendering plus request construction, draft validation, grouping, preview helpers, and provenance metadata in one file. The focused refactor should extract generation request orchestration and draft/provenance helpers while preserving the trusted trusted_v1 lane, generated lane safety, current validation rules, and the single prompt-driven UX.\n\nThe critique does not indicate that the plan targets the wrong code or root cause. It correctly flags an implementation risk in the module boundary: sequence-drafts.ts already owns row mutation behavior and imports sequence validation types, so generation/provenance helpers must not create a reverse dependency from sequence-drafts.ts back into a module that imports row mutation helpers. The revised approach pins the dependency direction explicitly:\n\n- src/tools/video-editor/sequences/generation.ts owns generation request/provenance data types and pure helpers only.\n- src/tools/video-editor/lib/sequence-drafts.ts continues to own insert/replace row mutation behavior and must not import sequences/generation.ts.\n- SequenceCreatorPanel.tsx and the local request orchestration module compose both modules.\n\nRelevant touch points:\n- src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.tsx:54\n- src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.tsx:120\n- src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.tsx:364\n- src/tools/video-editor/lib/sequence-drafts.ts:106\n- src/tools/video-editor/sequences/validation.ts:158\n- supabase/functions/ai-generate-sequence/index.ts:204\n- supabase/functions/ai-generate-sequence/templates.ts:113\n\n## Main Phase\n\n### Step 1: Capture Current Behavior And Boundaries (SequenceCreatorPanel.tsx, focused tests)\nScope: Small\n1. Run the focused baseline tests before changing code:\n bash\n npx vitest run --config config/testing/vitest.config.ts src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.test.tsx src/tools/video-editor/lib/sequence-drafts.test.ts src/tools/video-editor/sequences/validation.test.ts src/tools/video-editor/sequences/materialize.test.ts\n \n2. Treat current tests as behavior documentation for request payloads, client-side draft filtering, preview materialization, insert/replace safety, and provenance metadata.\n3. Note the intended dependency graph before editing:\n - sequences/generation.ts may import sequence validation types and selected media types.\n - components/SequenceCreator/useSequenceGeneration.ts may import generation helpers, registry metadata, validation, and the Supabase invoker.\n - SequenceCreatorPanel.tsx may import generation helpers, request orchestration, and sequence-drafts.ts mutation helpers.\n - sequence-drafts.ts must not import sequences/generation.ts.\n4. Do not include broad ArtAgents, schema package, generated registry, or edge prompt behavior changes in this pass.\n\n### Step 2: Add A Shared Sequence Generation Module (src/tools/video-editor/sequences/generation.ts)\nScope: Medium\n1. Move shared generation/provenance types out of SequenceCreatorPanel.tsx, including:\n - AllowedSequenceAsset\n - EditableSequenceDraft\n - SequenceDraftGroup\n - GenerateSequenceResponse\n - SequenceGenerationClipPayload\n - SequenceAnimationIntent\n2. Move pure helpers into the same module:\n - buildAllowedSequenceAssets\n - buildGenerationClipPayloads\n - buildAnimationIntentPayload\n - createEditableDraft\n - nameDraftGroupFromPrompt\n - sanitizeAnimationIntentForProvenance\n - buildSequenceGenerationMetadata\n - attachSequenceGenerationMetadata\n3. Keep attachSequenceGenerationMetadata in sequences/generation.ts, not sequence-drafts.ts, because it is provenance metadata decoration over an already-built row mutation and should not make row mutation helpers depend on generation helpers.\n4. Keep the module free of React state, UI rendering, Supabase invocation, and insert/replace row mutation construction.\n5. Allow sequences/generation.ts to import only type-level or pure data dependencies such as SelectedMediaClip, ResolvedTimelineConfig, ResolvedAssetRegistryEntry, TimelineEditMutation, and ValidatedSequenceDraft.\n6. Update imports in SequenceCreatorPanel.test.tsx so helper tests import from sequences/generation.ts, not from the panel component.\n\n### Step 3: Extract Request Orchestration (src/tools/video-editor/components/SequenceCreator/useSequenceGeneration.ts)\nScope: Medium\n1. Move runSequenceGeneration request construction and response normalization out of SequenceCreatorPanel.tsx:364 into a local hook or service under the Sequence Creator folder.\n2. The orchestration module may import sequences/generation.ts, sequences/registry.ts, sequences/validation.ts, and invokeSupabaseEdgeFunction.\n3. Do not import sequence-drafts.ts from the orchestration module; insert/replace row mutation remains a separate panel action path.\n4. Keep component-owned UI state in the panel where it remains presentation-specific: mode, text field values, selected group/index, rendered panels, and toasts/notes if the extracted hook returns outcome data.\n5. Have the extracted function return normalized outcomes such as valid editable drafts, invalid count, generated group metadata, and error/no-draft notes rather than directly rendering UI.\n6. Preserve the existing request body shape:\n - prompt\n - mode\n - edit_context\n - animation_intent derived from the same prompt text\n - timeline\n - selected_clips\n - attached_clips\n - allowed_clip_types\n - allowed_assets\n - theme\n - theme_overrides\n7. Preserve abort handling and the 150 second timeout.\n\n### Step 4: Keep Row Mutation Helpers One-Way (src/tools/video-editor/lib/sequence-drafts.ts)\nScope: Small\n1. Keep buildInsertSequenceDraftEdit and buildReplaceSequenceDraftEdit in sequence-drafts.ts unchanged except for import type cleanup if needed.\n2. Do not move EditableSequenceDraft, provenance helpers, or request helpers into sequence-drafts.ts.\n3. Do not import from sequences/generation.ts inside sequence-drafts.ts.\n4. Keep insertion/replacement row mutation behavior unchanged: placement, overlap resolution, replacement target validation, clip order, meta updates, and meta deletes must remain equivalent.\n5. In panel insert/replace handlers, compose row mutation output with attachSequenceGenerationMetadata from sequences/generation.ts after a successful mutation is produced.\n6. Ensure generated sequence clips still receive:\n ts\n generation: {\n sequence_lane: 'trusted_v1',\n sequence_creator: {\n name,\n prompt,\n draft_index,\n intent,\n },\n }\n \n7. Preserve URL redaction in provenance intent while leaving the original prompt stored as it is today.\n\n### Step 5: Slim The Panel Without Changing UX (SequenceCreatorPanel.tsx)\nScope: Medium\n1. Rewire SequenceCreatorPanel to import extracted generation helpers, request orchestration, and the existing sequence-drafts.ts row mutation helpers.\n2. Keep the current prompt-driven UI and do not add a separate animation intent input.\n3. Preserve generate/edit mode behavior, including clearing selected draft UI only for new generation and preserving the prior valid group when edit regeneration returns no valid replacement.\n4. Keep buildSequencePreviewConfig in the panel unless it becomes useful as a pure tested helper. If moved, place it in a module that does not import sequence-drafts.ts.\n5. Confirm the panel no longer exports pure generation helpers solely for tests.\n\n### Step 6: Update Focused Tests (SequenceCreatorPanel.test.tsx, sequence-drafts.test.ts, optional new generation tests)\nScope: Medium\n1. Add src/tools/video-editor/sequences/generation.test.ts or equivalent focused tests for pure helper behavior:\n - allowed asset construction\n - generation clip payloads\n - prompt-derived animation intent\n - provenance metadata shape\n - URL redaction in intent.freeform\n - attachSequenceGenerationMetadata preserving existing meta updates while adding generation\n2. Keep panel tests covering:\n - prompt-derived animation_intent request body\n - stale draft clearing on new generate\n - edit regeneration request body\n - invalid draft notes\n - insert/replace calls and metadata application\n3. Keep sequence-drafts.test.ts focused on row mutation safety and make no assertions that require importing generation helpers into sequence-drafts.ts.\n4. Add an import/dependency sanity check by reviewing changed imports or using the build output to verify no cycle or initialization issue was introduced.\n\n### Step 7: Validate Narrowly, Then Broadly Enough\nScope: Small\n1. Run focused tests first:\n bash\n npx vitest run --config config/testing/vitest.config.ts src/tools/video-editor/components/SequenceCreator/SequenceCreatorPanel.test.tsx src/tools/video-editor/lib/sequence-drafts.test.ts src/tools/video-editor/sequences/generation.test.ts src/tools/video-editor/sequences/validation.test.ts src/tools/video-editor/sequences/materialize.test.ts\n \n2. If no new generation.test.ts file is created, omit that path and keep the moved helper assertions in the closest focused test file.\n3. Run typecheck/build-level validation after focused tests pass:\n bash\n npm run build\n \n4. Run lint if the refactor adds new files or import paths with risk:\n bash\n npm run lint\n \n\n## Execution Order\n1. Establish focused baseline behavior and record the one-way dependency rule.\n2. Create sequences/generation.ts and move pure types/helpers first, including provenance metadata decoration.\n3. Update helper tests/imports before extracting orchestration so moved exports are covered.\n4. Extract request orchestration without importing row mutation helpers.\n5. Rewire SequenceCreatorPanel with minimal UI changes and compose generation/provenance helpers with sequence-drafts.ts only in the panel action handlers.\n6. Run focused tests before broader build/lint checks.\n\n## Validation Order\n1. Run the Sequence Creator and sequence helper tests first because they directly guard behavior.\n2. Run npm run build to catch cross-file TypeScript/import mistakes and dependency-cycle/runtime initialization issues.\n3. Run npm run lint if new helper files or import paths need lint validation.",
"changes_summary": "Addressed the dependency-cycle critique by pinning a one-way module boundary: generation/provenance helpers live in sequences/generation.ts, row mutation helpers stay in lib/sequence-drafts.ts, and only the panel composes them. The plan now explicitly forbids sequence-drafts.ts from importing generation helpers and adds validation for import/build safety.",
"flags_addressed": [
"FLAG-001"
],
"assumptions": [
"Existing dirty working tree changes are implementation context and should not be reverted unless they directly conflict with this refactor.",
"The refactor should preserve current user-facing labels, buttons, toasts, notes, validation messages, preview behavior, and generated/edit mode behavior.",
"The frontend shared module can live at src/tools/video-editor/sequences/generation.ts; edge function duplication in supabase/functions/ai-generate-sequence/sequence-validation.ts is intentionally left alone in this pass.",
"trusted_v1 is the required generated lane marker for provenance, not a broader schema migration target.",
"Focused Vitest coverage is sufficient for this structural cleanup, with npm run build used as the broader TypeScript/import and dependency safety check.",
"sequence-drafts.ts remains the owner of insert/replace row mutation behavior and must not depend on sequences/generation.ts."
],
"success_criteria": [
{
"criterion": "SequenceCreatorPanel.tsx no longer defines shared generation/provenance types or pure request payload helpers; those live in a sequence generation module and are imported by the panel/tests.",
"priority": "must",
"requires": [
"read_files",
"parse_diff"
]
},
{
"criterion": "src/tools/video-editor/lib/sequence-drafts.ts does not import src/tools/video-editor/sequences/generation.ts, and row mutation helpers remain independent of request/provenance orchestration.",
"priority": "must",
"requires": [
"read_files",
"parse_diff"
]
},
{
"criterion": "Generated sequence insert and replace still persist generation.sequence_lane as trusted_v1 and preserve sequence_creator provenance with URL-redacted intent.freeform.",
"priority": "must",
"requires": [
"run_tests",
"parse_diff"
]
},
{
"criterion": "The AI generation request body remains behaviorally compatible: prompt, mode, edit_context, animation_intent, timeline, selected_clips, attached_clips, allowed_clip_types, allowed_assets, theme, and theme_overrides are still sent as before.",
"priority": "must",
"requires": [
"run_tests",
"parse_diff"
]
},
{
"criterion": "Client-side validation still rejects invalid drafts, raw URLs, generated code fields, animation refs, untrusted clip types, and disallowed asset keys.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "Insert/replace generated lane safety is preserved: sequence drafts only insert on visual tracks, audio replacements are rejected, selected visual replacement behavior and clip order/meta deletes remain unchanged.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Focused Sequence Creator, generation helper, and sequence draft tests pass.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "The project builds successfully after the refactor, with no TypeScript/import/runtime initialization failures from the new module boundaries.",
"priority": "must",
"requires": [
"run_shell",
"read_build_output"
]
},
{
"criterion": "SequenceCreatorPanel.tsx is materially slimmer and reads primarily as UI composition plus event wiring rather than request/provenance orchestration.",
"priority": "should",
"requires": [
"read_files",
"subjective_judgment"
]
},
{
"criterion": "New helper boundaries avoid React dependencies unless implemented as an explicit hook under the SequenceCreator component folder.",
"priority": "should",
"requires": [
"read_files",
"parse_diff"
]
},
{
"criterion": "No ArtAgents, timeline schema package, generated registry, or broad edge function prompt/schema work is included in this pass.",
"priority": "should",
"requires": [
"parse_diff",
"read_files"
]
}
],
"questions": [
"Does “single prompt UX” mean preserving the existing Generate/Edit prompt areas exactly as-is, or should edit mode also be collapsed into the same visible prompt control? This plan assumes no new intent field and no UX restructuring beyond preserving the current prompt-driven flow.",
"Should provenance helpers remain frontend-only for this pass, or should their types be mirrored into supabase/functions/ai-generate-sequence? This plan keeps edge function behavior unchanged to avoid broad schema/package work."
]
}