Answers to planner questions: Q1: Implement tools from the TypeScript type definitions - the Python tools are reference implementations but the logic is straightforward JSON manipulation. Q2: Floating drawer/panel on the right side, collapsible - similar to a chat sidebar. Don't replace properties panel. Q3: Yes include create_generation_task but as a simple pass-through to existing createTask - it just queues the task, doesn't need complex logic. Include it in v1. Q4: Auto-re-invoke immediately with a small delay (~300ms). Show 'Agent is thinking...' spinner but don't require user intervention - the continuation should be seamless.
Build an AI-powered timeline editing agent that operates through a turn-based conversation model. The agent runs as a Supabase Edge Function (ai-timeline-agent), reads/writes timeline config via JSONB in the existing timelines table, and communicates with users through a chat UI embedded in VideoEditorShell. Sessions are stored in a new timeline_agent_sessions table with optimistic locking. Groq handles fast LLM calls; Claude Sonnet handles complex reasoning. Voice input reuses extracted Whisper transcription.
Current repo shape:
timelines table exists (supabase/migrations/20260325090000) with config JSONB, asset_registry JSONB, RLS, and realtime enabled. No config_version column yet.
SupabaseDataProvider reads/writes timeline config via Supabase client.
ai-voice-prompt edge function has Groq Whisper transcription (lines 96-104) tightly coupled with prompt enhancement.
bootstrapEdgeHandler / withEdgeRequest provide standard edge function scaffolding.
useVoiceRecording hook handles browser audio capture, submits to ai-voice-prompt.
VideoEditorShell is a 3-panel layout (preview, properties, timeline) with realtime conflict detection.
useTimelineRealtime subscribes to timelines-updated realtime events.
Python tools (place.py, view.py, common.py) contain the clip manipulation logic to port — not readable from this repo, will need user to provide or copy in.
Key constraints:
Edge functions are stateless — DB is the continuity mechanism.
Edge function timeout is ~60s (Supabase default), so agent must checkpoint and set status=continue for multi-turn work.
Optimistic locking needed to prevent agent and user from clobbering each other's edits.
Agent writes to timelines.config directly (same JSONB the UI reads), so changes appear via existing realtime subscription.
Phase 1: Foundation — DB Schema, Shared Modules, Types
ALTER TABLE timelines ADD COLUMN config_version integer NOT NULL DEFAULT 1;
Add trigger: on UPDATE of config, increment config_version automatically (or require caller to pass expected version).
Create RPC update_timeline_config_versioned(p_timeline_id uuid, p_expected_version int, p_config jsonb) that does a conditional update returning success/failure — this is the optimistic lock.
Update SupabaseDataProvider.saveTimeline to use the versioned RPC or pass config_version in the update filter.
create table public.timeline_agent_sessions (
id uuid primary key default gen_random_uuid(),
timeline_id uuid not null references public.timelines(id) on delete cascade,
user_id uuid not null references auth.users(id) on delete cascade,
status text not null default 'waiting_user'
check (status in ('waiting_user', 'processing', 'continue', 'done', 'cancelled', 'error')),
turns jsonb not null default '[]'::jsonb,
model text not null default 'groq',
summary text,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
RLS: user can select/insert/update own sessions.
Add to supabase_realtime publication for live turn updates.
Index on (timeline_id, status) for active session lookup.
view_timeline(config, assetRegistry): Build enriched view — list clips with computed durations (from asset registry), track assignments, timestamps. Return as structured text for LLM context.
move_clip(config, clipId, at): Find clip by ID, update at field. Return confirmation with old/new position.
trim_clip(config, clipId, { from?, to?, duration? }): Adjust source range. If duration given without from/to, adjust to = from + duration. Validate against asset duration from registry.
set_clip_property(config, clipId, property, value): Generic setter for volume, speed, opacity, position, etc. Whitelist allowed properties.
delete_clip(config, clipId): Remove from clips array. Return deleted clip info.
add_text_clip(config, track, at, duration, text): Create new TimelineClip with clipType: 'text', generate UUID for id.
find_issues(config, assetRegistry): Detect gaps between clips on same track, overlapping clips, clips extending past asset duration.
message_user(session, text): Append assistant message, set status='waiting_user'. Signal to stop the tool-use loop.
done(session, summary): Set status='done', store summary. Signal to stop.
create_generation_task(supabaseAdmin, session, { prompt, count }): Call existing create-task edge function or insert directly into tasks table via admin client.
Step 6: Implement the tool-use loop
Scope: Medium
Inai-timeline-agent/index.ts, after appending user message:
Load timelines.config and timelines.config_version via admin client.
Build LLM messages from session turns.
System prompt: describe available tools, current timeline state (via view_timeline), user's request.
Enter loop (max ~8 iterations to stay within edge function timeout):
a. Call Groq (or Claude if model='claude') with tools.
b. If response is text-only (no tool calls): append as assistant turn, call message_user, break.
c. If tool calls: execute each, append tool_call + tool_result turns.
d. If any tool mutated config: save via versioned RPC. If version conflict, reload and retry once.
e. If message_user or done was called: break.
f. Check session status (re-read from DB) — if cancelled, break immediately.
If loop hits iteration limit: set status='continue', save session, return.
Final: save updated turns to session, return response.
Timeout safety: Track wall-clock time. If approaching 50s, checkpoint and set status='continue'.
useAgentSessions(timelineId): React Query list of sessions for this timeline.
useAgentSession(sessionId): Single session with realtime subscription for turn updates.
useCreateSession(timelineId): Mutation to create new session row.
useSendMessage(sessionId): Mutation that POSTs to ai-timeline-agent edge function. On success, if response status === 'continue', auto-re-invoke after short delay (200ms).
useCancelSession(sessionId): Sets status='cancelled' directly via Supabase update.
Add a toggle button (e.g., MessageSquare icon from lucide) in the toolbar.
When active, show AgentChat as a side panel (right side, replacing or alongside PropertiesPanel) or as a drawer/overlay.
Pass timelineId to AgentChat.
UpdateuseTimelineRealtime awareness: when a timelines-updated event comes in and an agent session is active, don't show the conflict dialog — instead, silently reload (the agent is making the changes).
System prompt template that includes: tool descriptions, current timeline summary, user's editing history context, constraints (e.g., "always call view_timeline before making changes", "use message_user to communicate, don't just return text").
After Step 1: Run migration, verify config_version column exists and RPC works via SQL editor.
After Step 3: Test ai-voice-prompt still transcribes correctly (no regression).
After Step 6: curl the edge function with a test session — verify tool-use loop completes, config is updated.
After Step 9: Full E2E — open editor, chat with agent, see timeline update live.
After Step 12: Run through all validation scenarios from Step 12.4.
code
Plan metadata:
{
"version": 1,
"timestamp": "2026-03-25T23:11:35Z",
"hash": "sha256:8c8bff59ac594b2e3833fc8d4288d2e49e9fdbb517e47654fd070569a9098f36",
"questions": [
"Python tools (place.py, view.py, common.py) are outside the repo and I couldn't read them. Can you copy them into the repo (e.g., investigation/ or a temp folder) so I can port the exact logic? Or should I implement the tools from scratch based on the type definitions?",
"For the chat UI placement \u2014 should AgentChat replace the PropertiesPanel when open (toggle between them), sit as a resizable side panel alongside it, or be a floating overlay/drawer? The shell is already dense with 3 panels.",
"Should the agent be able to create generation tasks (e.g., generate new video clips via the existing task system)? The tool list includes create_generation_task but this requires knowing which task types are appropriate and having project context. Should this be deferred to a later phase?",
"For the auto-continuation loop: when the agent sets status=continue, should the client re-invoke immediately (200ms delay), or should there be a visible 'Agent is thinking...' state with the option for the user to intervene before it continues?"
],
"success_criteria": [
"New DB migration adds config_version to timelines and creates timeline_agent_sessions table with RLS and realtime",
"Shared transcription module extracted from ai-voice-prompt without breaking existing functionality",
"ai-timeline-agent edge function accepts session_id + user_message, runs tool-use loop, and writes updated config back to timelines table with optimistic locking",
"All 10 tools (view, move, trim, set_property, delete, add_text, find_issues, create_task, message_user, done) implemented and callable by the LLM",
"Kill switch works: setting session status to cancelled causes the agent to stop processing within one turn",
"Client chat UI shows conversation turns, supports text and voice input, and auto-continues on status=continue",
"Timeline updates from the agent appear in real-time in the editor (via existing realtime subscription)",
"Agent can handle a multi-step request like 'close the gap between clips 3 and 4' end-to-end in under 5 seconds"
],
"assumptions": [
"Groq API supports tool-use / function calling in chat completions (Groq added tool-use support for most models in 2024)",
"Edge function timeout is ~60s (Supabase default for Pro plan), which is enough for ~8 LLM turns with Groq's fast inference",
"The Python tools (place.py, view.py, common.py) implement straightforward clip manipulation logic that can be reimplemented from the TimelineConfig type definitions without needing exact source",
"Multiple concurrent agent sessions on the same timeline are safe because each session operates on a fresh config read and uses versioned writes \u2014 conflicts are detected and handled",
"The existing realtime subscription on the timelines table will fire when the edge function (using admin client) updates config, so no additional realtime wiring is needed for live updates",
"Voice transcription latency via Groq Whisper is ~500ms for typical utterances, meeting the parallel-load performance target",
"The session turns JSONB column is sufficient for conversation history \u2014 no need for a separate turns table unless sessions grow very large (>100 turns)"
],
"structure_warnings": []
}
code
Plan structure warnings from validator:
[]
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":"timeline-version-propagation","concern":"Timeline locking: config_version is only added at the DB write layer in the plan, but the current editor data flow never loads or carries a version token, so normal UI saves would remain blind writes and can still race the agent.","category":"correctness","severity_hint":"likely-significant","evidence":"Plan Step 1 only mentions updating SupabaseDataProvider.saveTimeline. In the repo, /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/data/SupabaseDataProvider.ts:19-34 loads only config, and /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useTimelineSave.ts:34-45 still calls provider.saveTimeline(timelineId, config) with no expected version. Unless the plan also threads config_version through load/query/state/reload paths, optimistic locking will not protect the existing editor save flow."},{"id":"session-realtime-plumbing","concern":"Realtime plumbing: adding timeline_agent_sessions to supabase_realtime is not sufficient for live turn updates; the current client realtime stack does not subscribe to or type that table anywhere.","category":"completeness","severity_hint":"likely-significant","evidence":"The plan relies on realtime session updates in Steps 2 and 7, but /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/shared/realtime/types.ts:46-51 only knows about tasks, generations, shot_generations, generation_variants, and timelines, and /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/shared/realtime/RealtimeConnection.ts:296-308 only subscribes to timelines on the editor side. Without a dedicated subscription in the new hooks or an extension of the shared realtime system, the chat UI will not auto-refresh turns/status."},{"id":"remote-reload-data-loss","concern":"Conflict handling: the Step 9 proposal to silently reload timeline updates while an agent session is active would discard unsaved local editor work and undermines the optimistic-locking goal.","category":"correctness","severity_hint":"likely-significant","evidence":"Today /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/hooks/useTimelineRealtime.ts:32-39 intentionally opens a conflict dialog whenever remote timeline updates arrive while saveStatus !== 'saved'. Replacing that with silent reload for agent-originated updates means a user with dirty local edits loses their draft as soon as the agent writes to timelines.config."},{"id":"task-creation-contract","concern":"Task creation: create_generation_task(prompt, count) is underspecified against the actual task system, and the plan's fallback of inserting directly into tasks would bypass the repo's validation, ownership, and idempotency guarantees.","category":"correctness","severity_hint":"likely-significant","evidence":"The repo has no generic prompt/count creation API. /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/shared/lib/taskCreation/createTask.ts:41-54 requires a concrete task_type, params, and project_id, /Users/user_c042661f/Documents/reigh-workspace/reigh-app/supabase/functions/create-task/index.ts:99-156 enforces project ownership and normalized insert building, and task families such as /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/shared/lib/tasks/families/imageGeneration/index.ts:67-141 map prompts into specific task contracts. Plan Step 5 says the agent can 'call existing create-task edge function or insert directly into tasks table via admin client', but direct inserts would skip those guarantees and the plan never states which task family prompt,count should target."},{"id":"find-issues-transcript-gap","concern":"Issue detection: the plan still treats find_issues as covering the Python behavior, but the current video-editor provider exposes no transcript/profile data, so mid-sentence-cut detection cannot be implemented from repository state as written.","category":"completeness","severity_hint":"likely-significant","evidence":"The user notes call out find_issues() including mid-sentence cuts, yet the plan's Step 5 silently narrows it to gaps/overlaps/duration bounds. In the repo, /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/data/DataProvider.ts:7-12 only defines transcript access as optional asset profile data, and /Users/user_c042661f/Documents/reigh-workspace/reigh-app/src/tools/video-editor/data/SupabaseDataProvider.ts:143-148 returns null for both loadWaveform() and loadAssetProfile(). Without a new source of transcript/profile metadata, that part of find_issues is not implementable."},{"id":"claude-path-missing","concern":"Model routing: the plan assumes a working Claude branch (model='claude' for complex reasoning), but the repository currently has Groq and some OpenAI wiring only; Anthropic integration work is not planned.","category":"completeness","severity_hint":"likely-minor","evidence":"Plan Steps 5-6 treat Claude as selectable, but repo search shows no Anthropic client/env wiring under supabase/functions or src. Existing AI endpoints such as /Users/user_c042661f/Documents/reigh-workspace/reigh-app/supabase/functions/ai-voice-prompt/index.ts and /Users/user_c042661f/Documents/reigh-workspace/reigh-app/supabase/functions/ai-prompt/index.ts use Groq, with one OpenAI call in ai-prompt; there is no corresponding Claude setup step in the plan."}],"verified_flag_ids":[],"disputed_flag_ids":[]}
“You are an independent reviewer. Critique the plan against the actual repository.….” Conversation with gpt-5.4, from the Peter O’Mallet DataClaw Conversations dataset. The Chat Archive, 2026. https://thechatarchive.com/c/01m80epz08gtbsw9t9bhyggppn