You are an independent reviewer. Critique the plan against the actual repository.
code
Project directory:
/Users/user_c042661f/Documents/reigh-workspace/reigh-app
User intent summary:
The intent is to make the persisted Reigh video editor timeline (TimelineConfig plus AssetRegistry) have one documented, reusable domain interpretation, so UI loading/editing, Remotion rendering, imports, and agent tools stop making their own conflicting decisions about shape, migration, serialization, validation, and duration. This is a foundation sprint: preserve current editor behavior, centralize the domain rules, add targeted tests, and clearly mark any paths that cannot yet be migrated without overreaching.
Original idea:
Video editor developer platform Sprint 1: canonical timeline domain model.
Context:
The Reigh video editor under src/tools/video-editor has useful primitives, but it is not yet easy for developers or agents to build on top of. Current pain points include multiple timeline shapes (TimelineClip, ClipMeta, ResolvedTimelineClip, TimelineData rows/meta/clipOrder), inconsistent duration semantics across UI/render/agent paths, Reigh-specific dependencies mixed into editor provider/components, and mutation paths that require internal knowledge.
This sprint is the first two-week slice. It must preserve the current Reigh app behavior while establishing the domain foundation for later ports/adapters, headless core, clip-type plugins, command bus, render pipeline hooks, and UI slots.
Goal:
Create a canonical timeline domain layer that all current editor paths can use without changing user-visible functionality.
Primary outcomes:
Establish one documented canonical interpretation of persisted TimelineConfig + AssetRegistry.
Centralize repair/migration/canonicalization, duration calculation, validation, serialization, and structured errors.
Remove or reduce divergent duration/shape logic between UI, Remotion renderer, import, and ai-timeline-agent paths.
Prepare for agent-safe editing by defining validation/dry-run-friendly primitives, even if the full command bus ships in a later sprint.
Important constraints:
Do not rewrite the video editor.
Do not change visible editor behavior except to fix clear inconsistencies.
Keep the existing Reigh editor page and shell working.
Keep current tests passing; add targeted tests for canonical domain behavior.
Avoid broad UI refactors in this sprint unless required to route through the domain layer.
Do not make plugin registries or UI slots yet; only shape the domain layer so those later sprints are easier.
UI load repairs/migrates before use, but ai-timeline-agent reads raw DB config.
UI duration helpers and agent timeline tools can interpret clips with missing from/to differently.
Some render paths compute sequence duration manually instead of using shared duration helpers.
Import validation and editor serialization validation may accept/reject different shapes.
Poll sync may advance configVersionRef before accepting polled data, potentially weakening conflict detection.
Pinned shot group metadata is not maintained consistently by backend clip CRUD.
Success criteria:
There is a canonical domain module/API for timeline normalization, duration, validation, and serialization.
UI, renderer, import, and agent paths either use this API or have explicit follow-up tasks for remaining migration.
Tests cover equivalent duration/canonicalization behavior across at least UI/domain and agent/import-adjacent helpers.
Current editor functionality remains intact.
The resulting API is understandable for a later command bus and agent edit layer.
Deliverable:
A code diff plus a concise notes section explaining the canonical domain boundary, remaining non-canonical call sites, and recommended Sprint 2 work.
User notes and answers:
Clarification decisions for Sprint 1: keep canonical domain API local to src/tools/video-editor/domain for now, while aligning with @banodoco/timeline-schema types and leaving package extraction as a later decision. Canonical persistence remains TimelineConfig + AssetRegistry; TimelineData rows/meta/clipOrder stay editor-only projection. Duration rule: define one shared helper that treats hold as explicit duration, otherwise uses from/to when present and may use AssetRegistry duration as a controlled fallback for media clips with missing to; preserve current visible behavior where tests reveal risk and document any mismatch. Canonicalization should return normalized in-memory data plus warnings/repair metadata; persistence may serialize repaired canonical output only on explicit save/import/agent write, not merely on read. Unknown clip types remain accepted with structured warnings and placeholder behavior. Structured errors should be stable and agent-readable with codes, paths, severity, and suggested repair. Pinned shot group consistency and poll-sync configVersion conflict behavior should be included only if low-risk; otherwise produce explicit follow-up tasks. Import and ai-timeline-agent should be planned to use the same canonical helpers; implement the smallest safe migration in Sprint 1 and document remaining raw paths. Validation boundary: hard errors for impossible/unsafe state, warnings for repairable legacy shape, missing optional metadata, unknown future clip types, and missing assets where placeholder behavior exists.
Intent Check
This sprint remains a foundation slice, not a rewrite. The persisted canonical source stays TimelineConfig + AssetRegistry. TimelineData, renderer-resolved clips, rows/meta/clipOrder, and agent command views are projections/adapters. The goal is to centralize interpretation while preserving current editor behavior and documenting any call sites that cannot be safely migrated in this slice.
Phase 0: Baseline and Characterization
Run targeted tests first, then add characterization tests before changing behavior:
bash
npm run test -- src/tools/video-editor/lib/config-utils.test.ts src/tools/video-editor/lib/timeline-data.test.ts src/tools/video-editor/lib/migrate.test.ts src/tools/video-editor/lib/serialize.test.ts src/tools/video-editor/hooks/usePollSync.test.ts src/tools/video-editor/hooks/useTimelineCommit.test.tsx
npm run test:edge:unit -- supabase/functions/timeline-import supabase/functions/ai-timeline-agent
Add characterization coverage for existing load/repair behavior before moving any repair logic:
Duplicate track IDs and duplicate clip IDs, including cascading -dup-N suffix cleanup.
Legacy pinned group children conversion.
repairShotGroupContiguity behavior.
migrateToFlatTracks behavior, including legacy track names and background hold clip injection.
Current UI zero-duration behavior for clips missing to when no registry is available.
Current agent duration behavior for clips missing to when registry duration is available.
These tests decide where Sprint 1 can safely change behavior and where compatibility wrappers must preserve legacy behavior.
Phase 1: Create an Acyclic Domain Boundary
Create src/tools/video-editor/domain/ as the owning layer for canonical interpretation. It must be runtime-safe for both browser/editor tests and Supabase edge function source:
No React imports.
No browser APIs.
No @/ aliases.
No imports from lib/config-utils.ts, lib/timeline-data.ts, hooks, components, or renderer files.
Only import persisted/shared types from src/tools/video-editor/types/index.ts by relative path if needed.
Initial files:
diagnostics.ts: stable TimelineDiagnostic types and codes.
duration.ts: registry-aware and registry-free duration helpers.
repair.ts: lifted repair/migration primitives currently owned by lib/migrate.ts, moved or duplicated only after characterization tests pin behavior.
domain/* owns duration, validation, repair, normalization, and serialization.
lib/config-utils.ts, lib/migrate.ts, lib/serialize.ts, and lib/timeline-data.ts become compatibility/adaptation layers that may import domain/*.
domain/* must never import those lib/* compatibility modules.
Phase 2: Define Duration APIs Without Breaking Existing Callers
Do not force registry fallback through old clip-only helpers. Add two explicit APIs:
getCanonicalClipDurationSeconds(clip, registry, options): registry-aware canonical helper for callers that have AssetRegistry.
getLegacyClipDurationSeconds(clip) or compatibility wrapper behavior through config-utils.ts: preserves existing clip-only semantics where no registry is available.
Canonical duration rule:
hold wins when finite and positive.
Else, finite from and to produce to - from.
Else, for media clips with a registry asset duration, use asset.duration - from when from exists, otherwise asset.duration.
Invalid, missing, or non-positive speed is repaired to 1 with a warning on read and on write for Sprint 1, matching existing UI sanitization behavior and avoiding a new write rejection policy.
Seconds-domain helpers may return 0 where canonical data is incomplete; frame helpers clamp only at render/frame conversion boundaries when a rendered sequence needs at least one frame.
Migration rule:
Callers with only clip keep legacy behavior through compatibility wrappers.
Callers with config + registry move to canonical helpers.
Any call site that cannot receive registry without broad signature churn is listed in the final notes as a remaining non-canonical duration path.
Phase 3: Preserve Existing Repair Semantics
Lift existing repair behavior into domain/repair.ts only after characterization tests are in place. The lifted implementation must preserve current semantics for:
repairConfig duplicate handling.
repairShotGroupContiguity.
migrateToFlatTracks.
Legacy pinned-group conversion.
Legacy track/background behavior.
Compatibility modules should delegate to these domain functions so existing imports continue to work. normalizeTimelineConfig should compose these exact repair steps and attach diagnostics; it should not invent new repair behavior in Sprint 1.
Read behavior remains non-persistent: normalization may repair in memory and report diagnostics, but UI load/poll/read paths must not write repaired data merely because they read it.
Phase 4: Route Editor and Renderer Call Sites Deliberately
First migrate low-risk call sites that already have or can cheaply receive AssetRegistry:
buildTimelineData / row assembly paths where both TimelineConfig and AssetRegistry are available.
Renderer sequence duration calculations in TimelineRenderer.tsx and related Remotion components where resolved clips or registry-backed metadata are available.
Attachment and selected-media helpers if they already have asset registry context.
Keep configToRows(config) signature stable if broad churn is required. Add a registry-aware sibling or options parameter only where call sites can be updated safely, for example configToRows(config, { assetRegistry }), while preserving old behavior when omitted.
Audit and classify all direct duration call sites from rg, including:
Each call site must either use the canonical helper or be documented as intentionally legacy/registry-unavailable with a follow-up. This avoids pretending the migration is complete when it is not.
Phase 5: Route Agent Semantics, Not Just Load/Save
Replace the private registry-aware duration helper in supabase/functions/ai-timeline-agent/tools/timeline.ts with the domain duration helper, but preserve current command behavior unless tests show a clear bug.
Normalize once after DB load, carry diagnostics into findIssues or logs, and serialize through domain serialization before saveTimelineConfigVersioned.
Pin command-level behavior with tests for operations that depend on duration:
splitClip bounds and mutation output.
trimClip validation and mutation output.
duplicateClip placement.
queryTimeline gap/overlap reporting.
findIssues duration-related messages.
selectedClips.ts live timeline duration context.
This is required because duration differences can change agent edits before the save boundary.
Phase 6: Route Import Without Persisting Raw Parsed Shape
Keep @banodoco/timeline-schema validation as the first shape gate, but use its parsed output and the domain serialized output for persistence:
Parse body.timeline with TimelineConfigSchema.safeParse.
Parse or normalize body.asset_registry consistently.
Run domain normalization/validation on parsed timeline plus registry.
Reject hard errors with structured details.
Persist serializeCanonicalTimeline(...) output, not the raw body timeline and not only validated.timeline if that object still reflects raw input.
Warnings may be logged in Sprint 1 to avoid response-contract churn. Exposing warnings in the API response is a Sprint 2/API compatibility decision unless an existing response field already supports it.
Phase 7: Narrow Pinned Groups and Poll Sync
Pinned groups:
Sprint 1 only validates and warns on stale clipIds, missing clips, wrong trackId, stale snapshots, and legacy shapes.
Do not prune clipIds, drop empty groups, or mutate pinned group state during serialization in Sprint 1.
Backend clip CRUD consistency remains a documented follow-up unless a tiny, already-tested fix is discovered during implementation.
Poll sync:
Keep this scoped to the known conflict-detection issue.
Add or update a focused test showing configVersionRef only advances after accepting a polled payload.
Implement the fix only if it is localized to usePollSync.ts and does not require broader persistence refactoring. Otherwise, leave code unchanged and record the test/follow-up explicitly.
Tests To Add or Update
src/tools/video-editor/domain/duration.test.ts: hold, from/to, missing to with registry fallback, missing registry legacy behavior, invalid speed repair, frame clamping.
src/tools/video-editor/domain/repair.test.ts: lifted existing repair/migration semantics exactly match current behavior.
src/tools/video-editor/domain/normalize.test.ts: diagnostics for repaired legacy shape, duplicate IDs, missing assets, unknown clip types, pinned group stale refs, no persistence on read.
src/tools/video-editor/domain/serialize.test.ts: explicit write serialization preserves allowed extras/theme metadata and does not prune pinned groups in Sprint 1.
Existing UI tests for timeline-data, config-utils, serialize, renderer-derived duration, and poll sync.
Edge tests for timeline-import/handler.test.ts, ai-timeline-agent/tools/timeline.test.ts, and selectedClips.test.ts, including command-level duration behavior.
Observable Success Criteria
A documented public domain API exists under src/tools/video-editor/domain and has no React/browser/Vite-alias dependencies.
TimelineConfig + AssetRegistry are documented and tested as the canonical persisted source; TimelineData and resolved renderer/agent views are documented projections.
Existing repair/migration semantics are characterized and preserved through the new domain boundary.
Registry-aware duration helpers are used wherever callers have registry context; registry-free compatibility wrappers preserve legacy behavior where signature churn would be unsafe.
UI, renderer, import, and agent paths either use shared domain helpers or are explicitly listed as remaining non-canonical call sites with reasons.
Agent command tests pin duration-sensitive behavior for split, trim, duplicate, query, and issue detection.
Timeline import persists domain-serialized canonical output after schema parse and domain validation, rather than raw request shape.
Read/load normalization returns diagnostics and does not mutate DB state or advance versions by itself.
Explicit save/import/agent writes serialize through the canonical boundary.
Pinned group mutation is limited to diagnostics in Sprint 1; destructive pruning is deferred.
Targeted tests pass, followed by broader npm run test and npm run test:edge:unit when runtime is acceptable.
code
Plan metadata:
{
"version": 2,
"timestamp": "2026-05-02T17:04:38Z",
"hash": "sha256:81ab3ae5072a5acd555847dbe78bb4823943791661f0b2a56936503b2e7f8e9b",
"changes_summary": "Narrowed the plan back to a foundation sprint by removing destructive pinned-group pruning and deferring API response warning changes unless already supported. Made the domain layering acyclic by moving repair ownership into domain/repair.ts before compatibility wrappers delegate to it. Resolved the duration API mismatch by separating registry-aware canonical helpers from registry-free legacy wrappers, and by requiring an audit/classification of all direct duration call sites. Clarified edge-runtime constraints so the domain cannot depend on Vite aliases or browser/UI modules. Resolved invalid speed policy for Sprint 1 as repair-to-1 with diagnostics on both read and write, matching current UI sanitization. Tightened import migration so parsed/domain-serialized data is what gets persisted. Expanded agent tests from generic duration coverage to command-level behavior where duration changes can affect mutations.",
"flags_addressed": [
"R1",
"R2",
"R3",
"R4",
"R5",
"R7",
"R8",
"R9",
"R10"
],
"questions": [
"Should import warnings remain log-only for Sprint 1 unless an existing response field can carry them without API churn?",
"For registry-unavailable UI call sites, is documenting legacy duration behavior acceptable for Sprint 1 if changing signatures would touch broad UI editing surfaces?"
],
"success_criteria": [
"Domain API exists under src/tools/video-editor/domain with documented canonical persistence/projection boundary and no UI/runtime-incompatible dependencies.",
"Existing repair and migration semantics are characterized by tests and preserved through the new domain boundary.",
"Shared registry-aware duration helpers are used by UI/render/agent/import paths that have registry context; remaining registry-free call sites are documented with reasons.",
"Normalization returns structured diagnostics and does not persist repairs on read.",
"Explicit save/import/agent writes serialize through the canonical boundary, and import persists serialized canonical output rather than raw request shape.",
"Agent command tests cover duration-sensitive split, trim, duplicate, query, issue detection, and selected-clip behavior.",
"Pinned group handling in Sprint 1 is validation/diagnostics only, with destructive cleanup deferred.",
"Targeted UI and edge tests cover duration fallback, normalization diagnostics, serialization, repair preservation, import persistence, and agent consistency."
],
"assumptions": [
"Existing UI behavior is the compatibility baseline unless characterization tests reveal a clear inconsistency that can be fixed safely.",
"Some old clip-only helpers will remain as compatibility wrappers in Sprint 1 because adding AssetRegistry everywhere would create broad signature churn.",
"Supabase edge function runtime can import relative TypeScript source already used by the repo, but cannot rely on Vite-only aliases or browser-facing modules.",
"Invalid speed <= 0 should be repaired to 1 with diagnostics in Sprint 1 to preserve current behavior and avoid introducing new write failures.",
"Pinned shot group data should not be destructively repaired until backend CRUD consistency is addressed deliberately."
],
"delta_from_previous_percent": 85.86
}
code
Existing flags:
[
{
"id": "R1",
"concern": "The duration migration plan does not resolve the registry-fallback API mismatch for existing UI callers. config-utils.ts helpers currently accept only a clip, and configToRows(config) also has no registry parameter, so simply delegating old helpers to domain helpers would either preserve the current zero-duration fallback or require broad signature changes that the plan does not spell out.",
"status": "addressed",
"severity": "significant"
},
{
"id": "R2",
"concern": "The proposed domain layering can easily create import cycles unless repair/migration code is moved into the domain first. The plan says config-utils.ts should delegate to domain/duration.ts, while existing migrate.ts imports config-utils.ts; if domain/normalize.ts reuses repairConfig, repairShotGroupContiguity, or migrateToFlatTracks from lib/migrate.ts, the new domain will depend back on compatibility wrappers.",
"status": "addressed",
"severity": "significant"
},
{
"id": "R3",
"concern": "The plan misses several concrete duration call sites, so divergent interpretation would likely remain after Sprint 1. It names useDerivedTimeline and TimelineRenderer, but the repository also computes durations in provider/shell/preview/attachment/editor helpers and the agent selection path.",
"status": "addressed",
"severity": "significant"
},
{
"id": "R4",
"concern": "The edge-function import strategy is under-specified for production deployment. Vitest has an @ alias for edge tests, but Supabase function source currently imports app types by relative path; a domain module imported at runtime by edge functions cannot rely on Vite-only aliases or browser-facing editor modules.",
"status": "addressed",
"severity": "significant"
},
{
"id": "R5",
"concern": "The plan does not preserve the existing repair semantics explicitly enough. Current load behavior deduplicates tracks, strips cascading -dup-N clip suffixes, drops duplicate base clip IDs, converts legacy pinned-group children, repairs shot-group contiguity, and migrates legacy tracks/background clips. Replacing that with a generic normalizeTimelineConfig risks visible data changes unless those exact behaviors are lifted and characterized first.",
"status": "addressed",
"severity": "significant"
},
{
"id": "R6",
"concern": "Scope creep: putting asset URL resolution and ResolvedTimelineConfig projection inside the canonical domain boundary risks expanding this sprint into provider/render adapter work. URL resolution is async and provider-specific, while the stated canonical persistence contract is TimelineConfig + AssetRegistry; making resolve.ts part of the public domain API could couple the domain to render/runtime concerns instead of keeping it as a pure persisted-data interpretation layer.",
"status": "open",
"severity": "minor"
},
{
"id": "R7",
"concern": "Scope creep: pruning pinned shot groups during serialization can cause data loss and goes beyond the low-risk validation/documentation target. The repo already has complex pinned-group legacy repair and contiguity behavior; deleting missing clip IDs or dropping empty groups on every explicit write may remove backend state that current CRUD paths failed to maintain, making the canonical layer mask rather than solve the inconsistency.",
"status": "addressed",
"severity": "significant"
},
{
"id": "R8",
"concern": "The write-validation policy for invalid speed remains unresolved, but this affects both render safety and agent edits. The plan simultaneously says invalid speed defaults to with a warning and asks whether should be hard-error on write; without a decided boundary, different paths can still accept, repair, or reject the same clip differently.",
"status": "addressed",
"severity": "significant"
},
{
"id": "R9",
"concern": "The import migration plan must account for the current handler validating with Zod but persisting the raw body object. If the implementation only adds domain validation after and continues passing into insert/RPC, schema-normalized or canonical-serialized output will not actually be what gets stored.",
"status": "addressed",
"severity": "significant"
},
{
"id": "R10",
"concern": "The plan treats agent normalization as mostly a load/save wrapper, but several agent operations compute durations before save and can change command behavior. , , , , and all depend on timeline duration; tests need to pin their result strings and mutation outputs, not just or a generic duration helper.",
"status": "addressed",
"severity": "significant"
}
]
code
Requirements:
- 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: thorough. Be exhaustive. Flag edge cases, missing error handling, performance concerns, and anything that could cause problems in production even if unlikely.
- Verify that the plan remains aligned with the user's original intent (above), not just internal plan quality.
- Flag scope creep explicitly when the plan grows beyond the original idea or recorded user notes. Use the phrase "Scope creep:" in the concern so the orchestrator can surface it.
- Do not rubber-stamp the plan.
- Assign severity_hint carefully: "likely-significant" for issues that would
cause real product or implementation problems. "likely-minor" for cosmetic,
nice-to-have, issues already covered elsewhere, or implementation details
the executor will naturally resolve by reading the actual code (e.g. exact
line numbers, missing boilerplate, export lists).
{"flags":[{"id":"R11","concern":"The plan says explicit UI saves should serialize through the canonical boundary, but it does not name the actual save boundary that currently persists nextData.config directly. In useTimelinePersistence.ts, doSave calls provider.saveTimeline(timelineId, config: nextData.config, expectedVersion, registry); several edit paths construct config through rowsToConfig or serializeForDisk, but others can assemble/migrate data and still leave nextData.config as the persisted object. Without routing doSave or DataProvider.saveTimeline through domain serialization, Sprint 1 can still have non-canonical UI writes even if import and agent writes are fixed.","category":"completeness","severity_hint":"likely-significant","evidence":"src/tools/video-editor/hooks/useTimelinePersistence.ts passes nextData.config directly into provider.saveTimeline; the plan migrates rows/config adapters but does not explicitly add a save-boundary guard/test for this path."},{"id":"R12","concern":"The AssetRegistry half of the canonical persisted source is still under-specified. The plan mentions parsing or normalizing body.asset_registry, but the concrete domain files/tests focus on timeline clips, duration, pinned groups, and serialization; there is no explicit registry schema/diagnostic policy for invalid assets entries, non-string file, non-finite/negative duration, bad type, or preserving unknown registry metadata. Since duration fallback and render URL resolution depend on registry entries, this can leave import, UI, and agent paths sharing a timeline config interpretation while still diverging on asset registry interpretation.","category":"completeness","severity_hint":"likely-significant","evidence":"Current supabase/functions/timeline-import/validate.ts only checks that asset_registry.assets[key] is an object. Current resolveTimelineConfig skips assets without valid file, while agent duration reads registry.assets[id].duration directly. The plan does not specify stable diagnostics/tests for malformed registry entries."},{"id":"R13","concern":"Agent write repair can make tool results lie unless the plan includes a post-mutation validation/repair feedback step. The plan decides invalid speed <= 0 is repaired to 1 on write, while current agent setClipProperty delegates numeric speed edits and returns success strings based on the requested value. If domain serialization silently repairs speed: 0 to 1, the LLM/user can see “Set speed ... to 0” while the persisted timeline contains 1; similar issues can happen for other repaired fields. The plan should require command results or diagnostics to reflect write-time repairs, not just serialize before saveTimelineConfigVersioned.","category":"correctness","severity_hint":"likely-significant","evidence":"supabase/functions/ai-timeline-agent/tools/timeline.tssetClipProperty accepts any numeric value through @banodoco/timeline-ops and formats the result from args.value; the plan says invalid speed is repaired to 1 with diagnostics on write but does not say those diagnostics affect agent tool output."}],"verified_flag_ids":["R1","R2","R3","R4","R5","R7","R8","R9","R10"],"disputed_flag_ids":["R6"]}