Skip to content

Open-source AI podcast clipper. Generate vertical clips with face tracking and burned-in captions. CLI, MCP server, web app.

Select clips for the format they will be rendered in (#163)

Nika Siradzed303757b3dfd
diff --git a/backend/cli.py b/backend/cli.py
index 5cd12a7..d7c8f66 100644
--- a/backend/cli.py
+++ b/backend/cli.py
@@ -73,7 +73,7 @@ def _reveal_in_os(path: str) -> None:
from config.paths import paths
from config.server import DEFAULT_PORT, resolve_web_server_port, web_server_url
-from presets import MIN_CLIP_DURATION, MAX_CLIP_DURATION, TARGET_CLIP_DURATION_MIN, TARGET_CLIP_DURATION_MAX
+from presets import DEFAULT_PRESET, MIN_CLIP_DURATION, MAX_CLIP_DURATION, TARGET_CLIP_DURATION_MIN, TARGET_CLIP_DURATION_MAX
from services.knowledge_base import is_empty as kb_is_empty, kb_files
@@ -100,6 +100,20 @@ def _suggestions_session_path(cache_hash: str) -> str:
return os.path.join(paths["home"], "sessions", f"clips-{cache_hash}.json")
+def _explicit_clip_bounds(config: dict) -> tuple[int | None, int | None]:
+ """Duration bounds the user actually chose, or (None, None).
+
+ config is seeded from DEFAULT_PRESET, which carries the vertical numbers,
+ so passing them through unconditionally would override every other format
+ with 20-45s and make --format horizontal a no-op for selection.
+ """
+ out = []
+ for key in ("min_clip_duration", "max_clip_duration"):
+ value = config.get(key)
+ out.append(value if value != DEFAULT_PRESET.get(key) else None)
+ return out[0], out[1]
+
+
def _selection_signature(config: dict) -> str:
"""Everything that changes which clips get selected.
@@ -981,7 +995,7 @@ def cmd_process(args):
# Try an AI CLI first (uses PodStack knowledge base for intelligent selection)
from services import ai_provider
from services.ai_cli import _engine_label
- from services.claude_suggest import select_clips_with_signal_scores, suggest_initial_with_claude
+ from services.claude_suggest import ClipBounds, select_clips_with_signal_scores, suggest_initial_with_claude
providers = ai_provider.status()["providers"]
if clips:
@@ -995,6 +1009,7 @@ def cmd_process(args):
top_n=candidate_top_n,
progress_callback=lambda pct, msg: print(f" {msg}") if msg else None,
reaction_times=reaction_times,
+ bounds=ClipBounds.of(config.get("format"), *_explicit_clip_bounds(config)),
)
if clips:
clips = select_clips_with_signal_scores(
diff --git a/backend/main.py b/backend/main.py
index d4f0a14..086f914 100644
--- a/backend/main.py
+++ b/backend/main.py
@@ -690,6 +690,7 @@ def handle_suggest_clips(task_id: str, params: dict):
"""AI-powered clip suggestion using Claude/Codex and PodStack knowledge base."""
from services import ai_provider
from services.claude_suggest import (
+ ClipBounds,
select_clips_with_signal_scores,
suggest_initial_with_claude,
)
@@ -697,6 +698,11 @@ def handle_suggest_clips(task_id: str, params: dict):
segments = params.get("segments", [])
top_n = params.get("top_n", 5)
existing_clips = params.get("existing_clips", [])
+ bounds = ClipBounds.of(
+ params.get("format"),
+ params.get("min_duration"),
+ params.get("max_duration"),
+ )
if not segments:
emit_result(task_id, "error", error="segments is required")
@@ -725,6 +731,7 @@ def handle_suggest_clips(task_id: str, params: dict):
progress_callback=lambda pct, msg: emit_progress(task_id, "suggesting", pct, msg),
error_sink=errors,
reaction_times=reaction_times,
+ bounds=bounds,
)
if clips is None:
diff --git a/backend/services/claude_suggest.py b/backend/services/claude_suggest.py
index a33d68f..123d249 100644
--- a/backend/services/claude_suggest.py
+++ b/backend/services/claude_suggest.py
@@ -22,6 +22,7 @@ from services.audio_events import compute_event_scores, dominant_reaction
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from presets import DEFAULT_PRESET, MIN_CLIP_DURATION, MAX_CLIP_DURATION, TARGET_CLIP_DURATION_MIN, TARGET_CLIP_DURATION_MAX
+from services.formats import get_format
from utils.text import clean_title
from services import ai_provider, podcli_cloud
from services.ai_cli import (
@@ -78,6 +79,38 @@ def _load_existing_shorts(episodes_path: str) -> list[str]:
# (filename, max_chars) that reach the selection prompt, highest priority first.
# Shared with kb_signature so the suggestion cache and the prompt cannot drift.
+class ClipBounds:
+ """Duration bounds and prompt framing for one output format.
+
+ formats.py calls itself the single source of truth for duration bounds and
+ every consumer honoured that except the one deciding which moments get
+ picked. Explicit overrides still win, so a Studio slider or a preset can
+ narrow a format without redefining it.
+ """
+
+ __slots__ = ("dur_min", "dur_max", "target_min", "target_max", "editor", "pacing", "lens")
+
+ def __init__(self, spec, dur_min=None, dur_max=None):
+ self.dur_min = int(dur_min) if dur_min else spec.dur_min
+ self.dur_max = int(dur_max) if dur_max else spec.dur_max
+ if self.dur_max < self.dur_min:
+ self.dur_min, self.dur_max = spec.dur_min, spec.dur_max
+ self.target_min = max(spec.target_min, self.dur_min)
+ self.target_max = min(spec.target_max, self.dur_max)
+ if self.target_max < self.target_min:
+ self.target_min, self.target_max = self.dur_min, self.dur_max
+ self.editor = spec.editor
+ self.pacing = spec.pacing
+ self.lens = spec.lens
+
+ @classmethod
+ def of(cls, fmt=None, dur_min=None, dur_max=None) -> "ClipBounds":
+ return cls(get_format(fmt), dur_min, dur_max)
+
+ def keeps(self, seconds: float) -> bool:
+ return self.dur_min <= seconds <= self.dur_max
+
+
KB_FILES = [
("04-shorts-creation-guide.md", 4000), # moment selection criteria, content types
("05-title-formulas.md", 3000), # title rules, shapes, banned openers
@@ -160,6 +193,7 @@ def _build_prompt(
top_n: int,
exclude_clips: list[dict] | None = None,
reaction_times: list[float] | None = None,
+ bounds: "ClipBounds | None" = None,
) -> str:
"""Build the prompt for Claude to extract clips.
@@ -194,7 +228,8 @@ def _build_prompt(
+ "\n".join(lines)
)
- return f"""You are a viral clip editor for TikTok and YouTube Shorts. Find the {top_n} most scroll-stopping moments in this podcast transcript.
+ b = bounds or ClipBounds.of()
+ return f"""You are {b.editor}. Find the {top_n} most scroll-stopping moments in this podcast transcript.
IMPORTANT: Return ONLY valid JSON. No markdown, no explanation, no code fences.
@@ -202,11 +237,11 @@ TIMESTAMP FORMAT: All timestamps in the transcript are in SECONDS (e.g., [123.4s
All timestamps you return MUST be in SECONDS as numbers (e.g., 123.4), NOT minutes:seconds.
DURATION RULES (CRITICAL):
-- Target: {TARGET_CLIP_DURATION_MIN}-{TARGET_CLIP_DURATION_MAX} seconds (this is the viral sweet spot)
-- Maximum: {MAX_CLIP_DURATION} seconds (anything longer still renders, but gets flagged as over target)
-- Minimum: {MIN_CLIP_DURATION} seconds (too short = no payoff)
-- SHORTER IS BETTER. A punchy 25s clip outperforms a 40s clip every time.
-- If a thought takes longer than {TARGET_CLIP_DURATION_MAX}s, use segments to cut the filler in the middle
+- Target: {b.target_min}-{b.target_max} seconds (this is the sweet spot)
+- Maximum: {b.dur_max} seconds (anything longer still renders, but gets flagged as over target)
+- Minimum: {b.dur_min} seconds (too short = no payoff)
+- {b.pacing}
+- If a thought takes longer than {b.target_max}s, use segments to cut the filler in the middle
CUTTING RULES (CRITICAL):
- Cut TIGHT. Every second must earn its place.
@@ -215,9 +250,9 @@ CUTTING RULES (CRITICAL):
- NEVER cut mid-sentence or mid-thought. The viewer must feel closure.
- The last sentence must feel like a natural ending, a punchline, or a mic-drop
- If there's filler/tangent in the middle, use multiple segments to skip it
-- A 30s clip with zero dead weight beats a {MAX_CLIP_DURATION}s clip with fluff
+- A tight clip with zero dead weight beats a {b.dur_max}s clip with fluff
-MOMENT SELECTION (think like a TikTok editor):
+MOMENT SELECTION ({b.lens}):
- Would YOU stop scrolling for this? If no, skip it.
- First 3 seconds must HOOK — a bold claim, shocking number, or provocative question
- Must make complete sense standalone — no "as I mentioned" or "going back to"
@@ -272,7 +307,7 @@ SEGMENTS RULES:
- Example: speaker makes great point (10s), rambles (8s), delivers punchline (12s) → 2 segments, 22s total
Rules:
-- Final clip duration (sum of segments) MUST be {MIN_CLIP_DURATION}-{MAX_CLIP_DURATION} seconds (target {TARGET_CLIP_DURATION_MIN}-{TARGET_CLIP_DURATION_MAX}s)
+- Final clip duration (sum of segments) MUST be {b.dur_min}-{b.dur_max} seconds (target {b.target_min}-{b.target_max}s)
- Each segment must start and end on COMPLETE SENTENCES — never mid-thought
- The LAST segment must end on a sentence that feels like a natural conclusion
- Must make sense standalone when stitched together
@@ -404,12 +439,14 @@ def find_moments_from_text(
existing_clips: Optional[list[dict]] = None,
progress_callback: Optional[Callable[[int, str], None]] = None,
max_results: int = 3,
+ bounds: ClipBounds | None = None,
) -> list[dict]:
"""Locate the moment(s) the user described/pasted in the transcript.
Returns clip dicts (same shape as suggest_with_claude). Status goes to
progress_callback; warnings to stderr — never stdout, which is the task
runner's JSON-RPC channel."""
existing_clips = existing_clips or []
+ bounds = bounds or ClipBounds.of()
if not ai_provider.available():
print("No AI available for moment search", file=sys.stderr, flush=True)
return []
@@ -434,7 +471,7 @@ RULES:
- The user may list several moments — return one clip per distinct moment they mention
- Return 1-{upper} matching moments (best match first)
- All timestamps in SECONDS as numbers
-- Duration target: {TARGET_CLIP_DURATION_MIN}-{TARGET_CLIP_DURATION_MAX} seconds, max {MAX_CLIP_DURATION} seconds
+- Duration target: {bounds.target_min}-{bounds.target_max} seconds, max {bounds.dur_max} seconds
- Cut tight: start at the hook, end when the point lands
- Use segments to cut filler if needed
@@ -488,7 +525,7 @@ Transcript:
keep_segments = [{"start": start_sec, "end": end_sec}]
kept_duration = sum(seg["end"] - seg["start"] for seg in keep_segments)
- if kept_duration < MIN_CLIP_DURATION or kept_duration > MAX_CLIP_DURATION:
+ if not bounds.keeps(kept_duration):
continue
found.append({
@@ -526,6 +563,7 @@ def suggest_with_claude(
timeout: int = 900,
error_sink: Optional[list[str]] = None,
reaction_times: list[float] | None = None,
+ bounds: ClipBounds | None = None,
) -> Optional[list[dict]]:
"""
Use an AI CLI (Claude Code or Codex) to extract the best clip moments.
@@ -536,6 +574,7 @@ def suggest_with_claude(
providers = ai_provider.status()["providers"]
if not providers:
return None
+ bounds = bounds or ClipBounds.of()
if progress_callback:
progress_callback(0, f"Preparing transcript for {providers[0]['label']}...")
@@ -554,6 +593,7 @@ def suggest_with_claude(
top_n,
exclude_clips=exclude_clips,
reaction_times=reaction_times,
+ bounds=bounds,
)
project_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")
@@ -689,7 +729,7 @@ def suggest_with_claude(
keep_segments = [{"start": start_sec, "end": end_sec}]
kept_duration = sum(seg["end"] - seg["start"] for seg in keep_segments)
- if kept_duration < MIN_CLIP_DURATION or kept_duration > MAX_CLIP_DURATION:
+ if not bounds.keeps(kept_duration):
continue
normalized.append({
@@ -739,6 +779,7 @@ def suggest_initial_with_claude(
progress_callback: Optional[Callable[[int, str], None]] = None,
error_sink: Optional[list[str]] = None,
reaction_times: list[float] | None = None,
+ bounds: ClipBounds | None = None,
) -> Optional[list[dict]]:
"""
Initial clip discovery entry point.
@@ -757,6 +798,7 @@ def suggest_initial_with_claude(
error_sink=error_sink,
timeout=180,
reaction_times=reaction_times,
+ bounds=bounds,
)
start_bound = float(segments[0].get("start", 0))
@@ -789,6 +831,7 @@ def suggest_initial_with_claude(
error_sink=error_sink,
timeout=180,
reaction_times=reaction_times,
+ bounds=bounds,
)
if progress_callback:
@@ -822,6 +865,7 @@ def suggest_initial_with_claude(
reaction_times=[
t for t in (reaction_times or []) if bucket["start"] <= t <= bucket["end"]
] or None,
+ bounds=bounds,
)
if not bucket_clips:
continue
@@ -846,6 +890,7 @@ def suggest_initial_with_claude(
error_sink=error_sink,
timeout=120,
reaction_times=reaction_times,
+ bounds=bounds,
)
if fallback_clips:
deduped = _dedupe_clips_by_range(deduped + fallback_clips)
@@ -1034,6 +1079,7 @@ def suggest_more_with_claude(
existing_clips: list[dict],
top_n: int = 8,
progress_callback: Optional[Callable[[int, str], None]] = None,
+ bounds: ClipBounds | None = None,
) -> Optional[list[dict]]:
"""
Ask the AI for more clips by searching under-covered time buckets first.
@@ -1075,6 +1121,7 @@ def suggest_more_with_claude(
top_n=top_n,
exclude_clips=existing_clips,
progress_callback=progress_callback,
+ bounds=bounds,
)
buckets.sort(key=lambda b: (b["coverage_ratio"], b["coverage_seconds"], b["start"]))
@@ -1100,6 +1147,7 @@ def suggest_more_with_claude(
f"{bucket_label}: {msg}" if msg else msg,
)
),
+ bounds=bounds,
)
if not bucket_clips:
continue
@@ -1125,6 +1173,7 @@ def suggest_more_with_claude(
f"{bucket_label}: {msg}" if msg else msg,
)
),
+ bounds=bounds,
)
if not bucket_clips:
continue
@@ -1145,6 +1194,7 @@ def suggest_more_with_claude(
f"global pass: {msg}" if msg else msg,
)
),
+ bounds=bounds,
)
if fallback_clips:
aggregated.extend(fallback_clips)
diff --git a/backend/services/formats.py b/backend/services/formats.py
index b749e3c..458c5ae 100644
--- a/backend/services/formats.py
+++ b/backend/services/formats.py
@@ -20,7 +20,13 @@ class FormatSpec:
dur_max: int
target_min: int
target_max: int
- score_key: str
+ # How the selection prompt should frame the job. Substituting only the
+ # numbers into a shorts-shaped prompt produces a self-contradicting ask:
+ # "SHORTER IS BETTER" next to a 90-240s target, and the model splits the
+ # difference.
+ editor: str
+ pacing: str
+ lens: str
@property
def dims(self) -> tuple[int, int]:
@@ -39,7 +45,9 @@ FORMATS = {
caption_profile="vertical",
dur_min=20, dur_max=45,
target_min=20, target_max=35,
- score_key="vertical_score",
+ editor="a viral clip editor for TikTok and YouTube Shorts",
+ pacing="SHORTER IS BETTER. A punchy 25s clip outperforms a 40s clip every time.",
+ lens="think like a TikTok editor",
),
"horizontal": FormatSpec(
name="horizontal",
@@ -48,7 +56,12 @@ FORMATS = {
caption_profile="lower_third",
dur_min=60, dur_max=300,
target_min=90, target_max=240,
- score_key="horizontal_score",
+ editor="an editor cutting standalone segments out of a long-form show",
+ pacing=(
+ "A complete arc beats a short one. Give the point room to land, "
+ "then cut everything that does not serve it."
+ ),
+ lens="think like a long-form editor",
),
"square": FormatSpec(
name="square",
@@ -57,7 +70,9 @@ FORMATS = {
caption_profile="center",
dur_min=20, dur_max=45,
target_min=20, target_max=35,
- score_key="vertical_score",
+ editor="a viral clip editor for feeds where the frame is square",
+ pacing="SHORTER IS BETTER. A punchy 25s clip outperforms a 40s clip every time.",
+ lens="think like a social editor",
),
}
diff --git a/src/ui/client/EpisodeWorkspace.jsx b/src/ui/client/EpisodeWorkspace.jsx
index 82f84b3..4c76b87 100644
--- a/src/ui/client/EpisodeWorkspace.jsx
+++ b/src/ui/client/EpisodeWorkspace.jsx
@@ -42,6 +42,15 @@ import { PageHeader } from './Page';
import { buildPreviewChunks, activePreviewChunk, selectPreviewWords } from './captionChunks';
import { findClipResult, resultBoundsKey, clipKey, buildEnergyMap, dropEnergy, clampClipIndex, resolveAssetName, formatTranscriptText } from './lib';
+// Mirrors backend/services/formats.py. A horizontal cutdown is minutes long,
+// so a slider capped at 60s could not express one.
+const FORMAT_BOUNDS = {
+ vertical: { min: 20, max: 45, ceiling: 60 },
+ square: { min: 20, max: 45, ceiling: 60 },
+ horizontal: { min: 60, max: 300, ceiling: 360 },
+};
+const boundsFor = (f) => FORMAT_BOUNDS[f] || FORMAT_BOUNDS.vertical;
+
const fmt = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
const fmtSaved = (s) => s < 10 ? `${Number(s || 0).toFixed(1)}s` : fmt(s);
const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());
@@ -785,9 +794,17 @@ const onKeyActivate = (fn) => (e) => {
const [cleanFillers, setCleanFillers] = useState(true);
const [quality, setQuality] = useState('max');
const [topClips, setTopClips] = useState(8);
- const [minDuration, setMinDuration] = useState(20);
- const [maxDuration, setMaxDuration] = useState(45);
+ const [minDuration, setMinDuration] = useState(boundsFor("vertical").min);
+ const [maxDuration, setMaxDuration] = useState(boundsFor("vertical").max);
const [energyBoost, setEnergyBoost] = useState(true);
+
+ // A vertical 20-45s window means nothing to a horizontal cutdown, so the
+ // sliders follow the format rather than pinning it back to shorts length.
+ useEffect(() => {
+ const b = boundsFor(format);
+ setMinDuration(b.min);
+ setMaxDuration(b.max);
+ }, [format]);
const [showYouTubeFrame, setShowYouTubeFrame] = useState(true);
const [silenceThreshold, setSilenceThreshold] = useState(0.5);
const [silenceMinPause, setSilenceMinPause] = useState(0.65);
@@ -2305,14 +2322,14 @@ const onKeyActivate = (fn) => (e) => {
<div className="field">
<label className="field-label">Min duration</label>
<div className="field-row">
- <input type="range" min="10" max="60" step="5" value={minDuration} onChange={e => setMinDuration(parseInt(e.target.value))} />
+ <input type="range" min="10" max={boundsFor(format).ceiling} step="5" value={minDuration} onChange={e => setMinDuration(parseInt(e.target.value))} />
<span className="range-value">{minDuration}s</span>
</div>
</div>
<div className="field">
<label className="field-label">Max duration</label>
<div className="field-row">
- <input type="range" min="30" max="60" step="5" value={maxDuration} onChange={e => setMaxDuration(parseInt(e.target.value))} />
+ <input type="range" min="30" max={boundsFor(format).ceiling} step="5" value={maxDuration} onChange={e => setMaxDuration(parseInt(e.target.value))} />
<span className="range-value">{maxDuration}s</span>
</div>
</div>
diff --git a/src/ui/web-server.ts b/src/ui/web-server.ts
index 14234ce..48c802a 100644
--- a/src/ui/web-server.ts
+++ b/src/ui/web-server.ts
@@ -3477,6 +3477,9 @@ app.post("/api/claude-suggest", async (req, res) => {
if (suggestVideo) params.video_path = suggestVideo;
if (min_duration) params.min_duration = min_duration;
if (max_duration) params.max_duration = max_duration;
+ // Duration bounds are per-format, so the numbers above mean nothing without it.
+ const suggestFormat = (uiState.settings as Record<string, unknown> | undefined)?.format;
+ if (suggestFormat) params.format = suggestFormat;
const result = await executor.execute<{ clips?: SuggestedClip[] }>(
"suggest_clips",
params,
diff --git a/tests/test_ai_fallback.py b/tests/test_ai_fallback.py
index f9f2ff9..4d49739 100644
--- a/tests/test_ai_fallback.py
+++ b/tests/test_ai_fallback.py
@@ -96,7 +96,7 @@ class AIFallbackTests(unittest.TestCase):
calls = []
- def fake_suggest(*, segments, top_n, exclude_clips=None, progress_callback=None):
+ def fake_suggest(*, segments, top_n, exclude_clips=None, progress_callback=None, **_kw):
calls.append({
"start": segments[0]["start"],
"end": segments[-1]["end"],
@@ -142,7 +142,7 @@ class AIFallbackTests(unittest.TestCase):
calls = []
- def fake_suggest(*, segments, top_n, exclude_clips=None, progress_callback=None):
+ def fake_suggest(*, segments, top_n, exclude_clips=None, progress_callback=None, **_kw):
calls.append({
"start": segments[0]["start"],
"end": segments[-1]["end"],
@@ -183,7 +183,7 @@ class AIFallbackTests(unittest.TestCase):
calls = []
- def fake_suggest(*, segments, top_n, exclude_clips=None, progress_callback=None, timeout=300, error_sink=None, reaction_times=None):
+ def fake_suggest(*, segments, top_n, exclude_clips=None, progress_callback=None, timeout=300, error_sink=None, reaction_times=None, **_kw):
calls.append({
"start": segments[0]["start"],
"end": segments[-1]["end"],
diff --git a/tests/test_claude_suggest_helpers.py b/tests/test_claude_suggest_helpers.py
index d0ffb22..3dd6f00 100644
--- a/tests/test_claude_suggest_helpers.py
+++ b/tests/test_claude_suggest_helpers.py
@@ -366,3 +366,66 @@ class CaptionStyleTests(unittest.TestCase):
def test_a_missing_knowledge_base_falls_back(self):
self.assertEqual(cs._preferred_caption_style("/nonexistent"), "branded")
+
+
+class ClipBoundsTests(unittest.TestCase):
+ def test_vertical_is_the_shorts_window(self):
+ b = cs.ClipBounds.of("vertical")
+ self.assertEqual((b.dur_min, b.dur_max), (20, 45))
+ self.assertIn("SHORTER IS BETTER", b.pacing)
+
+ def test_horizontal_is_minutes_not_seconds(self):
+ b = cs.ClipBounds.of("horizontal")
+ self.assertEqual((b.dur_min, b.dur_max), (60, 300))
+ self.assertEqual((b.target_min, b.target_max), (90, 240))
+ self.assertNotIn("SHORTER IS BETTER", b.pacing)
+
+ def test_an_explicit_override_narrows_the_format(self):
+ b = cs.ClipBounds.of("horizontal", 90, 120)
+ self.assertEqual((b.dur_min, b.dur_max), (90, 120))
+ self.assertTrue(b.dur_min <= b.target_min <= b.target_max <= b.dur_max)
+
+ def test_an_inverted_override_falls_back_to_the_format(self):
+ b = cs.ClipBounds.of("vertical", 90, 30)
+ self.assertEqual((b.dur_min, b.dur_max), (20, 45))
+
+ def test_an_unknown_format_falls_back_rather_than_raising(self):
+ b = cs.ClipBounds.of("hexagonal")
+ self.assertEqual((b.dur_min, b.dur_max), (20, 45))
+
+ def test_keeps_is_inclusive_at_both_ends(self):
+ b = cs.ClipBounds.of("vertical")
+ self.assertTrue(b.keeps(20))
+ self.assertTrue(b.keeps(45))
+ self.assertFalse(b.keeps(19.9))
+ self.assertFalse(b.keeps(45.1))
+
+ def test_a_horizontal_length_survives_the_filter_that_used_to_drop_it(self):
+ self.assertFalse(cs.ClipBounds.of("vertical").keeps(120))
+ self.assertTrue(cs.ClipBounds.of("horizontal").keeps(120))
+
+
+class FormatFramingTests(unittest.TestCase):
+ def test_the_prompt_asks_for_the_format_it_will_render(self):
+ prompt = cs._build_prompt(
+ transcript_text="[0.0s] hello",
+ segment_count=1,
+ duration_min=90.0,
+ top_n=3,
+ bounds=cs.ClipBounds.of("horizontal"),
+ )
+ self.assertIn("60", prompt)
+ self.assertIn("90-240 seconds", prompt)
+ self.assertNotIn("SHORTER IS BETTER", prompt)
+ self.assertNotIn("TikTok editor", prompt)
+
+ def test_the_vertical_prompt_is_unchanged_in_substance(self):
+ prompt = cs._build_prompt(
+ transcript_text="[0.0s] hello",
+ segment_count=1,
+ duration_min=30.0,
+ top_n=3,
+ )
+ self.assertIn("20-35 seconds", prompt)
+ self.assertIn("SHORTER IS BETTER", prompt)
+ self.assertIn("TikTok", prompt)
diff --git a/tests/test_cli_helpers.py b/tests/test_cli_helpers.py
index 2ec5ab8..5142956 100644
--- a/tests/test_cli_helpers.py
+++ b/tests/test_cli_helpers.py
@@ -94,3 +94,28 @@ class SelectionSignatureTests(unittest.TestCase):
a = cli_mod._selection_signature({"ai_select": True})
b = cli_mod._selection_signature({"ai_select": True})
self.assertNotEqual(a, b)
+
+
+class ExplicitClipBoundsTests(unittest.TestCase):
+ """config is seeded from DEFAULT_PRESET, which carries the vertical numbers.
+ Forwarding those unconditionally would make --format horizontal a no-op."""
+
+ def test_untouched_preset_values_do_not_override_the_format(self):
+ from presets import DEFAULT_PRESET
+
+ config = {**DEFAULT_PRESET, "format": "horizontal"}
+ self.assertEqual(cli_mod._explicit_clip_bounds(config), (None, None))
+
+ def test_a_value_the_user_changed_is_forwarded(self):
+ from presets import DEFAULT_PRESET
+
+ config = {**DEFAULT_PRESET, "min_clip_duration": 30}
+ self.assertEqual(cli_mod._explicit_clip_bounds(config), (30, None))
+
+ def test_horizontal_selection_uses_the_format_window(self):
+ from presets import DEFAULT_PRESET
+ from services.claude_suggest import ClipBounds
+
+ config = {**DEFAULT_PRESET, "format": "horizontal"}
+ bounds = ClipBounds.of(config["format"], *cli_mod._explicit_clip_bounds(config))
+ self.assertEqual((bounds.dur_min, bounds.dur_max), (60, 300))