# SupoClip Workflows: final implementation spec Codebase: `/home/loki/Work/supoclip-workflows` at `08ec76db`. Paths below are relative to the repo root unless stated otherwise. Line numbers are from that commit; re-anchor on function names if they drift. Audience: engineers who have **not** read the earlier design docs. Everything you need is here. --- ## 0. What we are building and the decisions behind it Today a task does one thing: it picks standalone viral highlights. We add a choice, **"What do you want to make?"**, stored as `workflow`: | `workflow` | Output | UI promise | |---|---|---| | `highlights` (default) | N standalone clips. Current behaviour, unchanged. | The best standalone moments | | `series` | Part 1..N, consecutive, numbered, in source order. Adjacent parts share one exact cut. | Consecutive parts that tell the whole story | | `topic` | Every strong standalone moment about a typed topic. Off-topic moments are rejected even if viral. | Every strong moment about one subject | | `recap` | **One** clip stitched from several source ranges, covering the main points in order. | One short video covering the main points | | `trailer` | **One** short clip of beats (may jump around), builds curiosity, never reveals the payoff. | One short preview that makes people watch the full video | Plus a free-text **`instructions`** field that steers any workflow, highlights included. Everything downstream is shared: captions, framing/reframing, B-roll, hook titles, editor, export, aspect ratio, caption templates, cleanup. ### Decisions (final) 1. **The model never addresses the video by timestamp.** Code builds numbered *units* (sentences; clauses for trailers) from the word-level sidecar. Every planner returns unit ids. Code converts ids into word-exact float seconds. Cuts land on sentence ends by construction. 2. **Understand once, plan many.** A shared, cached **Source Outline** (chapters, main points, story arcs, payoffs, key topics, central question) is computed once per source and reused by series, topic, recap and trailer, across workflows and users. Long sources use map-reduce. Any failed window fails the task loudly (no silent gaps). 3. **Draft → validate → repair → solve → critique → re-solve.** Each planner gets an LLM draft, deterministic validation, at most one LLM repair round, a deterministic solver that owns the hard constraints (lengths, contiguity, budgets, spoilers), one LLM critique of the *finished* text read as a viewer (fixes are applied as solver constraints), and a deterministic final solve. Hard constraints never depend on the model being careful. 4. **Series parts are expressed as `end_unit` values only**, so gaps or overlaps between parts cannot be expressed. Dead weight inside the story (sponsor reads, tangents) is removed with *skips* (whole units), not by jumping between spans. 5. **Planned segments are locked at render time.** Segments carry float `source_ranges` and `planned: True`. The renderer skips start snapping, end extension and the cold-open teaser. It uses a per-segment cap only as a safety net, and recomputes caption text from the ranges. Adjacent series parts therefore share one cut: no repeated word, no missing word. 6. **Highlights without instructions keeps its pipeline** (render differences listed in `docs/workflows.md`): same prompts, cache keys, post-processing, render path, enqueue args, `process_video_complete` kwargs. A golden test pins this (invariant I1). Highlights *with* instructions gets one extra user-prompt block and a derived cache key. 7. **Storage in real columns**, read by the worker from the task row (same pattern as `include_broll`, `task_service.py:547-548`). The ARQ job signature and both enqueue sites stay unchanged, and resume works with no route change. 8. **Rollout gate** `WORKFLOWS_ACCESS=off|admins|all` (default `admins`), mirroring `SOCIAL_PUBLISHING_ACCESS`. This also protects against an old worker draining a queued series task as highlights during deploy. 9. **Fail loud, refund, suggest a next step.** No fallback segments for workflows. Workflow errors carry a code, a user-facing message and details (e.g. suggested topics). Before the status flips to `error`, the error path deletes any clips so the automatic minute refund fires. 10. **No review gate in v1**, but the plan is persisted (`tasks.workflow_plan`) before rendering and the segments are a pure function of it, so a later `awaiting_review` status can pause between the two. 11. **Models**: bulk passes (outline map windows, topic extraction) use `config.llm` (`LLM`). Judgement passes (outline reduce, series/recap/trailer drafts, critiques, spoiler judge, topic locate and rerank) use `config.rerank_llm` (`RERANK_LLM`, defaults to `LLM`). No new providers, no new model env vars. 12. **Length**: the existing `clip_length` chip means *part length* for series, *total length* for recap and trailer, and per-clip length for topic. One field, one chip, relabelled per workflow. ### Judge-reported errors and how this spec fixes them (all re-verified in code) | Error | Fix in this spec | |---|---| | `sanitize_hook_title(raw)` (`ai.py:885`) has no budget parameter; caps at 64 chars / 10 words. | `workflows/titles.py::compose_title` calls `sanitize_hook_title` unchanged and then does its own word-boundary trim to the remaining budget (§9.7). `ai.py` is not touched for this. | | Repair round calling `agent.run(..., message_history=...)` bypasses the retry/timeout runner. | `llm.run_with_repair` sends the repair as a fresh prompt (original prompt + previous JSON + issues) through `ai._run_transcript_analysis` (§7.3). | | `youtube_captions` transcripts have no word sidecar; a hard failure is wrong. | Units degrade to transcript lines via `ai._parse_transcript_spans`, `coarse=True`, plan note `COARSE_TRANSCRIPT`. Only zero timed lines is an error (§6.6). | | Topic segments unlocked → end extension adds up to 5.85 s and stored text is stale. | Topic segments are `planned` too (locked, text recomputed) (§10). | | Default renderer auto-crossfades 2–8 in-order ranges, so recap/trailer would get uncontrolled dissolves. | Planned segments always get explicit `output_offsets` built from `junction_fades`; the same offsets reach render, captions, speaker turns, B-roll and the source map (§14.3). | | Trailer "button must end in `?`" as a hard rule is brittle. | Soft rule: prefer a question; otherwise the spoiler judge's `button_unresolved` must be true (§12). | | Recap "1–2 sentences per point" gives a choppy montage. | Beats are 4–25 s with a full span and a core span; the knapsack grows to full spans when budget allows; a coherence critique fixes junctions (§11). | | Multi-span "condensed" series parts reintroduce jump cuts and dangling references. | Contiguous parts with explicit, bounded skips (≤ 40 % per part, never at a part edge) (§9). | | "Refunded because clips were wiped at `task_service.py:533`" is false on resume: planning runs inside `process_video_complete` before the wipe, and `refund_failed_minute_usage` needs zero clips. | Error path deletes the task's clips before `update_task_status(..., "error")` for every `WorkflowError`, and for any non-cancel failure of series/recap/trailer (§15.2). | | `set_task_workflow` as a second UPDATE is not atomic with creation and the charge. | `workflow`/`workflow_options` go through `create_task_with_source` → `TaskRepository.create_task` in the same INSERT (§3.3). | | `output_offsets` plumbing missed `VideoService.plan_broll` (`video_service.py:597`). | `plan_broll(..., output_offsets=)` is in the plumbing list (§14.3). | | No rollout gate; old workers run paid series tasks as highlights. | `WORKFLOWS_ACCESS` default `admins` (§4.4). | | Cache-hit virality zeroing fix (`video_service.py:~1127`) would change highlights. | Out of scope; separate one-line PR. Workflows never use that path. | | `restore_clip_timeline` only runs with a time map; display bounds must be set unconditionally; `_drop_static_segments` reads only `start_time/end_time`. | Render loop sets display bounds for every planned segment after render (§5.3). Static checks for planned segments are per-range (§5.2 step 6). | | Sidecar words are in ms; `_start_before_word`/`_padded_clip_end` take seconds. | `units.py` converts after `repair_word_timings` (which works in int ms) (§6.1). | | Out-of-order trailer beats: `crossfade_fade_for_ranges` hard-cuts them; explicit offsets must be shared by every consumer. | Explicit offsets everywhere (§14.3). `render_ranges_crossfade_ffmpeg` trims from one input window, so out-of-order is supported (verified `ffmpeg.py:470-484`). | ### Invariants (each has a test) - **I1** `workflow="highlights"` and empty instructions: identical cache keys, prompts, `process_video_complete` kwargs, segment list, render path and enqueue args. - **I2** Series: for adjacent parts N, N+1, the word sets from `timeline.get_words_for_keep_ranges` over their keep ranges are disjoint, and the union over all parts equals the span's words minus skipped units. Holds with cleanup on and off. - **I3** Every range edge produced by a planner lies on a unit edge: start ≥ previous word end, end ≤ next word start − 0.03 s. - **I4** Recap and trailer produce exactly one output, and its estimated duration is inside the budget window. The planner guarantees this; the render clamp never fires on planner fixtures. - **I5** Topic never pads with off-topic moments. Zero qualifying moments raises `topic_not_found` with suggestions, and the task is refunded. - **I6** No silent partial series/recap/trailer. A missing required output means all clips are deleted, the task errors and the charge is refunded. --- ## 1. Product behaviour ### 1.1 Lengths and limits (`backend/src/workflows/durations.py`) All values are seconds of *speech after cleanup* (estimated, §6.4). **Series part budget** (`clip_length` = part length): | `clip_length` | min | ideal | max | render cap | |---|---|---|---|---| | auto | 45 | 60–100 | 150 | 155 | | short | 30 | 35–50 | 60 | 65 | | medium | 45 | 55–80 | 90 | 95 | | long | 90 | 100–150 | 175 | 180 | **Recap total budget**: target `T` = `short` 45, `medium` 75, `long` 120, `auto` scales with source length `D`: `D ≤ 600` → 45, `≤ 1800` → 60, `≤ 5400` → 90, else 120. Window `[0.85·T, 1.15·T]`. Render cap `min(180, 1.15·T + 5)`. If `T > 0.6·D` (short source), use `T = max(30, round(0.4·D))` and add plan note `TARGET_SHORTENED`. **Trailer total budget**: `auto` 30, `short` 20, `medium` 40, `long` 60. Window `[0.67·T, 1.1·T]` (four lines on one thread beat a padded trailer). Render cap `1.1·T + 5`. **Topic per clip** (`durations.topic_budget`): auto 15/30–60/90, render cap 95, so a whole story fits (a clip must make sense alone, so it can't be cut in half at 60 s); short, medium and long keep `clip_duration.CLIP_DURATIONS` (short 15/18–25/30, medium 30/35–55/60, long 60/75–110/120). Render cap = maximum + 5. Highlights keep `clip_budget`. **Counts**: series 2–10 parts (`SERIES_MIN_PARTS=2`, `SERIES_MAX_PARTS=10`); topic up to `WORKFLOW_TOPIC_MAX_CLIPS` (env, default 15); recap/trailer exactly 1. **Minimum source length** (checked at the API before charging, again in the worker when the API had no duration): | workflow | minimum | extra | |---|---|---| | series | 120 s | explicit N needs `D ≥ N · part.min · 1.25`, else `TOO_MANY_PARTS` with the largest N that fits | | recap | 180 s | — | | trailer | 180 s | — | | topic | 60 s | — | `WORKFLOW_RENDER_HARD_MAX_SECONDS = 185`. ### 1.2 Per-workflow defaults | | highlights | series | topic | recap | trailer | |---|---|---|---|---|---| | Hook title (burned in first ~4 s) | AI hook (unchanged) | `Part 2: The bank calls back` (label localized in code) | AI hook, topic-aware | recap title | curiosity title, never names the outcome | | Cold-open teaser (`HOOK_FIRST_TEASER`) | env flag (unchanged) | never | never | never | never (it *is* a teaser) | | Score ring / "Top pick" | yes | no | yes | no | no | | Default sort | score | part order | score | n/a | n/a | | Performance context | yes | no | yes (rerank only) | no | no | | Static-picture drop | yes | no (log only) | yes | per-range, swap/drop non-essential beat | per-range, drop non-essential beat | | Captions, framing, B-roll, template, cleanup, aspect | user settings for all workflows | --- ## 2. Shared contracts (every package codes against these) These land first, in WP1. Do not change them without updating this section. ### 2.1 `backend/src/workflows/contracts.py` ```python from __future__ import annotations import hashlib, json from dataclasses import dataclass, field from typing import Any, Awaitable, Callable, Literal, Optional, Protocol WORKFLOWS: tuple[str, ...] = ("highlights", "series", "topic", "recap", "trailer") Workflow = Literal["highlights", "series", "topic", "recap", "trailer"] WORKFLOW_PLAN_VERSION = "wf-v1" # bump to invalidate cached plans (not transcripts) OUTLINE_VERSION = "outline-v2" # bump to invalidate cached outlines @dataclass(frozen=True) class WorkflowOptions: topic: str = "" # topic workflow only; already normalized part_count: Optional[int] = None # series only; None = auto instructions: str = "" # any workflow; already normalized def to_json(self) -> dict[str, Any]: """Canonical, sorted, no empty values. Stored in tasks.workflow_options.""" out: dict[str, Any] = {} if self.topic: out["topic"] = self.topic if self.part_count is not None: out["part_count"] = self.part_count if self.instructions: out["instructions"] = self.instructions return out @classmethod def from_json(cls, raw: Any) -> "WorkflowOptions": """Lenient: unknown keys ignored, bad types dropped. Never raises.""" @dataclass(frozen=True) class WorkflowSpec: workflow: str # one of WORKFLOWS options: WorkflowOptions clip_length: str # auto|short|medium|long @property def legacy(self) -> bool: return self.workflow == "highlights" and not self.options.instructions @property def uses_performance_context(self) -> bool: return self.workflow in ("highlights", "topic") @property def topic_key(self) -> str: # casefold + collapse whitespace return " ".join(self.options.topic.casefold().split()) def fingerprint(self) -> str: """sha256 of canonical JSON: workflow, WORKFLOW_PLAN_VERSION, clip_length, topic_key, part_count, sha256(instructions)[:16].""" def workflow_spec_from_task(task_row: dict, clip_length: str) -> WorkflowSpec: """Lenient read for the worker. Missing/unknown workflow (including a MagicMock row in tests or a pre-migration row) -> highlights with empty options.""" ProgressFn = Callable[[int, str], Awaitable[None]] # (percent, message); raises on cancel class PlanCache(Protocol): async def load(self, key: str) -> Optional[str]: ... async def store(self, key: str, payload: str) -> None: ... @dataclass class PlanContext: spec: WorkflowSpec task_id: Optional[str] transcript_text: str # the existing analysis transcript ("[MM:SS - MM:SS] Speaker: ...") transcript_data: Optional[dict] # word sidecar (ms), from load_cached_transcript_data source_seconds: float # ffprobe duration of the analysed file cleanup_settings: dict # normalize_clip_cleanup_settings(...) output performance_context: Optional[str] progress: ProgressFn plan_cache: PlanCache outline_cache_key: str @dataclass class WorkflowResult: segments: list[dict] # PlannedSegment dicts (§2.2), in render order plan: dict # -> tasks.workflow_plan (§2.4) summary: Optional[str] key_topics: list[str] units_fingerprint: str def to_cache_json(self) -> str: return json.dumps({"version": WORKFLOW_PLAN_VERSION, "workflow": self.plan["workflow"], "units_fingerprint": self.units_fingerprint, "plan": self.plan, "segments": self.segments, "summary": self.summary, "key_topics": self.key_topics}) @classmethod def from_cache_json(cls, raw: Optional[str], workflow: str, units_fingerprint: str) -> Optional["WorkflowResult"]: """None unless version, workflow and units_fingerprint all match.""" ``` `backend/src/workflows/pipeline.py` (WP3) exports: ```python async def plan_workflow(ctx: PlanContext) -> WorkflowResult ``` It must be called only for `workflow != "highlights"`. It raises `WorkflowError` for user-facing failures and lets `TaskCancelled`/`Exception("Task cancelled")` propagate. Wall clock is bounded by `WORKFLOW_PLAN_TIMEOUT_SECONDS` (env, default 1800); on timeout raise `WorkflowError("plan_failed", ...)`. ### 2.2 `backend/src/workflows/errors.py` ```python class WorkflowRequestError(ValueError): """Rejected at the API. status 422 (or 403 for WORKFLOW_NOT_AVAILABLE).""" def __init__(self, code: str, message: str, status: int = 422): ... class WorkflowError(ValueError): """Raised in the worker. message is user-facing English and becomes progress_message.""" def __init__(self, code: str, message: str, details: Optional[dict] = None): ... # .code, .message, .details ; str(e) == message ``` Worker codes: `source_too_short`, `no_story`, `topic_not_found`, `recap_unsupported`, `trailer_unbuildable`, `analysis_incomplete`, `plan_failed`, `render_incomplete`, `transcript_untimed`. ### 2.3 PlannedSegment dict (what planners emit and the renderer consumes) All highlights segments are unchanged and have none of the new keys. ```python { # labels + filename only. First range's start/end, MM:SS (minutes may exceed 59). "start_time": "12:04", "end_time": "13:20", "source_ranges": [[724.31, 801.92], [815.10, 840.55]], # float seconds, PLAY order (may be non-monotonic for trailer) "planned": True, "junction_fades": [0.10], # len == len(source_ranges)-1; seconds; 0 = hard cut "max_seconds": 155.0, # render safety cap (budget max + 5) "required": True, # series/recap/trailer True; topic False "text": "...stitched unit text...", # display only; renderer recomputes from ranges "hook_title": "Part 2: The bank calls back", "reasoning": "", "relevance_score": 1.0, "virality_score": 0, "hook_score": 0, "engagement_score": 0, "value_score": 0, "shareability_score": 0, "hook_type": None, # topic: the model's hook_type "workflow_role": "part", # part | topic | recap | trailer "part_number": 2, # series only, else None "workflow_meta": { ... §2.5 ... }, } ``` ### 2.4 `tasks.workflow_plan` JSON (public-safe subset marked †) ```jsonc { "version": "wf-v1", "workflow": "series", // † "language": "en", "coarse": false, "mode": "full", // mode: full | long "title": "How we almost lost the company", // † series title / recap title / trailer title / topic canonical "summary": "...", "key_topics": ["..."], "parts": [{"part_number": 1, "title": "...", "delivers": "...", "ends_on": "...", "post_caption": "...", "first_unit": 40, "last_unit": 71, "ranges": [[61.42, 133.9]], "seconds": 72.1}], // † title, part_number "points": [{"label": "...", "ranges": [[...]], "output_start": 12.4}], // † recap "beats": [{"role": "cold_open", "ranges": [[...]], "output_start": 0.0}], // † trailer "topic": {"query": "building a business", "canonical": "...", "coverage": "strong|thin", "found": 4, "suggested_topics": ["pricing", "hiring"]}, // † "notes": [{"code": "PART_COUNT_REDUCED", "params": {"requested": 8, "actual": 5}}], // † "error": {"code": "topic_not_found", "details": {"suggested_topics": [...], "mentions": ["12:30", "41:02"]}}, // † only on failure "stats": {"llm_calls": 4, "repairs": 1, "critique_fixes": 2, "plan_seconds": 41.2} } ``` Note codes: `PART_COUNT_REDUCED`, `STORY_ARC_SELECTED`, `CHAPTERS_LEFT_OUT`, `NO_SINGLE_STORY`, `TOPIC_THIN`, `TOPIC_BROADENED`, `TARGET_SHORTENED`, `COARSE_TRANSCRIPT`, `SPONSOR_SKIPPED`, and the internal `RECAP_UNDER_WINDOW` (never shown). The frontend localizes them from `task.workflowNotes.` with `params`. ### 2.5 `generated_clips.workflow_meta` JSON Common keys for every planned clip: `{"planned": true, "ranges": [[s,e],...], "junction_fades": [...], "max_seconds": 155}`. `ranges` is the DB copy of the planned ranges, so a lost `.source_map.json` never falls back to the min–max span. - part: `+ {"series_title", "part_count", "title", "delivers", "ends_on", "post_caption", "first_unit", "last_unit"}` - topic: `+ {"topic", "topic_relevance": 0-100, "why"}` - recap: `+ {"points": [{"label", "range_index", "output_start"}]}` - trailer: `+ {"beats": [{"role", "range_index", "output_start"}]}` - after a split: `+ {"split": 1|2}` ### 2.6 `GET /tasks/workflows` response ```json {"enabled": true, "workflows": [ {"id": "highlights", "available": true, "min_source_seconds": 0}, {"id": "series", "available": true, "min_source_seconds": 120, "part_count": {"min": 2, "max": 10}, "lengths": {"auto": [45, 150], "short": [30, 60], "medium": [45, 90], "long": [90, 175]}}, {"id": "topic", "available": true, "min_source_seconds": 60}, {"id": "recap", "available": true, "min_source_seconds": 180, "lengths": {"auto": null, "short": 45, "medium": 75, "long": 120}}, {"id": "trailer", "available": true, "min_source_seconds": 180, "lengths": {"auto": 30, "short": 20, "medium": 40, "long": 60}}], "topic_max_chars": 120, "instructions_max_chars": 500} ``` `enabled` false means the caller may only use highlights without instructions. ### 2.6a Advanced settings (added after the first release) `WorkflowOptions.advanced` holds only non-default values from the registry in `workflows/settings.py`; `WorkflowSpec.setting(key)` reads a value or its default, and `fingerprint()` includes `advanced` only when it is non-empty, so default plans keep their cache keys. `docs/workflows.md` lists every setting. ### 2.7 Frontend contract `frontend/src/lib/workflows.ts` (WP1) ```ts export const WORKFLOWS = ["highlights", "series", "topic", "recap", "trailer"] as const; export type Workflow = (typeof WORKFLOWS)[number]; export function isWorkflow(v: unknown): v is Workflow; export const SINGLE_OUTPUT: ReadonlySet; // recap, trailer export const SCORED: ReadonlySet; // highlights, topic export const PART_COUNT_OPTIONS = ["auto", 2, 3, 4, 5, 6, 8, 10] as const; export const TOPIC_MAX_CHARS = 120; export const INSTRUCTIONS_MAX_CHARS = 500; export const MIN_SOURCE_SECONDS: Record; // mirrors §1.1 export type WorkflowOptions = { topic?: string; part_count?: number; advanced?: Record }; export type WorkflowPlan = { /* §2.4 */ }; export type WorkflowMeta = { /* §2.5 */ }; export type WorkflowsInfo = { /* §2.6 */ }; export function defaultSort(w: Workflow): "score" | "timeline"; // timeline for series export function expectedOutputs(w: Workflow, sourceSeconds?: number | null, partCount?: number | null): number; // recap/trailer 1; series partCount ?? clamp(round(sec/90), 2, 6); topic 5; highlights = existing expectedClipCount ``` --- ## 3. Data model ### 3.1 Migration `backend/src/migrations/sql/20261031_0001_task_workflows.sql` Applied automatically at API start by `database.init_db` (`backend/src/database.py:104-142`). That runner splits on `;` and runs everything in one transaction, so: no `;` in comments, no function bodies, no `CONCURRENTLY`. A fresh Docker DB runs `init.sql` first, so every statement must be idempotent. ```sql -- Workflows: what a task makes (highlights, series, topic, recap, trailer) ALTER TABLE tasks ADD COLUMN IF NOT EXISTS workflow VARCHAR(20) NOT NULL DEFAULT 'highlights'; ALTER TABLE tasks DROP CONSTRAINT IF EXISTS tasks_workflow_check; ALTER TABLE tasks ADD CONSTRAINT tasks_workflow_check CHECK (workflow IN ('highlights', 'series', 'topic', 'recap', 'trailer')); ALTER TABLE tasks ADD COLUMN IF NOT EXISTS workflow_options JSONB NOT NULL DEFAULT '{}'::jsonb; ALTER TABLE tasks ADD COLUMN IF NOT EXISTS workflow_plan JSONB; ALTER TABLE generated_clips ADD COLUMN IF NOT EXISTS workflow_role VARCHAR(20); ALTER TABLE generated_clips ADD COLUMN IF NOT EXISTS part_number INTEGER; ALTER TABLE generated_clips ADD COLUMN IF NOT EXISTS workflow_meta JSONB NOT NULL DEFAULT '{}'::jsonb; CREATE INDEX IF NOT EXISTS idx_tasks_user_workflow ON tasks(user_id, workflow) ``` - Mirror the columns in `init.sql` (`tasks` at lines 56–90, `generated_clips` at 93–117), same constraint name. - Mirror in `backend/src/models.py` (`Task`, `GeneratedClip`) so `create_all` test DBs match. - No unique constraint on `(task_id, part_number)`: split copies `part_number` onto both halves. - Prisma: **no change in v1** (`model Task` is already partial; no `GeneratedClip` model). ### 3.2 Repository changes **`backend/src/repositories/task_repository.py`** - `create_task(...)` (:26): add `workflow: str = "highlights", workflow_options: dict | None = None`. Add both to the INSERT column list and VALUES (`:workflow`, `CAST(:workflow_options AS JSONB)` with `json.dumps(workflow_options or {})`). Keep the existing 42703 behaviour pattern: if the INSERT fails with sqlstate 42703 (worker/API ahead of migration), retry without the two columns. - `get_task_by_id` (:129–188): add to the returned dict: ```python "workflow": getattr(row, "workflow", None) or "highlights", "workflow_options": getattr(row, "workflow_options", None) or {}, "workflow_plan": getattr(row, "workflow_plan", None), "source_duration_seconds": getattr(row, "source_duration_seconds", None), # missing today; used by clip_service/task_service "share_enabled": getattr(row, "share_enabled", None), # missing today; frontend reads it ``` - `get_user_tasks` (:394–437): - Return `"workflow": getattr(row, "workflow", None) or "highlights"`, `"workflow_title": (row.workflow_plan or {}).get("title")`, `"part_count": len((row.workflow_plan or {}).get("parts") or []) or None`. - Cover clip subquery (:404): `ORDER BY CASE WHEN t.workflow IN ('series','recap','trailer') THEN clip_order END ASC NULLS LAST, virality_score DESC NULLS LAST, clip_order ASC LIMIT 1`. (Use `COALESCE(t.workflow,'highlights')` is unnecessary; the column is NOT NULL.) Keep a 42703 fallback to the old query. - New `save_workflow_plan(db, task_id: str, plan: dict | None) -> None`: `UPDATE tasks SET workflow_plan = CAST(:plan AS JSONB) WHERE id = :task_id`, `commit_unless_editing(db)`, rollback on error (copy `save_source_metadata` at :86–95). Overwrites (never merges). - New `merge_workflow_plan_error(db, task_id, code, details)`: `UPDATE tasks SET workflow_plan = COALESCE(workflow_plan, '{}'::jsonb) || jsonb_build_object('error', CAST(:err AS JSONB))`. **`backend/src/repositories/clip_repository.py`** - `create_clip(...)` (:25): add kwargs `workflow_role: str | None = None, part_number: int | None = None, workflow_meta: dict | None = None`. Add to the INSERT columns/VALUES (`CAST(:workflow_meta AS JSONB)`, `json.dumps(workflow_meta or {})`) **and** to the `ON CONFLICT (task_id, clip_order) DO UPDATE SET` list. The 42703 fallback INSERT drops them (acceptable). - `get_clips_by_task` (:144) and `get_clip_by_id` (:251): add the three columns to the SELECT and returned dict (`getattr(row, "workflow_meta", None) or {}`). `get_clip_by_id` is the SSE `clip_ready` payload, so parts stream with numbers. - `update_clip` unchanged (metadata survives trims). ### 3.3 `TaskService.create_task_with_source` (`backend/src/services/task_service.py:210`, WP1) Add `workflow: str = "highlights", workflow_options: dict | None = None` and pass them to `TaskRepository.create_task`. Nothing else in this function changes. (WP1 lands this edit first; WP4 owns the file afterwards.) --- ## 4. API ### 4.1 `POST /tasks/` additions (all optional) ```jsonc { "source": {"url": "https://youtu.be/..."}, "workflow": "series", // default "highlights" "workflow_options": {"topic": "building a business", "part_count": "auto"}, "instructions": "Focus on the story about the first startup", // top level; any workflow "clip_length": "auto" // ...all existing fields unchanged } ``` `workflow_options.instructions` is also accepted (MCP/older clients); top-level wins when both are set. ### 4.2 Validation: `backend/src/workflows/options.py` (WP1) ```python TOPIC_MIN_CHARS, TOPIC_MAX_CHARS = 2, 120 INSTRUCTIONS_MAX_CHARS = 500 def normalize_text(value: Any, *, keep_newlines: bool) -> str: """str only; strip; remove control chars (keep \n if keep_newlines); collapse runs of spaces/tabs to one space; collapse 3+ newlines to 2.""" def parse_workflow_request(data: dict, clip_length: str) -> WorkflowSpec # raises WorkflowRequestError def check_source_duration(spec: WorkflowSpec, duration_seconds: float | None) -> None # raises WorkflowRequestError; no-op if None def workflow_runtime_minimum_error(spec: WorkflowSpec, source_seconds: float) -> WorkflowError | None # same rule for the worker when the API had no duration ``` Rules (422 `{"code", "message"}` unless stated): | Input | Rule | Code | Message | |---|---|---|---| | `workflow` | Missing/None → `highlights`. A present value not in `WORKFLOWS` is rejected, never coerced. | `INVALID_WORKFLOW` | "Unknown workflow. Use highlights, series, topic, recap or trailer." | | `topic` | Required for `topic`: `normalize_text(keep_newlines=False)`, 2–120 chars. Ignored (dropped) for other workflows. | `TOPIC_REQUIRED` / `TOPIC_TOO_LONG` | "Enter a topic to look for." / "Keep the topic under 120 characters." | | `part_count` | Series only. `"auto"`, null, missing → None. Int (or numeric string) 2–10. Otherwise reject. Dropped for other workflows. | `INVALID_PART_COUNT` | "Choose Auto or 2 to 10 parts." | | `instructions` | `normalize_text(keep_newlines=True)`, ≤ 500 chars after normalization. | `INSTRUCTIONS_TOO_LONG` | "Keep instructions under 500 characters." | | access | Non-highlights workflow, or non-empty instructions, when the user lacks access (§4.4). | `WORKFLOW_NOT_AVAILABLE` (403) | "This option isn't available on your account yet." | Duration rules (`check_source_duration`), run after preflight, before `assert_can_create_task(user_id, duration_seconds)`: | Code | Condition | Message | |---|---|---| | `SOURCE_TOO_SHORT_FOR_SERIES` | series, `D < 120` | "This video is too short to split into a series. Try Highlights instead." | | `TOO_MANY_PARTS` | series, explicit N, `D < N · part.min · 1.25` | "This video fits at most {max} parts. Choose fewer parts or Auto." (`max = max(2, floor(D / (part.min·1.25)))`; if `max < 2`, use `SOURCE_TOO_SHORT_FOR_SERIES`) | | `SOURCE_TOO_SHORT_FOR_RECAP` | recap, `D < 180` | "This video is already short. Recaps work on videos over 3 minutes." | | `SOURCE_TOO_SHORT_FOR_TRAILER` | trailer, `D < 180` | "Trailers work on videos over 3 minutes." | | `SOURCE_TOO_SHORT_FOR_TOPIC` | topic, `D < 60` | "This video is too short to search by topic. Try Highlights instead." | ### 4.3 `backend/src/api/routes/tasks.py::_create_task` (:480) edits (WP1) 1. Right after the `clip_length` block (:512–515): `spec = parse_workflow_request(data, clip_length)`; convert `WorkflowRequestError` to `HTTPException(status_code=e.status, detail={"code": e.code, "message": e.message})`. 2. Access check (needs `user_id`, already resolved at :488): `if not spec.legacy and not await workflows_enabled_for(db, user_id): raise 403 WORKFLOW_NOT_AVAILABLE`. 3. Upload dedupe options dict (:520–536): add `"workflow": spec.workflow, "workflow_options": spec.options.to_json()`. (Instructions are inside `to_json`; the key is a SHA-256 so raw text never leaves the process.) 4. After the preflight `duration_seconds` is known (:577) and before the `generation_allowance_guard` block: `check_source_duration(spec, duration_seconds)` → 422. 5. Pass `workflow=spec.workflow, workflow_options=spec.options.to_json()` into `task_service.create_task_with_source(...)` (:584). 6. **Enqueue unchanged** (:623–641). **Resume unchanged** (:1375–1497): the worker reads the row. 7. `PUBLIC_TASK_FIELDS` (:367): add `workflow`. In `_build_public_task`, add `workflow_plan` reduced to the † subset of §2.4 (`version`, `workflow`, `title`, `parts[].{part_number,title}`, `points[].label`, `beats[].role`, `topic.{query,canonical,coverage,found}`, `notes`). `PUBLIC_CLIP_FIELDS` (:375): add `part_number`, `workflow_role`, and `workflow_meta` reduced to `{title, ends_on, points, beats}`. 8. New route **declared before `/{task_id}`** (next to `/billing/summary`, :679): `GET /tasks/workflows` → §2.6. Auth like other task routes; `enabled = await workflows_enabled_for(db, user_id)`; each workflow `available = enabled or id == "highlights"`. `backend/src/source_submission.py::record_fields` (:71): add `workflow` (string only, never topic or instructions). ### 4.4 Access gate (`backend/src/config.py`, `backend/src/workflows/options.py`) ```python # config.py self.workflows_access = (os.getenv("WORKFLOWS_ACCESS") or "admins").strip().lower() if self.workflows_access not in {"all", "admins", "off"}: self.workflows_access = "admins" self.workflows_allowed_emails = {e.strip().lower() for e in os.getenv("WORKFLOWS_ALLOWED_EMAILS", "").split(",") if e.strip()} self.workflow_topic_max_clips = int(os.getenv("WORKFLOW_TOPIC_MAX_CLIPS", "15")) self.workflow_plan_timeout_seconds = float(os.getenv("WORKFLOW_PLAN_TIMEOUT_SECONDS", "1800")) self.workflow_full_context_max_words = int(os.getenv("WORKFLOW_FULL_CONTEXT_MAX_WORDS", "0")) or None # None = provider default (§8.1) ``` ```python # options.py async def workflows_enabled_for(db, user_id: str) -> bool: """Same logic as SocialService.has_access (social_service.py:119): all -> True, off -> False, admins -> users.is_admin or email in WORKFLOWS_ALLOWED_EMAILS.""" ``` Ship with `WORKFLOWS_ACCESS=admins` in prod, deploy worker and API together, then flip to `all`. Self-hosters set `WORKFLOWS_ACCESS=all` (documented). ### 4.5 Read paths - `GET /tasks/{id}` returns `workflow`, `workflow_options`, `workflow_plan`, `error_code` (already there) via `get_task_by_id`; clip fields via `get_clips_by_task`. `_load_task_source_settings` is unchanged. - `GET /tasks/` returns `workflow`, `workflow_title`, `part_count`. - `docs/api-reference.md` documents all of it (WP6). --- ## 5. Worker and service flow ### 5.1 `TaskService.process_task` (`backend/src/services/task_service.py:336`, WP4) Signature unchanged. Changes, in order: 1. **Read the row early.** Move `task_row = await self.task_repo.get_task_by_id(self.db, task_id) or {}` (today at :547) to just before the cache-key block (:390). Reuse it later for `include_broll`. `spec = workflow_spec_from_task(task_row, clip_length)`. 2. **Runtime minimum.** If not legacy and `task_row.get("source_duration_seconds")` is None, the planner enforces minimums (pipeline calls `workflow_runtime_minimum_error`). 3. **Cache keys** (:390–413): ```python if spec.legacy: analysis_cache_key = self._build_analysis_cache_key(cache_key, clip_length) # unchanged else: analysis_cache_key = hashlib.sha256(f"{cache_key}|wf:{spec.fingerprint()}|llm:{cfg.llm}|{cfg.rerank_llm}".encode()).hexdigest() outline_cache_key = hashlib.sha256(f"{cache_key}|{OUTLINE_VERSION}|{cfg.llm}|{cfg.rerank_llm}".encode()).hexdigest() ``` Highlights-with-instructions uses the derived key too (workflow `highlights` is inside the fingerprint). `TRANSCRIPT_ANALYSIS_CACHE_VERSION` is **not** bumped. 4. **Performance context** (:410): load only if `spec.uses_performance_context`. If present, `cached_analysis_json = None` as today (topic plans then neither read nor write the plan cache; the outline cache is still used because it holds no personal data). 5. **Call the pipeline** (:458): if `spec.legacy`, the call is byte-identical to today. Otherwise add kwargs `workflow_spec=spec, plan_cache=_ProcessingPlanCache(self.cache_repo, self.db, url, source_type), outline_cache_key=outline_cache_key, cleanup_settings=normalized_cleanup_settings` (compute `normalize_clip_cleanup_settings` before the call instead of after). ```python class _ProcessingPlanCache: # in task_service.py async def load(self, key): row = await self.cache_repo.get_cache(self.db, key); return row and row.get("analysis_json") async def store(self, key, payload): await self.cache_repo.upsert_cache(self.db, cache_key=key, source_url=..., source_type=..., analysis_json=payload) ``` 6. **Plan cache write-back**: unchanged code at :503–524 already writes `result["analysis_json"]` under a derived `analysis_cache_key` when it differs from `cache_key` and there is no performance context. For workflows, `analysis_json` is `WorkflowResult.to_cache_json()`. 7. **Persist the plan** before the clip wipe (:533): `if result.get("workflow_plan") is not None: await self.task_repo.save_workflow_plan(self.db, task_id, result["workflow_plan"])` inside `_processing_transaction(task_id)`. 8. **Render loop** (:545–624), §5.3. 9. **Error path** (:673–722), §15.2. 10. Completion notification: pass `workflow` and `part_count` to `_send_completion_notification_if_needed` → `task_completion_email_service` copy: series "Your {n}-part series is ready", recap "Your recap is ready", trailer "Your trailer is ready", topic "Your clips about {topic} are ready", highlights unchanged. ### 5.2 `VideoService.process_video_complete` (`backend/src/services/video_service.py:882`, WP4) New keyword-only params with defaults: `workflow_spec: Optional[WorkflowSpec] = None, plan_cache: Optional[PlanCache] = None, outline_cache_key: Optional[str] = None, cleanup_settings: Optional[dict] = None`. Download, duration guard and transcript (:918–1058) stay shared and unchanged. **Refactor (pure move, its own commit, reviewed with `git diff --color-moved`)**: lines 1060–1199 (cached analysis, `analyze_transcript`, normalize, `_ground_segment_text`, `_refine_segment_openings`, `clip_limit`, reserve, fallback) move verbatim into ```python async def _select_highlight_segments(self_or_cls, *, video_path, transcript, cached_analysis_json, performance_context, clip_length, processing_mode, file_duration, progress_callback, should_cancel, runtime_config, instructions=None) -> tuple[Any, list[dict], int] # returns (relevant_parts, segments_json, clip_limit) ``` Then: ```python if workflow_spec is None or workflow_spec.workflow == "highlights": relevant_parts, segments_json, clip_limit = await VideoService._select_highlight_segments( ..., **({"instructions": workflow_spec.options.instructions} if workflow_spec and workflow_spec.options.instructions else {})) workflow_result = None else: if progress_callback: await progress_callback(50, "Reading the whole video...", "processing") transcript_data = load_cached_transcript_data(video_path) # BEFORE planning units_fp = units_fingerprint(transcript_data, transcript) # workflows.units workflow_result = WorkflowResult.from_cache_json(cached_analysis_json, workflow_spec.workflow, units_fp) if workflow_result is None: ctx = PlanContext(spec=workflow_spec, task_id=task_id, transcript_text=transcript, transcript_data=transcript_data, source_seconds=file_duration, cleanup_settings=cleanup_settings or {}, performance_context=performance_context, progress=lambda p, m: progress_callback(p, m, "processing") if progress_callback else _noop(), plan_cache=plan_cache, outline_cache_key=outline_cache_key) workflow_result = await plan_workflow(ctx) segments_json = [dict(s) for s in workflow_result.segments] clip_limit = len(segments_json) relevant_parts = None ``` `progress` must check cancellation: the wrapper calls `should_cancel()` first and raises `Exception("Task cancelled")` if set (the update_progress callback already raises `TaskCancelled` when the row moved). **Section download** (:1201–1246): unchanged code; correctness comes from the `ranges_from_segments` fix (§14.5). **Static-picture check** (:1248–1255): - highlights and topic: `_drop_static_segments` as today, then `[:clip_limit]`. For topic, `clip_limit = len(selected)` and the planner returns up to 4 reserve segments flagged `workflow_meta.reserve = True` after the selected ones; the cut keeps the first `clip_limit` non-dropped ones. - Fix for planned single-range segments: `_drop_static_segments` must read `source_ranges` when present (`ranges = segment.get("source_ranges") or [(start, end)]`) before calling `local_ranges_for`. For legacy segments behaviour is unchanged. - series: skip; for each part, log a warning if `is_visually_static` over its ranges (no drop). - recap/trailer: new `VideoService._drop_static_ranges(video_path, segment) -> segment`. For each range index whose static check is true (same helpers, per range), if the range belongs to a *droppable* point/beat (`workflow_meta.points[*].droppable` / beats not `cold_open`/`button`) **and** the remaining estimated duration stays ≥ budget minimum, remove it (and its junction fade, and renumber `range_index` in meta); otherwise keep it. Never drop below 2 ranges. - The final `segments_json[:max(1, clip_limit)]` applies to highlights and topic only. **Return dict additions**: `"workflow_plan": workflow_result.plan if workflow_result else None`. For workflows `"analysis_json": workflow_result.to_cache_json()`, `"summary": workflow_result.summary`, `"key_topics": workflow_result.key_topics`. ### 5.3 Render loop (`task_service.py:545–624`, WP4) ```python noun = {"series": "part", "recap": "recap", "trailer": "trailer"}.get(spec.workflow, "clip") for i, segment in enumerate(segments_to_render): await check_cancelled() await update_progress(clip_progress, f"Creating {noun} {i + 1}/{total_clips}...") render_segment = localize_segment(segment, time_map) if time_map else segment max_clip = float(segment.get("max_seconds") or clip_duration(clip_length).maximum) clip_info = await self.video_service.create_single_clip(..., max_clip_seconds=max_clip, ...) if clip_info is None and segment.get("required"): clip_info = await self.video_service.create_single_clip(..., same args ...) # one retry if clip_info is None: raise WorkflowError("render_incomplete", _render_failure_message(spec, segment)) pending_clip_path = ... if clip_info is None: continue if time_map: clip_info = await run_in_thread(restore_clip_timeline, clip_info, time_map, segment) meta = dict(segment.get("workflow_meta") or {}) if segment.get("planned"): bounds = source_range_bounds(normalize_source_ranges(segment["source_ranges"])) # ORIGINAL timeline clip_info["start_time"], clip_info["end_time"] = seconds_to_mmss(bounds[0]), seconds_to_mmss(bounds[1]) _fill_output_starts(meta, clip_info.get("group_output_starts")) # points/beats output_start create_clip(..., clip_order=i + 1, workflow_role=segment.get("workflow_role"), part_number=segment.get("part_number"), workflow_meta=meta or None) ``` - `_render_failure_message`: series "Part {n} couldn't be rendered. Please try again.", recap "We couldn't render your recap. Please try again.", trailer "We couldn't render your trailer. Please try again.". - For series, `clip_order == part_number` because parts are never skipped. - After the loop, if `workflow_result` has `points`/`beats`, update `workflow_plan.points[*].output_start` / `beats[*].output_start` from the clip's meta and call `save_workflow_plan` again. --- ## 6. Units: the sentence-indexed transcript (`backend/src/workflows/units.py`, `language.py`, WP2) ### 6.1 Data model ```python @dataclass(frozen=True) class Word: # seconds, after repair_word_timings text: str; start: float; end: float; speaker: Optional[str] @dataclass(frozen=True) class Unit: id: int # 1-based, stable for a given sidecar + granularity w0: int; w1: int # inclusive indexes into UnitIndex.words; -1 for coarse units start: float; end: float # first word start, last word end (seconds) speaker: Optional[str] text: str end_kind: Literal["sentence", "speaker", "pause", "clause", "forced", "line", "eof"] gap_after: float # silence to the next unit's first word (0 for last) starts_sentence: bool ends_question: bool @dataclass class UnitIndex: units: list[Unit]; words: list[Word] granularity: Literal["sentence", "clause"] language: Optional[str] # ISO 639-1 from transcript_data["language_code"], or detected script ("zh"/"ja"/...) or None coarse: bool fingerprint: str def unit(self, uid: int) -> Unit # raises KeyError if out of range def clamp_id(self, uid: int) -> int # into [1, len] def range_seconds(self, first: int, last: int) -> tuple[float, float] def ranges_for(self, first: int, last: int, skips: list[tuple[int, int]] = ()) -> list[tuple[float, float]] def text(self, first: int, last: int, skips=()) -> str def speech_seconds(self, first: int, last: int, skips=(), cleanup: dict | None = None) -> float def boundary_strength(self, uid: int) -> float # strength of the gap AFTER unit uid def unit_at(self, seconds: float) -> int # unit containing / nearest after t def listing(self, ids: Iterable[int] | None = None, *, with_durations=True) -> str def build_units(transcript_data: Optional[dict], transcript_text: str, *, granularity: Literal["sentence", "clause"] = "sentence") -> UnitIndex def units_fingerprint(transcript_data: Optional[dict], transcript_text: str) -> str ``` ### 6.2 Word preparation 1. `raw = transcript_data["words"]` (ms ints; keys `text,start,end,confidence,speaker`). 2. `repaired = timeline.repair_word_timings(raw)` (works in int ms). 3. Convert: `Word(text=w["text"].strip(), start=w["start"]/1000, end=w["end"]/1000, speaker=w.get("speaker"))`. Drop words with empty text. Keep order. ### 6.3 Splitting rules (sentence granularity) `language.py`: ```python SENTENCE_END_RE = re.compile(r"""(?:[.!?。!?…‼⁇⁈⁉؟۔।॥։።፧]|\.{3})["'”’»)\]}」』)]*$""") CLAUSE_MARK_RE = re.compile(r"""[,;:—–、,;:]["'”’»)\]}」』)]*$""") QUESTION_END_RE = re.compile(r"""[??؟]["'”’»)\]}」』)]*$""") NO_SPACE_LANGS = {"zh", "ja", "th", "lo", "km", "my", "yue"} def is_no_space(language: str | None, sample_text: str) -> bool # lang in set, or > 50% CJK/Thai chars ``` `media/common.SENTENCE_END_RE` is **not** changed (highlights must not change). A unit ends after word *i* when the first of these holds: - (a) `SENTENCE_END_RE` matches word *i* → `sentence` - (b) word *i+1* has a different non-null speaker → `speaker` - (c) gap to word *i+1* ≥ 0.8 s (`SENTENCE_PAUSE_BOUNDARY_SECONDS`) → `pause` - last word → `eof` Normalization, in order: 1. **Force split**: a unit with > 40 words or > 20 s splits at its largest internal gap ≥ 0.3 s; else after the last word matching `CLAUSE_MARK_RE` in its first 75 %; else at word 40. Repeat until no unit exceeds the limits. New ends are `forced` (or `clause` if split at a clause mark). 2. **Merge fragments**: a unit with < 3 words (no-space languages: < 4 characters) whose `end_kind` is not `sentence` merges into the next unit when the speaker matches and the gap < 0.3 s. 3. `starts_sentence` = first unit, or previous unit's `end_kind` in {sentence, speaker, pause}. 4. Text join: `""` for no-space languages, else `" "` (reuse `transcription._join_transcript_tokens` for spaced languages). **Clause granularity** (trailer): additionally end a unit after a word matching `CLAUSE_MARK_RE` when the gap ≥ 0.25 s, or at any gap ≥ 0.5 s, provided both sides keep ≥ 3 words; force split at 14 words / 7 s. ### 6.4 Seconds and durations (the only place cuts are computed) ```python def _start(i): return timeline._start_before_word(words_as_dicts, units[i].w0, CLIP_START_LEAD_IN_SECONDS) # 0.1 def _end(i): nxt = words[u.w1 + 1].start if u.w1 + 1 < len(words) else None return timeline._padded_clip_end(words[u.w1].end, nxt) # +0.35, never past next.start-0.03 range_seconds(first, last) = (_start(first), _end(last)) ranges_for(first, last, skips): split [first..last] around skipped units -> list of range_seconds per kept run ``` `words_as_dicts` is `[{"start": w.start, "end": w.end}]` (seconds). Import the private helpers directly; add a comment noting the dependency. Because both helpers clamp against neighbouring words, the overlap between part N's end and part N+1's start is always silence (I2, I3). `speech_seconds(first, last, skips, cleanup)` = Σ unit durations of kept units + Σ gaps between consecutive kept units within a run, each gap capped at `0.6` s when `cleanup.cut_long_pauses` is true (else full gap) + 0.45 s edge padding per kept run. This is the estimate every budget uses. A silence over 12 s between two kept units never plays whole, cleanup on or off: `ranges_for` splits the range, keeping 2 s after the last word and 1 s before the next, and the clock counts only those seconds. No word is lost, so I2 and I3 hold. (A held wordless beat may be the best shot; the planner can't see the picture.) ### 6.5 Boundary strength (gap after unit k, 0..1) A silence of 4 s or more makes any cut but a `forced` one at least 0.9: a scene break is a natural part end. | end_kind | base | |---|---| | sentence | 0.75 + 0.25 · min(gap, 2)/2 | | sentence and next speaker differs | max(above, 0.9) | | speaker | 0.6 | | pause | 0.55 | | clause | 0.35 | | forced | 0.1 | | eof | 1.0 | | line (coarse) | 0.8 if text matches SENTENCE_END_RE else 0.6 | `+0.05` if `ends_question` (capped at 1.0). "Strong" means ≥ 0.75. "Usable" means ≥ 0.45. ### 6.6 Coarse fallback (no word sidecar) If `transcript_data` is missing or has no words (e.g. `youtube_captions` provider), build one unit per timed line from `ai._parse_transcript_spans(transcript_text)`: `start/end` from the line seconds, `w0 = w1 = -1`, `end_kind="line"`, `gap_after = next.start - end`. `range_seconds` returns the raw line bounds. `coarse=True`, and every plan gets note `COARSE_TRANSCRIPT`. Clause granularity is not available; trailers use sentence lines. If there are zero timed lines, raise `WorkflowError("transcript_untimed", "This video's transcript has no timings, so it can't be cut precisely. Try uploading the file instead.")`. ### 6.7 Listing format (what the model sees) ``` #412 41:20 +3.2s B: And that's when the bank called. #413 41:24 +1.1s Twice. ⏸1.8s #414 41:27 +2.4s A: What did you do? ··· 4:12 not shown ··· ``` - Time is `M:SS`, or `H:MM:SS` from one hour. Duration to one decimal. - Speaker label only when it changes (and on the first line of a listing or after a "not shown" marker). - `⏸Xs` appended when `gap_after ≥ 1.5`. - `listing(ids)` with a subset emits `··· {duration} not shown ···` between non-adjacent ids. `units_fingerprint` = sha256 of `"|".join(f"{w.text}:{w.start:.2f}:{w.end:.2f}")` over words (coarse: over lines) plus granularity-independent version tag `units-v1`. ### 6.8 Language helpers (`language.py`) ```python LANGUAGE_NAMES = {"en": "English", "de": "German", "es": "Spanish", "pt": "Portuguese", "fr": "French", "it": "Italian", "nl": "Dutch", "id": "Indonesian", "tr": "Turkish", "pl": "Polish", "ru": "Russian", "hi": "Hindi", "ja": "Japanese", "zh": "Chinese", "ko": "Korean", "ar": "Arabic", ...} def language_name(code: str | None) -> str # unknown -> "the language the speakers mainly use" PART_LABEL = {"en": "Part {n}", "de": "Teil {n}", "es": "Parte {n}", "pt": "Parte {n}", "it": "Parte {n}", "fr": "Partie {n}", "nl": "Deel {n}", "id": "Bagian {n}", "tr": "Bölüm {n}", "pl": "Część {n}", "ru": "Часть {n}", "hi": "भाग {n}", "ja": "パート{n}", "zh": "第{n}部分", "ko": "{n}부", "ar": "الجزء {n}"} def part_label(code: str | None, n: int) -> str # default English BACK_REFERENCE_OPENERS = { # lowercase, matched at unit start after stripping punctuation; en/de/es/pt/fr "en": ("as i said", "like i said", "that's why", "and that", "so that", "which is why", "this is why", "he ", "she ", "they ", "it ", "that ", "this ", "those "), "de": ("wie gesagt", "deshalb", "darum", "und das", "er ", "sie ", "es ", "das ", "dies "), "es": ("como dije", "por eso", "y eso", "él ", "ella ", "eso ", "esto "), "pt": ("como eu disse", "por isso", "e isso", "ele ", "ela ", "isso ", "isto "), "fr": ("comme je disais", "c'est pour ça", "et ça", "il ", "elle ", "ça ", "cela "), } def opens_with_back_reference(text: str, code: str | None) -> bool # False for other languages ``` --- ## 7. LLM plumbing (`backend/src/workflows/llm.py`, `prompts.py`, `schemas.py`, WP3) ### 7.1 Agent factory ```python def build_agent(output_type: type[BaseModel], system_prompt: str, *, structural: bool) -> Agent: cfg = get_config(); apply_settings_to_process_env(cfg) model_name = cfg.rerank_llm if structural else cfg.llm if (err := ai._get_missing_llm_key_error(model_name, cfg)): raise RuntimeError(err) # cache by (output_type.__name__, sha256(system_prompt), model_name, key signature) like ai.get_rerank_agent (:642) model = ai._build_transcript_model(cfg, model_name) out = NativeOutput(output_type, strict=True) if ai._uses_native_output(model_name) else output_type return Agent(model=model, output_type=out, system_prompt=system_prompt, output_retries=2) ``` ### 7.2 Runner `run(agent, prompt, *, timeout=600)` = `await ai._run_transcript_analysis(agent, prompt, timeout)` (transient retries, deadlines, privacy-safe logging). Record `result.usage()` per stage into `plan["stats"]`. ### 7.3 Repair ```python async def run_with_repair(agent, prompt: str, validate: Callable[[T], list[str]], *, timeout=600) -> tuple[T, list[str]]: first = (await run(agent, prompt, timeout=timeout)).output issues = validate(first) if not issues or len(issues) > 15: return first, issues repair = (prompt + "\n\nYOUR PREVIOUS ANSWER:\n" + first.model_dump_json() + "\n\nIT BREAKS THESE RULES:\n- " + "\n- ".join(issues) + "\n\nReturn the complete corrected answer in the same format. Change only what is needed to fix these problems.") second = (await run(agent, repair, timeout=timeout)).output second_issues = validate(second) return (second, second_issues) if len(second_issues) <= len(issues) else (first, issues) ``` Residual issues are handled by the deterministic solver of each planner. ### 7.4 Schema rules - **Required fields only.** No `Optional`, no defaults. Sentinels: `-1` for "no id", `""` for "no text", `[]` for "none". - Short `Literal` enums (≤ 8 values). No verbatim transcript echo: text is grounded in code. - A free-text analysis field comes **first** in every plan schema ("think first"). - `backend/tests/unit/test_workflow_schemas.py` asserts `len(json.dumps(Model.model_json_schema())) < 6000` for every model and that no field has a default. - Integer fields are clamped/validated in code, never trusted. ### 7.5 Shared prompt fragments (`prompts.py`) **`PREAMBLE`** (prefix of every workflow system prompt): ``` You are the lead editor at a top short-form video studio. You plan edits for TikTok, Reels and Shorts from a transcript that has been split into numbered units. HOW THE TRANSCRIPT IS SHOWN Each line is one unit: "#