Migrate ALL task creation logic into create-task edge function: move param building, defaults, validation, resolution calc, LoRA formatting, ID generation from 6 client-side task families into server-side resolvers. Batch support inside edge function. Travel orchestrator creates only orchestrator task. No backward compat needed. Clean migration of every caller, remove all client-side param building code.
code
Plan:
# Implementation Plan: Migrate ALL Task Creation Logic to Server-Side Resolvers
Overview
Current state: The create-task edge function (supabase/functions/create-task/) is intentionally thin — it authenticates, checks project ownership, and INSERTs an opaque params blob into the tasks table. All validation, default application, resolution calculation, LoRA formatting, ID generation, seed normalization, and payload composition happens client-side across ~15 files in src/shared/lib/tasks/ and src/shared/lib/taskCreation/.
Goal: Move all param-building logic into server-side "resolvers" inside the edge function. Clients send raw/minimal inputs; the server does validation, defaults, resolution lookup, LoRA formatting, ID generation, and final payload composition. Add batch support (N tasks from 1 request). No backward compatibility needed.
Scope: 6 task families in src/shared/lib/tasks/families/ plus 4 non-family creators (travelBetweenImages, magicEdit, maskedEdit, crossfadeJoin). ~2500 lines of client-side logic to move. ~12 caller hooks/services to simplify.
Constraints:
Edge function runs in Deno (Supabase Edge Functions). No access to Vite, React, or browser APIs.
Edge function already has supabaseAdmin — can do DB queries (resolution lookup, parent generation, segment routing) more cleanly than client.
Workers expect specific params shapes — resolver output must match current worker expectations exactly.
Batch tasks currently fire N parallel HTTP requests; new batch support = single request → N inserts.
Key DB queries that move server-side:
Assistant
User
Assistant
{"flags":[{"id":"batch-idempotency-design-gap","concern":"Task idempotency: the plan still breaks retry deduplication by moving idempotency-key generation entirely to the server.","category":"correctness","severity_hint":"likely-significant","evidence":"Current deduplication depends on the client sending a stable idempotency_key with the request (src/shared/lib/taskCreation/createTask.ts:36-54), and the edge function recovers duplicates by that exact key (supabase/functions/create-task/index.ts:164-178). In Step 3, the server generates fresh UUIDs per task after receiving the request. A retried request would therefore get new keys and create duplicate tasks instead of reusing the original ones, which conflicts with the success criterion that re-sending the same batch request returns existing task IDs."},{"id":"travel-validation-callsite-left-behind","concern":"Travel validation: Step 19/23 removes , but the plan does not explicitly retire the remaining client-side call in .","category":"completeness","severity_hint":"likely-minor","evidence":" still imports and calls before task creation. The revised plan says will be deleted and validation moves server-side, but it only mentions reading ; it does not explicitly remove or replace this import/callsite."}],"verified_flag_ids":["task-api-remaining-raw-callers","travel-module-delete-scope-creep","family-types-relocation-missing","response-contract-update-missing","cleanup-shared-utils-overreach"],"disputed_flag_ids":[]}
resolveProjectResolution() — queries projects.aspect_ratio (already queried for ownership check — can piggyback)
Decision: Keep the existing raw { params, task_type } path alive during migration (feature-flagged by presence of family field), so families can be migrated one at a time without coordinating client+server deploys.
Step 2: Add shared server-side utilities
Scope: Medium
Port resolution lookup into supabase/functions/create-task/resolvers/shared/resolution.ts:
Reuse the project query the edge function already makes for ownership — extend it to select('user_id, aspect_ratio') instead of select('user_id') (supabase/functions/create-task/index.ts:120).
Port ASPECT_RATIO_TO_RESOLUTION map (from src/shared/lib/media/aspectRatios.ts).
Port model-specific resolution scaling (e.g., 1.5x for qwen-image models from families/imageGeneration/index.ts:39-69).
Port ID generation into resolvers/shared/ids.ts:
generateTaskId(prefix), generateRunId(), generateUUID() — from src/shared/lib/taskCreation/ids.ts.
Port seed utilities into resolvers/shared/seed.ts:
resolveSeed32Bit(), validateSeed32Bit() — from src/shared/lib/taskCreation/schemaUtils.ts.
Port LoRA formatting into resolvers/shared/loras.ts:
mapPathLorasToStrengthRecord() — from src/shared/lib/taskCreation/schemaUtils.ts.
validateLoraConfigs() — same source.
Port hires fix builder into resolvers/shared/hiresFix.ts:
buildHiresFixParams() — from src/shared/lib/taskCreation/hiresFix.ts.
Port lineage fields into resolvers/shared/lineage.ts:
setTaskLineageFields() — from src/shared/lib/taskCreation/payloadFields.ts.
Port validation utilities into resolvers/shared/validation.ts:
validateRequiredFields(), validateNonEmptyString(), validateUrlString(), validateNumericRange(), TaskValidationError — from src/shared/lib/taskCreation/.
Step 3: Add batch insert support to edge function
Scope: Medium
Modifysupabase/functions/create-task/index.ts to handle resolver results that produce multiple TaskInsertObjects.
Use.insert(arrayOfObjects) instead of .insert(singleObject) for batch — Supabase supports array insert natively.
Return{ task_ids: string[], status: "Tasks queued" } for batch, { task_id: string, status: "Task queued" } for single — maintain backward compat on response shape.
Idempotency: For batch, generate one idempotency key per task (server-side), not one for the whole batch.
Step 4: Wire resolver dispatch into the edge function
Scope: Small
Add a resolver registry (resolvers/registry.ts) mapping family names to resolver functions.
Inindex.ts, after auth/ownership: if body.family exists, dispatch to resolver; else fall through to existing raw path.
PassResolverContext with supabaseAdmin, finalProjectId, aspectRatio (from the extended project query), and logger.
Step 5: Validate foundation with a smoke test
Scope: Small
Write a test in supabase/functions/create-task/resolvers/__tests__/ that exercises the resolver dispatch path with a minimal mock resolver.
Scope: Large — complex orchestrator payload (~450 lines, families/joinClips/index.ts)
Createresolvers/joinClips.ts:
Port normalizeJoinClipsParams(), buildJoinClipsPayload(), all helper functions.
Port TASK_DEFAULTS (derived from joinClipsSettings.defaults).
Port buildPhaseConfigWithLoras() and VACE defaults.
Port task family contract building (buildJoinClipsFamilyContract, composeTaskFamilyPayload).
Input: CanonicalJoinClipsTaskInput shape.
Portsrc/shared/lib/tasks/core/taskFamilyContracts.ts and src/shared/lib/tasks/taskPayloadContract.ts to server-side shared utilities (needed by joinClips and travelBetweenImages).
Complex families (Steps 12-13) exercise payload composition and contract building.
DB-query families (Steps 14-16) are highest risk — need server-side RPC/query access.
Cleanup (Steps 17-20) only after ALL families are migrated and validated.
Validation Order
After each resolver: compare DB task params with pre-migration snapshot for same input.
After Phase 2: deploy to staging, run upscale + video enhance manually.
After Phase 3: verify batch creates correct row count.
After Phase 5: verify travel segment routing + parent generation creation work server-side.
After Phase 6: TypeScript compilation, full manual test pass.
Risk Assessment
Highest risk: Travel between images payload builder (380 lines of nuanced logic with legacy field handling). Mitigated by: porting line-by-line, comparing output snapshots.
Medium risk: DB queries in resolvers (segment generation routing). Mitigated by: same RPCs/queries, just using supabaseAdmin instead of client Supabase.
Low risk: Simple families (upscale, video enhance). Straightforward port.
Edge function size: Adding ~2500 lines of resolver code. Deno edge functions have no hard size limit but cold start matters. Mitigated by: lazy-loading resolvers (dynamic import per family).
code
Plan metadata:
{
"version": 1,
"timestamp": "2026-03-25T23:01:47Z",
"hash": "sha256:a6b8b6abdfc556f8ebd222934f5844c4f1e1b1353e0508794d8b07eff20ea8a7",
"questions": [
"Should the taskParamsUtils.ts display/analysis functions (used by UI to parse task params for display in TasksPane, SegmentCard, etc.) remain client-side or also move? They read FROM task params, not write them, so likely stay \u2014 but confirming since the file references task-family-specific field names.",
"For the travel orchestrator's ensureShotParentGenerationId() \u2014 this calls a DB RPC that may CREATE a generation record. Moving this to the edge function means generation creation happens server-side. Is that acceptable, or should the client still handle parent generation creation before calling the edge function?",
"The generateVideoService.ts in the travel tool does complex pre-processing (fetching fresh shot_generations from DB, building image payloads from timeline/batch/by-pair modes, resolving model specs) that is UI-state-dependent. How much of this orchestration should move server-side vs. remain as client-side pre-processing that feeds into the resolver input?",
"Should the new API support the old raw { params, task_type } request shape permanently (for external API/PAT consumers) or only as a transitional bridge during migration?",
"For batch responses, should the edge function return parentGenerationId (needed by travel between images callers like generateVideoService.ts) in the response, or should callers that need it query for it after task creation?"
],
"success_criteria": [
"TypeScript compiles with zero errors after all client-side param-building code is deleted",
"Every resolver produces task params byte-identical (or semantically equivalent) to the pre-migration client-side output for the same input \u2014 verified by snapshot comparison",
"Batch requests create exactly N task rows from a single HTTP request (verified in DB)",
"All 10+ task families work end-to-end: UI action \u2192 edge function resolver \u2192 correct DB row \u2192 worker processes successfully \u2192 generation appears in UI",
"No client-side file in src/shared/lib/tasks/families/, src/shared/lib/tasks/travelBetweenImages/, or src/shared/lib/tasks/imageEditing/ exists after cleanup",
"Edge function cold start time does not regress by more than 500ms (measured via Supabase logs)",
"Resolution calculation produces identical results server-side (verified by logging both client and server results during migration overlap)",
"The create-task edge function handles validation errors with clear 400 responses including field-level error details (matching current client-side TaskValidationError behavior)"
],
"assumptions": [
"'6 task families' refers to the 6 directories in src/shared/lib/tasks/families/ (imageGeneration, imageUpscale, individualTravelSegment, joinClips, videoEnhance, zImageTurboI2I). Non-family creators (travelBetweenImages, magicEdit, maskedEdit, crossfadeJoin) are also in scope per 'ALL task creation logic'.",
"No backward compatibility needed means we can change the create-task request schema and deploy client+server together (no rolling deploy concern).",
"'Batch support inside edge function' means a single HTTP request can create multiple tasks (array insert), replacing the current client-side Promise.allSettled pattern.",
"'Travel orchestrator creates only orchestrator task' describes the current behavior (it already creates one task). The change is that payload building moves server-side.",
"Workers are NOT changed \u2014 resolver output must produce params blobs identical to what workers currently expect.",
"The Deno edge function runtime can handle the additional resolver code without hitting memory/timeout limits (current function is ~250 lines; will grow to ~3000+ lines across resolver files).",
"Client-side UI state processing (e.g., timeline mode \u2192 image pairs in generateVideoService.ts) stays client-side; only the param building/validation/resolution/ID generation moves.",
"The taskPayloadContract.ts and taskFamilyContracts.ts contract system (used by joinClips and travelBetweenImages) will be ported to server-side shared code since these contracts are part of the param-building pipeline.",
"External API consumers using PATs currently send raw { params, task_type } \u2014 the old path can be removed since the user said no backward compat needed, but this affects any external integrations."
],
"structure_warnings": [
"Each step section should reference at least one file in backticks."
]
}
code
Plan structure warnings from validator:
[
"Each step section should reference at least one file in backticks."
]
code
Existing flags:
[]
Known accepted debt grouped by subsystem:
{}
Escalated debt subsystems:
[]
Debt guidance:
These are known accepted limitations. Do not re-flag them unless the current plan makes them worse, broadens them, or fails to contain them.
Prefix every new concern with a subsystem tag followed by a colon, for example Timeout recovery: retry backoff remains brittle.
When a concern is recurring debt that still needs to be flagged, prefix it with Recurring debt: after the subsystem tag, for example Timeout recovery: Recurring debt: retry backoff remains brittle.
code
Requirements:
- Consider whether the plan is at the right level of abstraction.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids` should list previously addressed flags that now appear resolved.
- Focus on concrete issues that would cause real problems.
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Verify that the plan remains aligned with the user's original intent.
- Verify that the plan follows the expected structure: one H1 title, `## Overview`, numbered step sections (`### Step N:` under `## Phase` headers, or flat `## Step N:`) with file references and numbered substeps, plus `## Execution Order` or `## Validation Order`.
- Missing required sections or step coverage (for example: no H1, no `## Overview`, or no step sections at all) should be flagged as category `completeness` with severity_hint `likely-significant`.
- Structural formatting within steps (for example: prose instead of numbered substeps, or a missing file reference inside an otherwise actionable step) should usually be category `completeness` with severity_hint `likely-minor` because the executor can still follow the instructions.
- Ask whether the plan is the simplest approach that solves the stated problem, whether it could use fewer steps or less machinery, and whether it introduces unnecessary complexity.
- Over-engineering concerns should use category `maintainability`, should usually prefix the concern with "Over-engineering:", and should scale severity_hint to the practical impact.
- Flag scope creep explicitly when the plan grows beyond the original idea or recorded user notes. Use the phrase "Scope creep:" in the concern.
- Assign severity_hint carefully. Implementation details the executor will naturally resolve should usually be `likely-minor`.
{"flags":[{"id":"task-api-remaining-raw-callers","concern":"Task API: Step 17 removes the raw createTask({ project_id, task_type, params }) path before migrating all existing direct callers.","category":"completeness","severity_hint":"likely-significant","evidence":"The repo still has raw createTask(...) task creators outside the listed 6 families + 4 outliers: src/domains/media-lightbox/hooks/modes/useVideoEditing.ts:105, src/tools/edit-video/hooks/useReplaceMode.ts:337, and src/tools/character-animate/lib/characterAnimate.ts:127. Following the plan as written would break those paths while claiming a clean migration of every caller."},{"id":"travel-module-delete-scope-creep","concern":"Travel contracts: Scope creep: deleting src/shared/lib/tasks/travelBetweenImages/ would remove shared read-side contracts and helpers, not just task creation code.","category":"maintainability","severity_hint":"likely-significant","evidence":"src/shared/lib/tasks/travelBetweenImages/index.ts:1-31 re-exports types/defaults/read helpers like resolvePrimaryStructureVideo, and those are consumed across UI code such as src/tools/travel-between-images/components/SharedGenerationView.tsx:22 and src/shared/components/SegmentSettingsForm/segmentSettingsUtils.ts:2-6. The directory is not creation-only, so deleting it is broader than the stated migration."},{"id":"family-types-relocation-missing","concern":"Family exports: deleting all of src/shared/lib/tasks/families/ is incomplete because several family modules are used as shared type surfaces, not only as task builders.","category":"completeness","severity_hint":"likely-significant","evidence":"src/shared/components/ImageGenerationForm/types.ts:2 imports ReferenceMode from @/shared/lib/tasks/families/imageGeneration and re-exports family API types at :136+; src/shared/components/modals/ImageGenerationModal.tsx:10,44-56 imports both createBatchImageGenerationTasks and BatchImageGenerationTaskParams; src/shared/components/SegmentSettingsForm/segmentSettingsUtils.ts:6 imports IndividualTravelSegmentParams. The plan names a few call-site rewrites, but not relocation of these shared types/contracts."},{"id":"response-contract-update-missing","concern":"Response handling: the planned batch and travel response shape changes are not wired through the existing client parsing and placeholder lifecycle.","category":"correctness","severity_hint":"likely-significant","evidence":"src/shared/lib/taskCreation/parseTaskCreationResponse.ts:24-40 only accepts a single task_id. src/shared/hooks/tasks/useTaskPlaceholder.ts:33-64 only extracts IDs from task_id or arrays of { task_id }, not { task_ids: string[] }. Also src/shared/lib/tasks/travelBetweenImages/createTravelBetweenImagesTask.ts:94-103 currently gets parentGenerationId from client-side preparation, so Step 15's server-returned parentGenerationId needs an explicit parsing path that the plan does not cover."},{"id":"cleanup-shared-utils-overreach","concern":"Cleanup inventory: Step 18 proposes deleting shared client utilities that are still used outside the task-building flow.","category":"completeness","severity_hint":"likely-significant","evidence":"src/shared/lib/taskCreation/resolution.ts:33 is still used by reference-processing flows in src/shared/components/ImageGenerationForm/hooks/referenceUpload/referenceDomainService.ts:8,79-80 and src/domains/media-lightbox/hooks/useReferences.ts:10,76. src/shared/lib/taskCreation/ids.ts:1-19 is also used outside task creation, e.g. src/tools/video-editor/data/SupabaseDataProvider.ts:2,137. src/shared/lib/tasks/segmentGenerationPersistence.ts:71-80 still exports persistSegmentEnhancedPrompt, which is imported by src/domains/media-lightbox/components/submitSegmentTask.ts:24."},{"id":"batch-idempotency-design-gap","concern":"Batch idempotency: the batch insert design does not match the current edge function's [REDACTED] logic.","category":"correctness","severity_hint":"likely-significant","evidence":"Current duplicate recovery in supabase/functions/create-task/index.ts:158-178 assumes one insert, one idempotency_key, and one .single() recovery query. A multi-row .insert(array) with per-task keys can fail the whole batch on one unique-key conflict, and the current recovery path cannot map that failure back to multiple existing task IDs. The plan says 'one idempotency key per task' but does not specify conflict handling or partial recovery semantics."}],"verified_flag_ids":[],"disputed_flag_ids":[]}
You are an independent reviewer. Critique the plan against the actual repository.
Migrate ALL task creation logic into create-task edge function: move param building, defaults, validation, resolution calc, LoRA formatting, ID generation from 6 client-side task families into server-side resolvers. Batch support inside edge function. Travel orchestrator creates only orchestrator task. No backward compat needed. Clean migration of every caller, remove all client-side param building code.
code
Plan:
# Implementation Plan: Migrate ALL Task Creation Logic to Server-Side Resolvers
Overview
Current state: The create-task edge function (supabase/functions/create-task/) is intentionally thin — it authenticates, checks project ownership, and INSERTs an opaque params blob into the tasks table. All validation, default application, resolution calculation, LoRA formatting, ID generation, seed normalization, and payload composition happens client-side across ~15 files in src/shared/lib/tasks/ and src/shared/lib/taskCreation/.
Goal: Move all param-building logic into server-side "resolvers" inside the edge function. Clients send raw/minimal inputs; the server does validation, defaults, resolution lookup, LoRA formatting, ID generation, and final payload composition. Add batch support (N tasks from 1 request). No backward compatibility needed.
Scope: 6 task families in src/shared/lib/tasks/families/ plus 4 non-family creators (travelBetweenImages, magicEdit, maskedEdit, crossfadeJoin) plus 3 direct createTask() callers (editVideoOrchestrator ×2, characterAnimate). ~2500 lines of client-side param-building logic to move. ~15 caller hooks/services to simplify.
Constraints:
Edge function runs in Deno (Supabase Edge Functions). No access to Vite, React, or browser APIs.
Edge function already has supabaseAdmin — can do DB queries (resolution lookup, parent generation, segment routing) more cleanly than client.
Workers expect specific params shapes — resolver output must match current worker expectations exactly.
Batch tasks currently fire N parallel HTTP requests; new batch support = single request → N inserts.
Read-side helpers, UI types, and defaults exported from task modules must be preserved and relocated, not deleted.
Shared utilities (resolveProjectResolution, generateUUID) used outside task creation must remain client-accessible.
Key DB queries that move server-side:
resolveProjectResolution() — queries projects.aspect_ratio (already queried for ownership check — can piggyback)
ResolverContext: { supabaseAdmin, projectId, aspectRatio, logger } — shared deps injected into every resolver
ResolverResult: { tasks: TaskInsertObject[], meta?: Record<string, unknown> } — one or more tasks to insert, plus optional response metadata (e.g., parentGenerationId for travel)
Decision: Keep the existing raw { params, task_type } path alive during migration (feature-flagged by presence of family field), so families can be migrated one at a time without coordinating client+server deploys.
Port resolution lookup into resolvers/shared/resolution.ts:
Reuse the project query the edge function already makes for ownership — extend it to select('user_id, aspect_ratio') instead of select('user_id') (supabase/functions/create-task/index.ts:120).
Port ASPECT_RATIO_TO_RESOLUTION map (from src/shared/lib/media/aspectRatios.ts).
Port model-specific resolution scaling (e.g., 1.5x for qwen-image models from families/imageGeneration/index.ts:39-69).
Port ID generation into resolvers/shared/ids.ts:
generateTaskId(prefix), generateRunId(), generateUUID() — from src/shared/lib/taskCreation/ids.ts.
Port seed utilities into resolvers/shared/seed.ts:
resolveSeed32Bit(), validateSeed32Bit() — from src/shared/lib/taskCreation/schemaUtils.ts.
Port LoRA formatting into resolvers/shared/loras.ts:
mapPathLorasToStrengthRecord() — from src/shared/lib/taskCreation/schemaUtils.ts.
validateLoraConfigs() — same source.
Port hires fix builder into resolvers/shared/hiresFix.ts:
buildHiresFixParams() — from src/shared/lib/taskCreation/hiresFix.ts.
Port lineage fields into resolvers/shared/lineage.ts:
setTaskLineageFields() — from src/shared/lib/taskCreation/payloadFields.ts.
Port validation utilities into resolvers/shared/validation.ts:
validateRequiredFields(), validateNonEmptyString(), validateUrlString(), validateNumericRange(), TaskValidationError — from src/shared/lib/taskCreation/.
Step 3: Add batch insert support to edge function (supabase/functions/create-task/index.ts)
Scope: Medium
Implement batch insert as a loop of individual inserts, not a single .insert(array) call. Rationale: the existing idempotency recovery logic (index.ts:164-218) catches 23505 unique-key violations per-insert and recovers the existing task ID. A multi-row insert would fail the entire batch on any single duplicate, with no way to recover individual task IDs.
Each iteration: call supabaseAdmin.from('tasks').insert(singleObject).select('id').single(), with the existing duplicate-recovery path. Collect results into { task_ids: string[], deduplicated: boolean[] }.
Server generates one idempotency key per task (via generateUUID() from Step 2). Client no longer sends idempotency keys.
Return shape:{ task_ids: string[], status: "Tasks queued", meta?: Record<string, unknown> } for batch; { task_id: string, status: "Task queued", meta?: Record<string, unknown> } for single-task resolvers. The meta field carries resolver-specific data (e.g., parentGenerationId).
ExtendparseTaskCreationResponse() (parseTaskCreationResponse.ts:14-43) to handle the new batch response shape:
If payload.task_ids is a string array, return a new BatchTaskCreationResult type with task_ids and optional meta.
Keep existing single task_id path for backward compat during migration.
ExtendextractTaskIds() in useTaskPlaceholder.ts:43-65 to handle { task_ids: string[] } — add a branch: if result has task_ids array, return it directly.
Addmeta extraction to parseTaskCreationResponse() so callers can read parentGenerationId from the response (needed by travel between images callers like generateVideoService.ts:~line 320).
Step 5: Wire resolver dispatch into the edge function (supabase/functions/create-task/index.ts, supabase/functions/create-task/resolvers/registry.ts)
Scope: Small
Add a resolver registry (resolvers/registry.ts) mapping family names to resolver functions.
Inindex.ts, after auth/ownership: if body.family exists, dispatch to resolver; else fall through to existing raw path.
PassResolverContext with supabaseAdmin, finalProjectId, aspectRatio (from the extended project query), and logger.
Step 6: Validate foundation with a smoke test (supabase/functions/create-task/resolvers/__tests__/)
Scope: Small
Write a test that exercises the resolver dispatch path with a minimal mock resolver.
Verify batch insert with idempotency recovery returns correct task IDs.
VerifyparseTaskCreationResponse handles both single and batch shapes.
Phase 2: Type Relocation — Preserve Shared Type Surfaces
MoveReferenceMode, ReferenceApiParams, BatchImageGenerationTaskParams type definitions from families/imageGeneration/types.ts to src/shared/types/imageGeneration.ts (a new types-only file, no logic).
Scope: Large — complex orchestrator payload (~450 lines, families/joinClips/index.ts)
Createresolvers/joinClips.ts:
Port normalizeJoinClipsParams(), buildJoinClipsPayload(), all helper functions.
Port TASK_DEFAULTS (derived from joinClipsSettings.defaults).
Port buildPhaseConfigWithLoras() and VACE defaults.
Port task family contract building (buildJoinClipsFamilyContract, composeTaskFamilyPayload).
Input: CanonicalJoinClipsTaskInput shape (types already relocated in Step 9).
Portsrc/shared/lib/tasks/core/taskFamilyContracts.ts and src/shared/lib/tasks/taskPayloadContract.ts to server-side shared utilities (needed by joinClips and travelBetweenImages).
Note:segmentGenerationPersistence.ts still exports persistSegmentEnhancedPrompt used by submitSegmentTask.ts:24 — do NOT delete this file. Only the resolveSegmentGenerationRoute function moves server-side.
Scope: Large — most complex payload builder (~380 lines payload + ~110 lines task creator)
Createresolvers/travelBetweenImages.ts:
Port validateTravelBetweenImagesParams() and buildTravelBetweenImagesPayload() from payloadBuilder.ts.
Port ensureShotParentGenerationId() server-side using supabaseAdmin.
Port travel guidance normalization (normalizeTravelGuidance()).
Port legacy structure video validation.
Port task family contract building.
Port DEFAULT_TRAVEL_BETWEEN_IMAGES_VALUES from defaults.ts (only the defaults needed for payload building; read-side defaults stay client-side).
Input: TravelBetweenImagesTaskInput shape.
Output: single task (either travel_orchestrator or wan_2_2_i2v for turbo mode), with meta: { parentGenerationId } in ResolverResult.
Register as 'travel_between_images'.
Update client caller (src/tools/travel-between-images/components/ShotEditor/services/generateVideoService.ts) to read parentGenerationId from response.meta.parentGenerationId instead of from client-side preparation.
Do NOT deletesrc/shared/lib/tasks/travelBetweenImages/ directory. Only delete the task-creation files (createTravelBetweenImagesTask.ts, payloadBuilder.ts). Preserve all read-side helpers:
index.ts — update to remove creation exports, keep re-exports of types/defaults/read helpers
primaryStructureVideo.ts — resolvePrimaryStructureVideo() (26 importers across UI)
structureState.ts — resolveTravelStructureState()
taskTypes.ts — type definitions
uiTypes.ts — StructureVideoConfigWithMetadata
defaults.ts — DEFAULT_STRUCTURE_GUIDANCE_CONTROLS, DEFAULT_STRUCTURE_VIDEO (used by forms)
Createresolvers/crossfadeJoin.ts — port createCrossfadeJoinTask() from src/shared/lib/tasks/createCrossfadeJoinTask.ts.
Register as 'crossfade_join'.
Update callers and delete src/shared/lib/tasks/createCrossfadeJoinTask.ts.
Step 21: Migrate remaining direct createTask() callers
Scope: Medium — 3 direct callers that bypass families
Createresolvers/editVideoOrchestrator.ts:
Port param building from src/domains/media-lightbox/hooks/modes/useVideoEditing.ts:105 and src/tools/edit-video/hooks/useReplaceMode.ts:337.
Both create task_type: 'edit_video_orchestrator' with inline param construction.
Input: the orchestrator params these callers currently build inline.
Createresolvers/characterAnimate.ts:
Port param building from src/tools/character-animate/lib/characterAnimate.ts:127.
Creates task_type: 'animate_character'.
Input: the animation params currently built inline.
Register both as 'edit_video_orchestrator' and 'character_animate'.
Update all 3 callers to use the family-based createTask() path.
Phase 7: Client Cleanup and Finalization
Step 22: Remove raw createTask() path and simplify client (src/shared/lib/taskCreation/createTask.ts)
Scope: Medium
RewritecreateTask() to send family-based requests:
New signature: createTask({ family, project_id, input }).
Remove raw { params, task_type } path — safe because Steps 10-21 migrated ALL callers.
UpdateBaseTaskParams type → TaskCreationRequest with family field (src/shared/lib/taskCreation/types.ts).
Delete client-side pipelines (no longer needed, server validates+builds):
src/shared/lib/tasks/core/taskCreatorPipeline.ts
src/shared/lib/tasks/core/batchTaskPipeline.ts
src/shared/lib/tasks/core/taskRequestComposer.ts
src/shared/lib/tasks/core/taskFieldPolicy.ts
src/shared/lib/tasks/core/taskCreationError.ts
Step 23: Delete migrated task-creation code (families and non-family creators)
Scope: Medium
Delete task-creation logic from src/shared/lib/tasks/families/:
imageGeneration/index.ts, imageGeneration/builders.ts, imageGeneration/validators.ts — keep imageGeneration/types.ts only if not yet fully relocated (should be empty after Step 7; delete entire directory if so).
imageUpscale/ — entire directory (no shared type exports).
individualTravelSegment/index.ts — keep types.ts only if not yet relocated; delete directory if empty after Step 8.
joinClips/ — entire directory (types relocated in Step 9).
videoEnhance/ — entire directory (no shared type exports).
zImageTurboI2I/ — entire directory (no shared type exports).
Delete from src/shared/lib/tasks/travelBetweenImages/:
Complex families (Steps 16-17) exercise payload composition and contract building.
DB-query families + direct callers (Steps 18-21) are highest risk — need server-side RPC/query access.
Cleanup (Steps 22-26) only after ALL callers are migrated and validated.
Validation Order
After each resolver: compare DB task params with pre-migration snapshot for same input.
After Phase 3: deploy to staging, run upscale + video enhance manually.
After Phase 4: verify batch creates correct row count; verify idempotency recovery works per-task.
After Phase 6: verify travel segment routing + parent generation creation work server-side; verify parentGenerationId in response meta.
After Phase 7: TypeScript compilation, full manual test pass across all 12+ task types.
code
Plan metadata:
{
"version": 2,
"timestamp": "2026-03-25T23:12:53Z",
"hash": "sha256:4c650ce1803c762fe8a0b79cac5c824d9ea88c9b069d4c19f050c81b1c458991",
"changes_summary": "Revised plan addresses all 6 significant flags from gate critique:\n\n1. task-api-remaining-raw-callers: Added Step 21 to migrate 3 direct createTask() callers (useVideoEditing.ts, useReplaceMode.ts, characterAnimate.ts) with dedicated resolvers (editVideoOrchestrator, characterAnimate). Raw path removal (Step 24) now happens AFTER all callers are migrated.\n\n2. travel-module-delete-scope-creep: Step 19 now explicitly preserves all read-side helpers (resolvePrimaryStructureVideo, structureState, types, defaults, legacyStructureVideo, segmentImages) \u2014 only deletes createTravelBetweenImagesTask.ts and payloadBuilder.ts. Step 23 mirrors this by only deleting creation files from the directory.\n\n3. family-types-relocation-missing: Added Phase 2 (Steps 7-9) as a dedicated type relocation phase before any family deletion. Relocates ReferenceMode, BatchImageGenerationTaskParams, IndividualTravelSegmentParams, CanonicalJoinClipsTaskInput and related types to src/shared/types/ with all importers updated.\n\n4. response-contract-update-missing: Added Step 4 to extend parseTaskCreationResponse for batch { task_ids } shape, extend extractTaskIds in useTaskPlaceholder, and add meta extraction for parentGenerationId. Travel resolver (Step 19) returns parentGenerationId via meta field.\n\n5. cleanup-shared-utils-overreach: Step 23 now explicitly lists which utilities to keep (resolution.ts, ids.ts, segmentGenerationPersistence.ts) with evidence of non-task callers, and which to delete (hiresFix.ts, payloadFields.ts, payloadMapping.ts, arrayUtils.ts, batchResults.ts) because they have no callers outside task creation.\n\n6. batch-idempotency-design-gap: Step 3 redesigned batch insert to use a loop of individual inserts (not array insert), reusing the existing per-insert duplicate-recovery logic. Server generates idempotency keys. Each task gets independent conflict handling.",
"flags_addressed": [
"task-api-remaining-raw-callers",
"travel-module-delete-scope-creep",
"family-types-relocation-missing",
"response-contract-update-missing",
"cleanup-shared-utils-overreach",
"batch-idempotency-design-gap"
],
"questions": [
"Should the taskParamsUtils.ts display/analysis functions (used by UI to parse task params for display in TasksPane, SegmentCard, etc.) remain client-side or also move? They read FROM task params, not write them, so likely stay \u2014 but confirming since the file references task-family-specific field names.",
"For the travel orchestrator's ensureShotParentGenerationId() \u2014 this calls a DB RPC that may CREATE a generation record. Moving this to the edge function means generation creation happens server-side. Is that acceptable, or should the client still handle parent generation creation before calling the edge function?",
"The in the travel tool does complex pre-processing (fetching fresh shot_generations from DB, building image payloads from timeline/batch/by-pair modes, resolving model specs) that is UI-state-dependent. How much of this orchestration should move server-side vs. remain as client-side pre-processing that feeds into the resolver input?"
],
"success_criteria": [
"TypeScript compiles with zero errors after all client-side param-building code is deleted (verified via )",
"Every resolver produces task params semantically equivalent to the pre-migration client-side output for the same input \u2014 verified by snapshot comparison of DB task params",
"Batch requests create exactly N task rows from a single HTTP request (verified in DB)",
"All 12+ task types work end-to-end: UI action \u2192 edge function resolver \u2192 correct DB row \u2192 worker processes successfully \u2192 generation appears in UI (imageGen, upscale, videoEnhance, zImageTurboI2I, magicEdit, maskedEdit, individualTravelSegment, travelBetweenImages, joinClips, crossfadeJoin, editVideoOrchestrator, characterAnimate)",
"No task-creation functions remain in , only relocated type-only files or empty directories",
"Read-side helpers in (resolvePrimaryStructureVideo, types, defaults) remain functional \u2014 all 26+ importers still compile",
"Shared client utilities (resolution.ts, ids.ts) remain accessible to non-task callers (referenceDomainService.ts, SupabaseDataProvider.ts, etc.)",
"Batch idempotency works correctly: re-sending the same batch request returns existing task IDs without creating duplicates",
"Edge function cold start time does not regress by more than 500ms (measured via Supabase logs)",
"The edge function handles validation errors with clear 400 responses including field-level error details",
"Client parseTaskCreationResponse handles both single and batch response shapes",
"Travel between images callers receive via response field"
],
"assumptions": [
"'6 task families' refers to the 6 directories in (imageGeneration, imageUpscale, individualTravelSegment, joinClips, videoEnhance, zImageTurboI2I). Non-family creators (travelBetweenImages, magicEdit, maskedEdit, crossfadeJoin) plus 3 direct callers (editVideoOrchestrator \u00d72, characterAnimate) are also in scope per 'ALL task creation logic'.",
"No backward compatibility needed means we can change the request schema and deploy client+server together (no rolling deploy concern).",
"'Batch support inside edge function' means a single HTTP request can create multiple tasks, replacing the current client-side Promise.allSettled pattern. Implemented as a loop of individual inserts with per-task idempotency recovery.",
"'Travel orchestrator creates only orchestrator task' describes the current behavior (it already creates one task). The change is that payload building moves server-side.",
"Workers are NOT changed \u2014 resolver output must produce params blobs identical to what workers currently expect.",
"The Deno edge function runtime can handle the additional resolver code without hitting memory/timeout limits.",
"Client-side UI state processing (e.g., timeline mode \u2192 image pairs in generateVideoService.ts) stays client-side; only the param building/validation/resolution/ID generation moves.",
"The and contract system will be ported to server-side shared code.",
"Read-side helpers, types, and defaults exported from task modules (travelBetweenImages/, families/) will be preserved and relocated, not deleted with the task-creation logic.",
"Shared utilities used outside task creation (resolution.ts, ids.ts, segmentGenerationPersistence.ts) will remain client-accessible."
],
"structure_warnings": [
"Each step section should reference at least one file in backticks."
],
"delta_from_previous_percent": 35.94
}
code
Plan structure warnings from validator:
[
"Each step section should reference at least one file in backticks."
]
code
Existing flags:
[
{
"id": "task-api-remaining-raw-callers",
"concern": "Task API: Step 17 removes the raw createTask({ project_id, task_type, params }) path before migrating all existing direct callers.",
"status": "addressed",
"severity": "significant"
},
{
"id": "travel-module-delete-scope-creep",
"concern": "Travel contracts: Scope creep: deleting src/shared/lib/tasks/travelBetweenImages/ would remove shared read-side contracts and helpers, not just task creation code.",
"status": "addressed",
"severity": "significant"
},
{
"id": "family-types-relocation-missing",
"concern": "Family exports: deleting all of src/shared/lib/tasks/families/ is incomplete because several family modules are used as shared type surfaces, not only as task builders.",
"status": "addressed",
"severity": "significant"
},
{
"id": "response-contract-update-missing",
"concern": "Response handling: the planned batch and travel response shape changes are not wired through the existing client parsing and placeholder lifecycle.",
"status": "addressed",
"severity": "significant"
},
{
"id": "cleanup-shared-utils-overreach",
"concern": "Cleanup inventory: Step 18 proposes deleting shared client utilities that are still used outside the task-building flow.",
"status": "addressed",
"severity": "significant"
},
{
"id": "batch-idempotency-design-gap",
"concern": "Batch idempotency: the batch insert design does not match the current edge function's [REDACTED] logic.",
"status": "addressed",
"severity": "significant"
}
]
code
Known accepted debt grouped by subsystem:
{}
Escalated debt subsystems:
[]
Debt guidance:
These are known accepted limitations. Do not re-flag them unless the current plan makes them worse, broadens them, or fails to contain them.
Prefix every new concern with a subsystem tag followed by a colon, for example Timeout recovery: retry backoff remains brittle.
When a concern is recurring debt that still needs to be flagged, prefix it with Recurring debt: after the subsystem tag, for example Timeout recovery: Recurring debt: retry backoff remains brittle.
code
Requirements:
- Consider whether the plan is at the right level of abstraction.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids` should list previously addressed flags that now appear resolved.
- Focus on concrete issues that would cause real problems.
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Verify that the plan remains aligned with the user's original intent.
- Verify that the plan follows the expected structure: one H1 title, `## Overview`, numbered step sections (`### Step N:` under `## Phase` headers, or flat `## Step N:`) with file references and numbered substeps, plus `## Execution Order` or `## Validation Order`.
- Missing required sections or step coverage (for example: no H1, no `## Overview`, or no step sections at all) should be flagged as category `completeness` with severity_hint `likely-significant`.
- Structural formatting within steps (for example: prose instead of numbered substeps, or a missing file reference inside an otherwise actionable step) should usually be category `completeness` with severity_hint `likely-minor` because the executor can still follow the instructions.
- Ask whether the plan is the simplest approach that solves the stated problem, whether it could use fewer steps or less machinery, and whether it introduces unnecessary complexity.
- Over-engineering concerns should use category `maintainability`, should usually prefix the concern with "Over-engineering:", and should scale severity_hint to the practical impact.
- Flag scope creep explicitly when the plan grows beyond the original idea or recorded user notes. Use the phrase "Scope creep:" in the concern.
- Assign severity_hint carefully. Implementation details the executor will naturally resolve should usually be `likely-minor`.
src/shared/lib/taskCreation/schemaUtils.ts — review remaining callers; delete only if all callers are gone.
src/shared/lib/tasks/segmentGenerationPersistence.ts — persistSegmentEnhancedPrompt still used by submitSegmentTask.ts:24. Only resolveSegmentGenerationRoute moved server-side.
Verify no remaining imports reference deleted files (npx tsc --noEmit).